From 3871fb42959175bf233b673c0800a905f7274d59 Mon Sep 17 00:00:00 2001
From: 高章伟 <gaozhangwei@prec-tech.com>
Date: 星期二, 15 二月 2022 16:28:59 +0800
Subject: [PATCH] full 最新代码

---
 scr/classes/LoanerTakeBackControllerTest.cls                                      |  495 
 scr/classes/CommunitiesSelfRegController.cls-meta.xml                             |    5 
 scr/pages/SiteTemplate.page-meta.xml                                              |    8 
 scr/classes/EmailComeBackListen.cls                                               |  182 
 scr/classes/LoanerLendDeliverControllerTest.cls                                   |  240 
 scr/classes/NewHighProductsOppControllerTest.cls                                  |   59 
 scr/classes/OrderSplitRatioControllerTest.cls-meta.xml                            |    5 
 scr/classes/LoanerReceiveGoodsControllerTest.cls-meta.xml                         |    5 
 scr/classes/ContactTriggerHandler.cls                                             |  205 
 scr/classes/CertificationDetailTriggerTest.cls                                    |   81 
 scr/classes/QuoteTriggerHandler.cls                                               |  128 
 scr/classes/SendEmailController.cls-meta.xml                                      |    5 
 scr/pages/LoanerReceiveGoods.page                                                 |  128 
 scr/classes/LogAutoSendBatchTest.cls-meta.xml                                     |    5 
 scr/pages/SearchSetProduct.page                                                   |  180 
 scr/classes/LoanerTakeBackController.cls-meta.xml                                 |    5 
 scr/classes/TradeCustomerManagerControllerTest.cls-meta.xml                       |    5 
 scr/classes/OpportunityProductControllerTest.cls                                  |  333 
 scr/classes/SWOControllerTest.cls-meta.xml                                        |    5 
 scr/classes/CustContController.cls-meta.xml                                       |    5 
 scr/classes/BreachRecordBatch.cls-meta.xml                                        |    5 
 scr/pages/SearchProduct.page-meta.xml                                             |    7 
 scr/classes/EquipmentLoanerApplyControllerTest.cls-meta.xml                       |    5 
 scr/triggers/ContactTrigger.trigger-meta.xml                                      |    5 
 scr/classes/SBG004WebServiceTest.cls                                              |  612 
 scr/pages/ChatterAnswersRegistration.page-meta.xml                                |    8 
 scr/classes/ForgotPasswordController.cls-meta.xml                                 |    5 
 scr/pages/orderPage.page-meta.xml                                                 |    7 
 scr/classes/NewLoanerApplicationControllerTest.cls-meta.xml                       |    5 
 scr/classes/SBG018Rest.cls-meta.xml                                               |    5 
 scr/pages/DeliveryConfirmPDF.page                                                 |  269 
 scr/classes/TydelikeAccControllerTest.cls                                         |   60 
 scr/classes/OppTestController.cls                                                 |   38 
 scr/classes/AccountWebServiceTest.cls                                             |  166 
 scr/pages/OrderOpenAlert.page                                                     |  176 
 scr/classes/LoanerExpressTriggerHandlerTest.cls-meta.xml                          |    5 
 scr/classes/NetworkAccess.cls-meta.xml                                            |    5 
 scr/classes/AssetTurnoverSchedulable.cls                                          |    7 
 scr/classes/StaticParameterTest.cls                                               |   10 
 scr/classes/AgentContributionArticleController.cls-meta.xml                       |    5 
 scr/pages/CanNotEditOrDelete.page                                                 |    6 
 scr/classes/LogAutoSendScheduleTest.cls-meta.xml                                  |    5 
 scr/pages/IdeasHome.page                                                          |    1 
 scr/staticresources/jquery183minjs.txt                                            |    2 
 scr/classes/CustContController.cls                                                |   59 
 scr/classes/QuotePDFControllerTest.cls                                            |  126 
 scr/triggers/QuoteLineItemTrigger.trigger                                         |   11 
 scr/classes/NewLoanerApplicationController.cls                                    |   99 
 scr/classes/UpdateTotalCostPriceSetTextBatch.cls-meta.xml                         |    5 
 scr/classes/LicenseCheckUtilTest.cls-meta.xml                                     |    5 
 scr/classes/LoanerApplicationStockUpCheckController.cls                           |  210 
 scr/classes/PersonalProcessInstanceControllerTest.cls                             |  161 
 scr/classes/NewQuoteEntryWebServiceTest.cls                                       |   47 
 scr/pages/LoanerApplicationStockDownCheck.page-meta.xml                           |    7 
 scr/pages/SWOPageRead.page                                                        | 1732 
 scr/classes/LoanerOrderState.cls-meta.xml                                         |    5 
 scr/classes/NewLoanerUserControllerTest.cls                                       |  121 
 scr/classes/EquipmentLoanerApplyControllerTest.cls                                |  578 
 scr/pages/LoanerApplicationStockDown.page                                         |   87 
 scr/pages/CommunitiesSelfReg.page-meta.xml                                        |    8 
 scr/classes/TOTPPlugin.cls-meta.xml                                               |    5 
 scr/triggers/UserFaultInfoTrigger.trigger-meta.xml                                |    5 
 scr/classes/AccountWebServiceTest.cls-meta.xml                                    |    5 
 scr/classes/SBG004WebService.cls-meta.xml                                         |    5 
 scr/classes/LoanerPortionReturnControllerTest.cls                                 |  131 
 scr/classes/ChatterAnswers.cls                                                    |    7 
 scr/classes/OrderTriggerTest.cls-meta.xml                                         |    5 
 scr/pages/CampaignRelationship.page                                               |  238 
 scr/classes/ApplicationMessageControllerTest.cls                                  |   79 
 scr/classes/SBG027TriggerHandler.cls                                              |  320 
 scr/classes/RepairDetailsTriggerTest.cls                                          |   42 
 scr/classes/SBG017Rest.cls                                                        |  157 
 scr/classes/SBG017RestTest.cls-meta.xml                                           |    5 
 scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls-meta.xml                   |    5 
 scr/pages/OpportunityPage.page-meta.xml                                           |    7 
 scr/classes/IENewOpportunityController.cls                                        |  138 
 scr/pages/NewQuoteDevide.page-meta.xml                                            |    7 
 scr/classes/SoapApi.cls-meta.xml                                                  |    5 
 scr/classes/SBG019RestTest.cls-meta.xml                                           |    5 
 scr/triggers/ProRegister.trigger-meta.xml                                         |    5 
 scr/pages/SoftwarePhoneInformation.page                                           |  853 
 scr/pages/OpportunityVisitNotes.page                                              |   41 
 scr/pages/LoanerApplicationStockUpCheck.page                                      |  134 
 scr/classes/NewRepairPartsController.cls-meta.xml                                 |    5 
 scr/classes/LogAutoSendScheduleProduct.cls-meta.xml                               |    5 
 scr/classes/SearchManagementControllerTest.cls                                    |   86 
 scr/classes/QuoteTriggerTest.cls                                                  |  306 
 scr/classes/IdentityContextPluginTest.cls-meta.xml                                |    5 
 scr/classes/OpportunityAAdvancedControllerTest.cls-meta.xml                       |    5 
 scr/classes/OpportunityStockAnswer.cls                                            |   23 
 scr/pages/FileNotFound.page                                                       |   35 
 scr/classes/CampaignUpsertContactToSapTest.cls                                    |   20 
 scr/pages/NewReplacementOpportunity.page-meta.xml                                 |    7 
 scr/classes/SearchSetProductController.cls                                        |  169 
 scr/classes/TrialCustomerPortalHomePageController.cls                             |   80 
 scr/classes/MicrobatchSelfRegControllerTest.cls                                   |   14 
 scr/staticresources/SWOJS.resource-meta.xml                                       |    6 
 scr/classes/OpportunityMessageController.cls                                      |  117 
 scr/classes/UserViolationsTriggerTest.cls                                         |  162 
 scr/classes/TS_SearchAccountControllerTest.cls-meta.xml                           |    5 
 scr/classes/TydelikeACControllerTest.cls-meta.xml                                 |    5 
 scr/triggers/Product2Triggrt.trigger-meta.xml                                     |    5 
 scr/classes/ContactTriggerHandler.cls-meta.xml                                    |    5 
 scr/classes/OrderPdf2ControllerTest.cls-meta.xml                                  |    5 
 scr/classes/LoanerApplicationStockUpController.cls                                |  148 
 scr/classes/SBGITMWebServiceTest.cls                                              |  185 
 scr/pages/Exception.page-meta.xml                                                 |    8 
 scr/classes/NewOpportunityControllerTest.cls                                      |   82 
 scr/classes/LoanerAppDetailTriggerHandlerTest.cls-meta.xml                        |    5 
 scr/pages/QuotePDF.page-meta.xml                                                  |    7 
 scr/classes/LoanerStockDownCheckControllerTest.cls                                |  142 
 scr/pages/ChatterAnswersLogin.page-meta.xml                                       |    8 
 scr/pages/NewQuoteEntry.page                                                      | 1109 
 scr/classes/EmailComeBackListenTest.cls-meta.xml                                  |    5 
 scr/classes/PartnerSoapSforceCom.cls-meta.xml                                     |    5 
 scr/pages/TradeCustomerManagerSearchOpp.page                                      |   75 
 scr/classes/MyProfilePageController.cls                                           |   75 
 scr/triggers/loanerAppDetStatusUp.trigger-meta.xml                                |    5 
 scr/pages/TradeCustomerManager.page-meta.xml                                      |    7 
 scr/classes/NewQuoteEntryWebService.cls                                           |  129 
 scr/staticresources/PleaseWaitDialog.resource-meta.xml                            |    5 
 scr/classes/OpportunityAAdvancedController.cls                                    |   96 
 scr/pages/scc_tour_style.page-meta.xml                                            |    7 
 scr/pages/OrderInternalMessagePopup.page                                          |   51 
 scr/staticresources/jquery183minjs.resource-meta.xml                              |    5 
 scr/classes/AssetTurnoverBatch.cls                                                |  309 
 scr/classes/OppInternalMessageController.cls                                      |  422 
 scr/pages/OrderApproveAlert2.page                                                 |    9 
 scr/staticresources/StageProgressBarCss.resource-meta.xml                         |    5 
 scr/classes/NewLoanerApplicationController.cls-meta.xml                           |    5 
 scr/classes/ProRegisterHandlerTest.cls-meta.xml                                   |    5 
 scr/triggers/loanerAppStatusUp.trigger-meta.xml                                   |    5 
 scr/staticresources/scc_tour_images.resource-meta.xml                             |    5 
 scr/triggers/OpportunityLineItemTrigger.trigger                                   |   16 
 scr/pages/AnswersHome.page-meta.xml                                               |    8 
 scr/classes/LoanerApplicationStockUpCheckController.cls-meta.xml                  |    5 
 scr/classes/OrderMessageController.cls-meta.xml                                   |    5 
 scr/triggers/BusinessActivityTrigger.trigger-meta.xml                             |    5 
 scr/classes/AllAssetControllerTest.cls                                            |  146 
 scr/classes/OpportunityLineItemTriggerHandler.cls                                 |  233 
 scr/classes/calendarUtilTest.cls                                                  |   45 
 scr/classes/CommunitiesLandingControllerTest.cls                                  |    9 
 scr/classes/SBGCallLogRest.cls-meta.xml                                           |    5 
 scr/classes/TydelikeConController.cls-meta.xml                                    |    5 
 scr/pages/TradeCustomerManager.page                                               |  528 
 scr/staticresources/scc_tour_images/Tour_Images/bg_tour.png                       |    0 
 scr/classes/SBG007TriggerHandler.cls-meta.xml                                     |    5 
 scr/classes/UserFaultInfoHandlerTest.cls-meta.xml                                 |    5 
 scr/classes/MessageBoardController.cls-meta.xml                                   |    5 
 scr/classes/ForgotPasswordControllerTest.cls                                      |   12 
 scr/classes/ChangePasswordControllerTest.cls-meta.xml                             |    5 
 scr/classes/NewRepairPartsControllerTest.cls                                      |   55 
 scr/classes/OlympusCoJpCommonMessage.cls                                          |   48 
 scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls                             |  143 
 scr/triggers/SWOTrigger.trigger                                                   |    8 
 scr/staticresources/tests.resource-meta.xml                                       |    5 
 scr/classes/setOrderShareBatchTest.cls-meta.xml                                   |    5 
 scr/classes/TradeCustomerManagerSearchOppTest.cls                                 |   12 
 scr/staticresources/ServiceCloudLogo.png                                          |    0 
 scr/classes/NFMUtil.cls-meta.xml                                                  |    5 
 scr/staticresources/StageMapJsNew1.resource-meta.xml                              |    5 
 scr/pages/MessageBoard.page                                                       |   40 
 scr/classes/ProRegisterHandler.cls-meta.xml                                       |    5 
 scr/classes/SearchMemberPageController.cls                                        |  114 
 scr/classes/OpportunityWebServiceTest.cls-meta.xml                                |    5 
 scr/pages/ca_tour_main.page-meta.xml                                              |    7 
 scr/pages/IENewOpportunity.page                                                   |  211 
 scr/classes/CampaignUpsertContactToSapBatch.cls                                   |   42 
 scr/pages/NewRepairParts.page                                                     |  284 
 scr/classes/AssetNumberChangeController.cls                                       |   89 
 scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger          |   29 
 scr/classes/NFMHttpCalloutMock.cls                                                |   13 
 scr/classes/LoanerPortionReturnController.cls-meta.xml                            |    5 
 scr/classes/ChangePasswordController.cls-meta.xml                                 |    5 
 scr/classes/AllAssetController.cls                                                |  227 
 scr/staticresources/SiteSamples/img/maintenance.png                               |    0 
 scr/classes/loanerAppTriggerHandlerTest.cls-meta.xml                              |    5 
 scr/classes/CampaignRelationshipControllerTest.cls-meta.xml                       |    5 
 scr/classes/NewQuoteDevideController.cls                                          |   75 
 scr/classes/OpportunityWebServiceTest.cls                                         |   99 
 scr/classes/SearchProductController.cls-meta.xml                                  |    5 
 scr/pages/LoanerApplicationStockDown.page-meta.xml                                |    7 
 scr/pages/SiteLogin.page-meta.xml                                                 |    8 
 scr/classes/SiteLoginControllerTest.cls-meta.xml                                  |    5 
 scr/staticresources/connection20.resource-meta.xml                                |    5 
 scr/staticresources/SiteSamples/img/tools.png                                     |    0 
 scr/classes/OrderTriggerHandler.cls-meta.xml                                      |    5 
 scr/classes/SWOController.cls-meta.xml                                            |    5 
 scr/triggers/OrderTrigger.trigger-meta.xml                                        |    5 
 scr/pages/LoanerPortionReturn.page                                                |  169 
 scr/classes/AssetTurnoverBatchTest.cls                                            |  123 
 scr/classes/QuotePDFController.cls                                                |  392 
 scr/pages/ChatterAnswersForgotPasswordConfirm.page                                |    6 
 scr/pages/MicrobatchSelfReg.page-meta.xml                                         |    8 
 scr/classes/SBG027TriggerHandler.cls-meta.xml                                     |    5 
 scr/pages/CustContPage.page                                                       |   40 
 scr/pages/AnswersHome.page                                                        |    1 
 scr/pages/OpportunityMessage.page                                                 |   35 
 scr/pages/OrderMessagePopUp.page-meta.xml                                         |    7 
 scr/classes/BusinessActivityHandlerTest.cls                                       |  140 
 scr/classes/LoanerOrderState.cls                                                  |  145 
 scr/classes/TaskTriggerHandler.cls                                                |   43 
 scr/classes/SWOTriggerHandler.cls                                                 |  113 
 scr/pages/ApplicationMessage.page                                                 |   35 
 scr/classes/CodeGeneratorTest.cls                                                 |   24 
 scr/classes/LoanerExpressTriggerHandlerTest.cls                                   |  134 
 scr/classes/LogAutoSendBatchTest.cls                                              |  296 
 scr/classes/OrderDivisionController.cls-meta.xml                                  |    5 
 scr/staticresources/blockUIcss.css                                                |   29 
 scr/classes/NewLoanerUserController.cls                                           |  152 
 scr/classes/PDFWbrController.cls-meta.xml                                         |    5 
 scr/classes/SendEmailController.cls                                               |  648 
 scr/triggers/TaskTrigger.trigger-meta.xml                                         |    5 
 scr/triggers/loanerchangerecord.trigger                                           |    5 
 scr/classes/SSOpporToSSBDallRepBatch.cls-meta.xml                                 |    5 
 scr/classes/LogAutoSendScheduleProductTest.cls                                    |   13 
 scr/classes/NewQuoteEntryControllerTest.cls-meta.xml                              |    5 
 scr/triggers/OpportunityTrigger.trigger                                           |  170 
 scr/classes/CommunitiesLandingController.cls-meta.xml                             |    5 
 scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger-meta.xml |    5 
 scr/classes/OpportunityUpdateSendEmailBatchTest.cls-meta.xml                      |    5 
 scr/classes/ProRegisterBatchSchedulable.cls-meta.xml                              |    5 
 scr/classes/LoanerLendDeliverController.cls                                       | 2237 +
 scr/pages/NewRepairPartsRead.page                                                 |    2 
 scr/classes/SoapApi.cls                                                           |  104 
 scr/pages/UnderConstruction.page                                                  |   19 
 scr/pages/ForgotPasswordConfirm.page                                              |   30 
 scr/classes/OrderTriggerTest.cls                                                  |  807 
 scr/pages/OppTestPage.page-meta.xml                                               |    7 
 scr/staticresources/StageMapJs.resource-meta.xml                                  |    5 
 scr/classes/PrototypeToThaw.cls                                                   |  134 
 scr/classes/NewReplacementOpportunityController.cls                               | 1841 
 scr/classes/OpportunityAAdvancedController.cls-meta.xml                           |    5 
 scr/pages/NewDiagnosisPart.page                                                   |  145 
 scr/classes/NewRepairPartsControllerTest.cls-meta.xml                             |    5 
 scr/pages/ForgotPasswordConfirm.page-meta.xml                                     |    8 
 scr/classes/SWOTriggerHandlerTest.cls-meta.xml                                    |    5 
 scr/classes/SBG010WebService.cls                                                  |  201 
 scr/pages/OpportunityCSVExport.page-meta.xml                                      |    7 
 scr/triggers/Product2Triggrt.trigger                                              |    9 
 scr/classes/AttachmentTriggerTest.cls                                             |  394 
 scr/classes/TaskTriggerHandler.cls-meta.xml                                       |    5 
 scr/classes/UserFaultInfoHandler.cls                                              |  281 
 scr/classes/QuotePDFControllerTest.cls-meta.xml                                   |    5 
 scr/classes/SoapApiTest.cls-meta.xml                                              |    5 
 scr/classes/loanerChangeRecordTriggerHandlerTest.cls-meta.xml                     |    5 
 scr/pages/OrderPDF.page-meta.xml                                                  |    7 
 scr/classes/DeleteSSBatch.cls-meta.xml                                            |    5 
 scr/classes/NewOpportunityControllerTest.cls-meta.xml                             |    5 
 scr/classes/UserViolationsTriggerHandler.cls                                      |   43 
 scr/classes/Product2TriggerHandler.cls-meta.xml                                   |    5 
 scr/pages/NewCrossRegionalSalesOpportunity.page-meta.xml                          |    7 
 scr/classes/OpportunityVisitNotesController.cls-meta.xml                          |    5 
 scr/pages/NewHighProductsOpp.page                                                 |  224 
 scr/pages/ChangePassword.page                                                     |   41 
 scr/components/SiteHeader.component                                               |   15 
 scr/pages/NewQuoteService.page-meta.xml                                           |    7 
 scr/classes/IdentityContextPlugin.cls                                             |   80 
 scr/pages/OrderOpenAlert.page-meta.xml                                            |    7 
 scr/classes/QuotesesEmailComeBackListen.cls                                       |   91 
 scr/classes/OrderShippingNotificationController.cls-meta.xml                      |    5 
 scr/classes/RepairTriggerHandler.cls-meta.xml                                     |    5 
 scr/classes/SBG007TriggerHandler.cls                                              |  375 
 scr/classes/DeliveryTriggerHandler.cls-meta.xml                                   |    5 
 scr/pages/ChatterAnswersChangePassword.page-meta.xml                              |    8 
 scr/pages/ContactOpenAlert.page                                                   |   21 
 scr/classes/CodeGeneratorTest.cls-meta.xml                                        |    5 
 scr/classes/TSRepairUtil.cls                                                      |  544 
 scr/pages/IENewOpportunity.page-meta.xml                                          |    7 
 scr/pages/OrderContract2.page                                                     |  203 
 scr/classes/SBG001TriggerHandlerTest.cls-meta.xml                                 |    5 
 scr/pages/OrderDivision.page                                                      |  110 
 scr/classes/SWOTriggerHandlerTest.cls                                             |  133 
 scr/pages/CanNotEditOrDelete.page-meta.xml                                        |    7 
 scr/pages/CommunitiesTemplate.page-meta.xml                                       |    8 
 scr/classes/QuoteTriggerHandler.cls-meta.xml                                      |    5 
 scr/classes/ProRegisterBatch.cls-meta.xml                                         |    5 
 scr/pages/AllAsset.page                                                           |  180 
 scr/pages/CommunitiesLogin.page                                                   |    2 
 scr/classes/NetworkAccess.cls                                                     |   60 
 scr/pages/MyProfilePage.page-meta.xml                                             |    8 
 scr/pages/NewLoanerApplication.page-meta.xml                                      |    7 
 scr/components/SitePoweredBy.component-meta.xml                                   |    6 
 scr/staticresources/SiteSamples/img/clock.png                                     |    0 
 scr/pages/OrderPDF.page                                                           | 1111 
 scr/classes/ServiceSummaryHandler.cls                                             |   44 
 scr/pages/FileNotFound.page-meta.xml                                              |    8 
 scr/classes/superSort.cls-meta.xml                                                |    5 
 scr/pages/ChatterAnswersLogin.page                                                |    6 
 scr/classes/CommunitiesLandingControllerTest.cls-meta.xml                         |    5 
 scr/classes/ForgotPasswordControllerTest.cls-meta.xml                             |    5 
 scr/classes/NewCrossHighOpportunityController.cls-meta.xml                        |    5 
 scr/pages/QuoteExcelImport.page-meta.xml                                          |    7 
 scr/pages/OrderMessage.page                                                       |   35 
 scr/classes/AccountTriggerHandler.cls                                             | 2231 +
 scr/classes/OpportunityProductControllerTest.cls-meta.xml                         |    5 
 scr/classes/TydelikeAccController.cls                                             |  178 
 scr/classes/SBG018Rest.cls                                                        |  314 
 scr/components/SiteLogin.component-meta.xml                                       |    6 
 scr/staticresources/scc_tour_images/Tour_Images/console-950.png                   |    0 
 scr/classes/MyProfilePageControllerTest.cls-meta.xml                              |    5 
 scr/classes/CodeGenerator.cls                                                     |   30 
 scr/pages/MessageBoard.page-meta.xml                                              |    7 
 scr/classes/LoanerReceiveGoodsController.cls-meta.xml                             |    5 
 scr/pages/OppTestPage.page                                                        |   48 
 scr/classes/IENewOpportunityControllerTest.cls                                    |   83 
 scr/classes/UserFaultInfoHandler.cls-meta.xml                                     |    5 
 scr/pages/NEWCreateSWOQuote.page-meta.xml                                         |    7 
 scr/classes/MyProfilePageController.cls-meta.xml                                  |    5 
 scr/pages/EquipmentLoanerApply.page                                               |  563 
 scr/classes/IdentityContextPluginTest.cls                                         |   29 
 scr/classes/MicrobatchSelfRegController.cls-meta.xml                              |    5 
 scr/classes/LoanerAppDetailTriggerHandlerTest.cls                                 |  124 
 scr/classes/OpportunityUpdateSendEmailSTest.cls-meta.xml                          |    5 
 scr/pages/OrderPdf2.page                                                          |  527 
 scr/classes/ProRegisterLinkHandlerTest.cls-meta.xml                               |    5 
 scr/pages/AssetNumberChange.page                                                  |   82 
 scr/classes/QuotePDFController.cls-meta.xml                                       |    5 
 scr/pages/NewHighProductsOpp.page-meta.xml                                        |    7 
 scr/pages/AssetNumberChange.page-meta.xml                                         |    7 
 scr/classes/OpportunityLineItemTriggerHandler.cls-meta.xml                        |    5 
 scr/classes/TradeCustomerManagerSearchOppController.cls-meta.xml                  |    5 
 scr/classes/CampaignRelationshipControllerTest.cls                                |   90 
 scr/pages/NewOpportunity.page                                                     |  428 
 scr/triggers/CertificationDetailTrigger.trigger                                   |    6 
 scr/classes/QuotesesEmailComeBackListen.cls-meta.xml                              |    5 
 scr/pages/OrderSplitRatio.page-meta.xml                                           |    7 
 scr/classes/SWOSearchProductContaroller.cls-meta.xml                              |    5 
 scr/triggers/RepairDetailsTrigger.trigger-meta.xml                                |    5 
 scr/pages/SWOPage.page-meta.xml                                                   |    7 
 scr/classes/SBG200RestTest.cls-meta.xml                                           |    5 
 scr/classes/TydelikeACController.cls                                              |  298 
 scr/pages/OpportunityMessagePopUp.page                                            |   51 
 scr/triggers/User_Violations.trigger                                              |    5 
 scr/classes/BreachRecordBatchTest.cls                                             |  177 
 scr/staticresources/StageProgressBarCss.css                                       |  276 
 scr/classes/SearchSetProductControllerTest.cls-meta.xml                           |    5 
 scr/classes/OrderShippingNotificationController.cls                               |  145 
 scr/pages/LoanerLendDeliver.page                                                  |  134 
 scr/pages/SearchMemberPage.page-meta.xml                                          |    7 
 scr/classes/CommunitiesLoginControllerTest.cls                                    |   10 
 scr/classes/NewOrderController.cls-meta.xml                                       |    5 
 scr/classes/SBG017WebService.cls                                                  |  127 
 scr/classes/NewQuoteDevideControllerTest.cls-meta.xml                             |    5 
 scr/pages/OpportunityOpenAlert.page-meta.xml                                      |    7 
 scr/pages/NewReplacementOpportunity.page                                          |  108 
 scr/pages/TSRepair.page-meta.xml                                                  |    7 
 scr/staticresources/StageMapJsNew1.js                                             |  170 
 scr/pages/ForgotPassword.page                                                     |   36 
 scr/pages/QuoteCSVExport.page-meta.xml                                            |    7 
 scr/classes/CaseWebService.cls                                                    |   16 
 scr/classes/SearchMemberPageController.cls-meta.xml                               |    5 
 scr/staticresources/tests.js                                                      |    3 
 scr/classes/SearchProductControllerTest.cls                                       |  151 
 scr/classes/TydelikeACControllerTest.cls                                          |  115 
 scr/pages/LoanerTakeBack.page                                                     |  136 
 scr/triggers/ProRegisterLink.trigger                                              |   14 
 scr/classes/SBG001TriggerHandler.cls-meta.xml                                     |    5 
 scr/triggers/UserFaultInfoTrigger.trigger                                         |   14 
 scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls-meta.xml                  |    5 
 scr/pages/SiteRegisterConfirm.page                                                |   30 
 scr/pages/OpportunityOpenAlert.page                                               |  119 
 scr/classes/AccountTriggerHandlerTest.cls                                         |  427 
 scr/classes/ProRegisterLinkHandler.cls-meta.xml                                   |    5 
 scr/pages/SearchProduct.page                                                      |  269 
 scr/pages/ContactOpenAlert.page-meta.xml                                          |    7 
 scr/pages/BandwidthExceeded.page                                                  |   17 
 scr/classes/OrderSplitRatioController.cls-meta.xml                                |    5 
 scr/pages/NewRepairParts.page-meta.xml                                            |    7 
 scr/classes/AssetNumberChangeControllerTest.cls-meta.xml                          |    5 
 scr/classes/AssetNumberChangeController.cls-meta.xml                              |    5 
 scr/classes/SBG005RestTest.cls-meta.xml                                           |    5 
 scr/classes/CommunitiesSelfRegConfirmControllerTest.cls                           |    9 
 scr/classes/OrderWebServiceTest.cls-meta.xml                                      |    5 
 scr/classes/LoanerLendDeliverControllerTest.cls-meta.xml                          |    5 
 scr/classes/SBG005WebService.cls                                                  |  366 
 scr/classes/OrderPdfControllerTest.cls-meta.xml                                   |    5 
 scr/pages/TS_SearchAccount.page-meta.xml                                          |    7 
 scr/classes/NFMUtilTest.cls                                                       |  198 
 scr/classes/CaseWebService.cls-meta.xml                                           |    5 
 scr/classes/CampaignRelationshipController.cls                                    |   82 
 scr/classes/EmailComeBackListen.cls-meta.xml                                      |    5 
 scr/pages/orderPage.page                                                          |   58 
 scr/pages/test001.page-meta.xml                                                   |    7 
 scr/classes/LoanerStockDownCheckController.cls-meta.xml                           |    5 
 scr/classes/test001Controller.cls-meta.xml                                        |    5 
 scr/pages/TydelikeCon.page-meta.xml                                               |    7 
 scr/classes/NetworkAccessTest.cls                                                 |   27 
 scr/classes/SWOTriggerHandler.cls-meta.xml                                        |    5 
 scr/triggers/User_Violations.trigger-meta.xml                                     |    5 
 scr/classes/SBG017WebServiceTest.cls                                              |  216 
 scr/classes/AssetTurnoverSchedulableTest.cls-meta.xml                             |    5 
 scr/classes/OpportunityProductController.cls                                      | 3524 +
 scr/classes/SBG204RestExecute.cls-meta.xml                                        |    5 
 scr/classes/NEWCreateSWOQuoteControllerTest.cls-meta.xml                          |    5 
 scr/staticresources/NewQuoteEntryJS.resource-meta.xml                             |    5 
 scr/classes/TS_SearchAccountController.cls-meta.xml                               |    5 
 scr/classes/LoanerTakeBackControllerTest.cls-meta.xml                             |    5 
 scr/classes/OpportunityUpdateSendEmailBatch.cls                                   |  178 
 scr/classes/TrialCustomerPortalHomePageController.cls-meta.xml                    |    5 
 scr/classes/SBG005Rest.cls-meta.xml                                               |    5 
 scr/pages/OrderContract.page                                                      |  746 
 scr/staticresources/scc_tour_images/Tour_Images/tourArrows.png                    |    0 
 scr/classes/ChangePasswordControllerTest.cls                                      |   14 
 scr/pages/LoanerLendDeliver.page-meta.xml                                         |    7 
 scr/staticresources/jquerysuggestcss.resource-meta.xml                            |    5 
 scr/classes/NewReplacementOpportunityController.cls-meta.xml                      |    5 
 scr/classes/OppInternalMessageController.cls-meta.xml                             |    5 
 scr/classes/OrderMessageController.cls                                            |  117 
 scr/pages/OrderSplitRatioPopUp.page-meta.xml                                      |    7 
 scr/classes/OppInternalMessageControllerTest.cls-meta.xml                         |    5 
 scr/pages/OrderSplitRatioPopUp.page                                               |   44 
 scr/classes/CommunitiesSelfRegControllerTest.cls                                  |   20 
 scr/classes/SBG004WebServiceTest.cls-meta.xml                                     |    5 
 scr/pages/OppInternalMessagePopup.page-meta.xml                                   |    7 
 scr/classes/QuotesPDFControllerTest.cls                                           |  217 
 scr/classes/SBG005Rest.cls                                                        |  399 
 scr/classes/LogAutoSendSchedule.cls                                               |   20 
 scr/pages/LoanerPortionReturn.page-meta.xml                                       |    7 
 scr/classes/CertificationDetailTriggerTest.cls-meta.xml                           |    5 
 scr/pages/NewCrossRegionalSalesOpportunity.page                                   |  437 
 scr/pages/OrderApproveAlert2.page-meta.xml                                        |    7 
 scr/classes/NewOpportunityController.cls-meta.xml                                 |    5 
 scr/classes/SBG010WebService.cls-meta.xml                                         |    5 
 scr/classes/SBG027TriggerHandleTest.cls                                           |  617 
 scr/pages/NewCrossHighOpportunity.page-meta.xml                                   |    7 
 scr/classes/RadiationUtil.cls-meta.xml                                            |    5 
 scr/pages/OrderContract2.page-meta.xml                                            |    7 
 scr/pages/QuoteExcelImport.page                                                   |   40 
 scr/pages/AccountOpenAlert.page                                                   |   78 
 scr/pages/scc_tour_style.page                                                     |  234 
 scr/pages/SWOPageRead.page-meta.xml                                               |    7 
 scr/pages/StdExceptionTemplate.page-meta.xml                                      |    8 
 scr/pages/TSRepair.page                                                           | 1006 
 scr/classes/SWOUtil.cls-meta.xml                                                  |    5 
 scr/classes/oppbatchTest.cls-meta.xml                                             |    5 
 scr/classes/LogAutoSendBatchProductTest.cls                                       |  141 
 scr/triggers/AttachmentTrigger.trigger                                            |   26 
 scr/triggers/DeliveryTrigger.trigger                                              |    6 
 scr/classes/SSOpportunityBatch.cls-meta.xml                                       |    5 
 scr/classes/ServiceSummaryHandler.cls-meta.xml                                    |    5 
 scr/classes/LoanerAppDetailTriggerHandler.cls                                     |  271 
 scr/pages/TydelikeAC.page                                                         |  282 
 scr/staticresources/SiteSamples/SiteStyles.css                                    |   28 
 scr/staticresources/TrialPortalBanner.png                                         |    0 
 scr/classes/OrderDivisionControllerTest.cls                                       |  434 
 scr/staticresources/CommonUtilJs.resource-meta.xml                                |    5 
 scr/pages/OpportunityPage.page                                                    |   22 
 scr/classes/SBGITMRestTest.cls-meta.xml                                           |    5 
 scr/pages/MyProfilePage.page                                                      |   72 
 scr/classes/TradeCustomerManagerSearchOppController.cls                           |   26 
 scr/classes/OrderItemTriggerHandler.cls-meta.xml                                  |    5 
 scr/classes/SearchSetProductController.cls-meta.xml                               |    5 
 scr/classes/ProRegisterBatchSchedulable.cls                                       |    5 
 scr/classes/SiteRegisterControllerTest.cls-meta.xml                               |    5 
 scr/pages/CTITest.page                                                            |  853 
 scr/classes/ContactTriggerHandlerTest.cls-meta.xml                                |    5 
 scr/classes/OpportunityUpdateSendEmailSTest.cls                                   |   19 
 scr/pages/OpportunityVisitNotesPopUp.page-meta.xml                                |    8 
 scr/classes/SBGITMRest.cls                                                        |  365 
 scr/pages/CommunitiesTemplate.page                                                |    6 
 scr/classes/QuotesPDFController.cls                                               |  336 
 scr/classes/SBG200RestTest.cls                                                    |  218 
 scr/classes/SiteLoginControllerTest.cls                                           |   13 
 scr/triggers/AccountTrigger.trigger-meta.xml                                      |    5 
 scr/classes/NewCrossRegionalControllerText.cls                                    |  157 
 scr/triggers/ServiceSummaryTrigger.trigger-meta.xml                               |    5 
 scr/triggers/ProRegisterLink.trigger-meta.xml                                     |    5 
 scr/classes/DataLoadAccountController.cls-meta.xml                                |    5 
 scr/classes/SBG004Rest.cls-meta.xml                                               |    5 
 scr/classes/CodeGenerator.cls-meta.xml                                            |    5 
 scr/staticresources/apex20.resource-meta.xml                                      |    5 
 scr/classes/SiteLoginController.cls-meta.xml                                      |    5 
 scr/classes/ProRegisterBatchTest.cls-meta.xml                                     |    5 
 scr/classes/Sbg001Sync.cls                                                        |   84 
 scr/classes/SoapApiTest.cls                                                       |   43 
 scr/triggers/UpdateLogisticsInformation.trigger                                   |   11 
 scr/components/SitePoweredBy.component                                            |    8 
 scr/pages/OpportunityProduct.page                                                 |  484 
 scr/classes/AssetTriggerHandler.cls-meta.xml                                      |    5 
 scr/classes/OrderInternalMessageController.cls-meta.xml                           |    5 
 scr/classes/BusinessActivityHandlerTest.cls-meta.xml                              |    5 
 scr/classes/SBGCallLogRest.cls                                                    |   68 
 scr/classes/ChatterAnswersEscalationTriggerTest.cls                               |   24 
 scr/classes/AccountTriggerHandlerTest.cls-meta.xml                                |    5 
 scr/classes/Sbg001Sync.cls-meta.xml                                               |    5 
 scr/classes/TydelikeACController.cls-meta.xml                                     |    5 
 scr/pages/LoanerTakeBack.page-meta.xml                                            |    7 
 scr/classes/setOrderShareBatchTest.cls                                            |  272 
 scr/classes/OrderWebServiceTest.cls                                               | 1209 
 scr/staticresources/jquerysuggestjs.js                                            |  420 
 scr/pages/CustContPage.page-meta.xml                                              |    7 
 scr/staticresources/PleaseWaitDialog.bin                                          |  201 
 scr/classes/setOrderShareBatch.cls                                                |  171 
 scr/pages/SoftphoneConsole.page-meta.xml                                          |    7 
 scr/staticresources/NewQuoteEntryJS.bin                                           |   85 
 scr/classes/loanerChangeRecordTriggerHandlerTest.cls                              |  119 
 scr/classes/OrderPdfController.cls                                                |  896 
 scr/pages/SiteRegister.page-meta.xml                                              |    8 
 scr/triggers/AttachmentTrigger.trigger-meta.xml                                   |    5 
 scr/classes/NewQuoteDevideController.cls-meta.xml                                 |    5 
 scr/classes/OpportunityAAdvancedControllerTest.cls                                |   54 
 scr/classes/NewDiagnosisPartControllerTest.cls                                    |   54 
 scr/classes/SBG027Controller.cls                                                  |  411 
 scr/classes/TOTPPluginTest.cls-meta.xml                                           |    5 
 scr/classes/AssetTriggerHandlerTest.cls                                           |  325 
 scr/classes/ApplicationMessageController.cls                                      |  123 
 scr/classes/SBG027Controller.cls-meta.xml                                         |    5 
 scr/aura/.eslintrc.json                                                           |    8 
 scr/classes/AccountWebService.cls                                                 |  265 
 scr/classes/loanerChangeRecordTriggerHandler.cls                                  |   33 
 scr/pages/LoanerApplicationStockUp.page                                           |   94 
 scr/pages/StageProgressBar.page-meta.xml                                          |    7 
 scr/classes/OpportunityMessageControllerTest.cls-meta.xml                         |    5 
 scr/classes/DeliveryConfirmPDFController.cls                                      |  177 
 scr/classes/LogAutoSendBatch.cls                                                  |  106 
 scr/classes/EquipmentLoanerApplyController.cls                                    | 1556 
 scr/classes/LogAutoSendScheduleTest.cls                                           |   13 
 scr/pages/TrialCustomerPortalHomePage.page                                        |  189 
 scr/classes/LoanerOrderStateTest.cls-meta.xml                                     |    5 
 scr/classes/SBG203Rest.cls                                                        | 1682 
 scr/classes/UserViolationsTriggerTest.cls-meta.xml                                |    5 
 scr/pages/CommunitiesLogin.page-meta.xml                                          |    8 
 scr/classes/AttachmentTriggerTest.cls-meta.xml                                    |    5 
 scr/classes/StaticParameter.cls                                                   |  284 
 scr/classes/LoanerApplicationWebService.cls-meta.xml                              |    5 
 scr/classes/NewOrderControllerTest.cls-meta.xml                                   |    5 
 scr/classes/SBG004RestTest.cls-meta.xml                                           |    5 
 scr/pages/NEWCreateSWOQuoteReadOnly.page                                          |  842 
 scr/classes/Sbg007Sync.cls-meta.xml                                               |    5 
 scr/classes/CampaignUpsertContactToSapBatchTest.cls-meta.xml                      |    5 
 scr/classes/SBG018RestTest.cls-meta.xml                                           |    5 
 scr/classes/CaseEmailComeBackListen.cls-meta.xml                                  |    5 
 scr/classes/OpportunityProductController.cls-meta.xml                             |    5 
 scr/classes/loanerAppTriggerHandler.cls-meta.xml                                  |    5 
 scr/classes/SWOController.cls                                                     |  753 
 scr/classes/StageProgressBarExtension.cls                                         |   39 
 scr/classes/RepairTriggerHandler.cls                                              |  118 
 scr/classes/AttachmentTriggerHandler.cls                                          |  537 
 scr/classes/ControllerUtil.cls-meta.xml                                           |    5 
 scr/classes/SBG017WebServiceTest.cls-meta.xml                                     |    5 
 scr/classes/SBG019RestTest.cls                                                    |   94 
 scr/classes/SBG018RestTest.cls                                                    |  175 
 scr/staticresources/ServiceCloudLogo.resource-meta.xml                            |    5 
 scr/classes/SBG017RestTest.cls                                                    |  247 
 scr/triggers/AccountTrigger.trigger                                               |   53 
 scr/triggers/ContactTrigger.trigger                                               |   12 
 scr/classes/LoanerApplicationWebService.cls                                       | 1056 
 scr/pages/CanNotDeleteCase.page                                                   |    6 
 scr/pages/TradeCustomerManagerSearchOpp.page-meta.xml                             |    7 
 scr/pages/test001.page                                                            |    6 
 scr/classes/Sbg027Sync.cls-meta.xml                                               |    5 
 scr/classes/TSRepairUtil.cls-meta.xml                                             |    5 
 scr/classes/UserViolationsTriggerHandler.cls-meta.xml                             |    5 
 scr/classes/OppTestController.cls-meta.xml                                        |    5 
 scr/classes/SWOSearchProductContaroller.cls                                       |   96 
 scr/classes/SBGITMRestNewTest.cls-meta.xml                                        |    5 
 scr/classes/SBG005WebServiceTest.cls                                              | 1065 
 scr/classes/SWOSearchProductContarollerTest.cls                                   |   34 
 scr/classes/LogAutoSendBatch.cls-meta.xml                                         |    5 
 scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls                           |   86 
 scr/pages/Exception.page                                                          |   37 
 scr/classes/CampaignUpsertContactToSapTest.cls-meta.xml                           |    5 
 scr/triggers/AssetTrigger.trigger-meta.xml                                        |    5 
 scr/triggers/SWOTrigger.trigger-meta.xml                                          |    5 
 scr/pages/OrderCSVExport.page                                                     |    7 
 scr/classes/loanerAppTriggerHandler.cls                                           |  679 
 scr/classes/ProRegisterLinkHandlerTest.cls                                        |   97 
 scr/pages/NewOpportunity.page-meta.xml                                            |    7 
 scr/classes/OrderSplitRatioController.cls                                         |   85 
 scr/classes/TSRepairControllerTest.cls-meta.xml                                   |    5 
 scr/pages/NewSearchProductPage.page                                               |   65 
 scr/pages/ChangePassword.page-meta.xml                                            |    8 
 scr/classes/CampaignUpsertContactToSapBatchTest.cls                               |   97 
 scr/pages/ChatterAnswersHelp.page                                                 |    6 
 scr/classes/OlympusCoJpCommonMessage.cls-meta.xml                                 |    5 
 scr/classes/SBG005RestTest.cls                                                    | 1113 
 scr/classes/ChangePasswordController.cls                                          |   14 
 scr/pages/Trial_Tour.page                                                         |    5 
 scr/classes/SBG004RestTest.cls                                                    |  645 
 scr/classes/SiteRegisterController.cls                                            |   50 
 scr/pages/OrderSplitRatio.page                                                    |   44 
 scr/classes/SSOpportunityBatch.cls                                                |  214 
 scr/classes/OrderMessageControllerTest.cls                                        |  198 
 scr/pages/NewQuoteEntry.page-meta.xml                                             |    7 
 scr/pages/OrderDivision.page-meta.xml                                             |    7 
 scr/components/SiteLogin.component                                                |   23 
 scr/pages/TydelikeAC.page-meta.xml                                                |    7 
 scr/staticresources/scc_tour_images/Tour_Images/chatter-answers-950.png           |    0 
 scr/classes/BreachRecordBatch.cls                                                 |  451 
 scr/classes/OrdertoZhaoEmailSchedulableTest.cls                                   |   19 
 scr/pages/SiteRegisterConfirm.page-meta.xml                                       |    8 
 scr/classes/TydelikeAccControllerTest.cls-meta.xml                                |    5 
 scr/pages/ChatterAnswersAgentView.page-meta.xml                                   |    8 
 scr/classes/NewQuoteEntryWebServiceTest.cls-meta.xml                              |    5 
 scr/classes/OrdertoZhaoEmailSchedulableTest.cls-meta.xml                          |    5 
 scr/classes/LoanerTakeBackController.cls                                          |  166 
 scr/classes/OrderSplitRatioControllerTest.cls                                     |  282 
 scr/classes/RadiationUtilTest.cls-meta.xml                                        |    5 
 scr/classes/SBG005WebServiceTest.cls-meta.xml                                     |    5 
 scr/pages/NewLoanerUser.page                                                      |   70 
 scr/classes/NewDiagnosisPartController.cls-meta.xml                               |    5 
 scr/classes/LoanerLendDeliverController.cls-meta.xml                              |    5 
 scr/classes/CertificationDetailTriggerHandler.cls-meta.xml                        |    5 
 scr/classes/NewDiagnosisPartControllerTest.cls-meta.xml                           |    5 
 scr/classes/SBG007TriggerHandlerTest.cls-meta.xml                                 |    5 
 scr/staticresources/StageMapJsNew.js                                              |   89 
 scr/classes/OpportunityVisitNotesControllerTest.cls                               |   69 
 scr/classes/SWOControllerTest.cls                                                 |  349 
 scr/pages/SendEmail.page-meta.xml                                                 |    7 
 scr/classes/AssetTurnoverBatch.cls-meta.xml                                       |    5 
 scr/classes/OrdertoZhaoEmailBatch.cls-meta.xml                                    |    5 
 scr/classes/NewLoanerUserControllerTest.cls-meta.xml                              |    5 
 scr/pages/MessageBoardPoPuP.page-meta.xml                                         |    7 
 scr/triggers/OpportunityProgressBarTrgiger.trigger                                |    5 
 scr/classes/LoanerPortionDeliverControllerTest.cls-meta.xml                       |    5 
 scr/classes/SBG204RestExecute.cls                                                 |  122 
 scr/classes/CommunitiesLoginController.cls-meta.xml                               |    5 
 scr/classes/NewCrossRegionalSalesController.cls                                   |  159 
 scr/classes/oppbatch.cls                                                          |  234 
 scr/pages/AccountOpenAlert.page-meta.xml                                          |    7 
 scr/classes/oppbatchTest.cls                                                      |    6 
 scr/classes/RepairDetailsTriggerTest.cls-meta.xml                                 |    5 
 scr/classes/SBGITMWebService.cls-meta.xml                                         |    5 
 scr/pages/OrderPdf3.page                                                          |  326 
 scr/classes/StaticParameterTest.cls-meta.xml                                      |    5 
 scr/pages/ca_tour_main.page                                                       |  162 
 scr/classes/OrderInternalMessageController.cls                                    |  422 
 scr/pages/LoanerReceiveGoods.page-meta.xml                                        |    7 
 scr/classes/ProRegisterBatchTest.cls                                              |   54 
 scr/classes/LoanerStockDownCheckControllerTest.cls-meta.xml                       |    5 
 scr/classes/MicrobatchSelfRegControllerTest.cls-meta.xml                          |    5 
 scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls                              |  113 
 scr/classes/SiteRegisterController.cls-meta.xml                                   |    5 
 scr/classes/TSRepairController.cls                                                | 1882 
 scr/pages/OpportunityVisitNotes.page-meta.xml                                     |    8 
 scr/classes/DataLoadAccountControllerTest.cls                                     |  241 
 scr/pages/OppInternalMessage.page                                                 |   41 
 scr/classes/Sbg027Sync.cls                                                        |  109 
 scr/classes/ProRegisterHandler.cls                                                |  192 
 scr/classes/NewOrderController.cls                                                |   54 
 scr/classes/LoanerApplicationFlowController.cls                                   |  146 
 scr/pages/TydelikeCon.page                                                        |  158 
 scr/staticresources/scc_tour_images/Tour_Images/icon_sprite_serviceSupport.png    |    0 
 scr/classes/NewHighProductsOppControllerTest.cls-meta.xml                         |    5 
 scr/classes/RadiationUtil.cls                                                     |  577 
 scr/classes/SSOpportunitySchedule.cls                                             |    5 
 scr/triggers/OpportunityTrigger.trigger-meta.xml                                  |    5 
 scr/pages/ForgotPassword.page-meta.xml                                            |    8 
 scr/classes/LoanerReceiveGoodsControllerTest.cls                                  |  127 
 scr/classes/OrdertoZhaoEmailBatchTest.cls-meta.xml                                |    5 
 scr/pages/CommunitiesSelfReg.page                                                 |   28 
 scr/classes/ApplicationMessageControllerTest.cls-meta.xml                         |    5 
 scr/classes/SiteLoginController.cls                                               |   14 
 scr/staticresources/SiteSamples/img/force_logo.png                                |    0 
 scr/components/SiteHeader.component-meta.xml                                      |    6 
 scr/pages/EquipmentLoanerApply.page-meta.xml                                      |    7 
 scr/pages/InMaintenance.page-meta.xml                                             |    8 
 scr/classes/SBG010Rest.cls-meta.xml                                               |    5 
 scr/classes/loanerAppTriggerHandlerTest.cls                                       |  197 
 scr/classes/ContactTriggerHandlerTest.cls                                         |   90 
 scr/classes/TSRepairController.cls-meta.xml                                       |    5 
 scr/pages/scc_tour_main.page                                                      |  174 
 scr/classes/ProRegisterBatch.cls                                                  |   45 
 scr/classes/LogAutoSendBatchProductTest.cls-meta.xml                              |    5 
 scr/classes/SBGITMRest.cls-meta.xml                                               |    5 
 scr/classes/SBG007TriggerHandlerTest.cls                                          |  238 
 scr/classes/DeleteSSBatch.cls                                                     |  114 
 scr/classes/OrderDivisionControllerTest.cls-meta.xml                              |    5 
 scr/classes/UpdateTotalCostPriceSchedule.cls-meta.xml                             |    5 
 scr/classes/CampaignUpsertContactToSapBatchSchedule.cls                           |    5 
 scr/classes/setOrderShareBatchSchedule.cls                                        |    5 
 scr/classes/NFMHttpCalloutMock.cls-meta.xml                                       |    5 
 scr/pages/NewOrder.page                                                           |   26 
 scr/classes/LoanerPortionDeliverController.cls                                    |  402 
 scr/classes/StageProgressBarExtension.cls-meta.xml                                |    5 
 scr/classes/OrderPdfController.cls-meta.xml                                       |    5 
 scr/triggers/OpportunityProgressBarTrgiger.trigger-meta.xml                       |    5 
 scr/classes/CommunitiesLoginControllerTest.cls-meta.xml                           |    5 
 scr/pages/InMaintenance.page                                                      |   19 
 scr/classes/RepairTriggerHandlerTest.cls-meta.xml                                 |    5 
 scr/classes/SBG203RestTest.cls                                                    |  385 
 scr/classes/setOrderShareBatchSchedule.cls-meta.xml                               |    5 
 scr/classes/TydelikeAccController.cls-meta.xml                                    |    5 
 scr/components/PDFWbr.component                                                   |    7 
 scr/classes/SearchSetProductControllerTest.cls                                    |  106 
 scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls-meta.xml                     |    5 
 scr/classes/OpportunityWebService.cls                                             |  703 
 scr/components/PDFWbr.component-meta.xml                                          |    5 
 scr/classes/CommunitiesSelfRegController.cls                                      |   69 
 scr/classes/OpportunityUpdateSendEmailBatchTest.cls                               |  215 
 scr/classes/OrderShippingNotificationControllerTest.cls-meta.xml                  |    5 
 scr/pages/Trial_Tour.page-meta.xml                                                |    7 
 scr/classes/TOTPPlugin.cls                                                        |   96 
 scr/classes/SBG019Rest.cls                                                        |  211 
 scr/classes/LoanerApplicationWebServiceTest.cls-meta.xml                          |    5 
 scr/pages/TydelikeAcc.page-meta.xml                                               |    7 
 scr/classes/LogAutoSendScheduleProduct.cls                                        |   19 
 scr/classes/SBG204RestTest.cls-meta.xml                                           |    5 
 scr/classes/LoanerPortionReturnControllerTest.cls-meta.xml                        |    5 
 scr/classes/PDFWbrControllerTest.cls                                              |   20 
 scr/triggers/DeliveryTrigger.trigger-meta.xml                                     |    5 
 scr/classes/NewLoanerUserController.cls-meta.xml                                  |    5 
 scr/pages/SearchMemberPage.page                                                   |  133 
 scr/classes/OrderPdf2Controller.cls-meta.xml                                      |    5 
 scr/classes/TradeCustomerManagerSearchOppTest.cls-meta.xml                        |    5 
 scr/classes/SBG200Rest.cls-meta.xml                                               |    5 
 scr/classes/NewHighProductsOppController.cls-meta.xml                             |    5 
 scr/classes/NewCrossRegionalSalesController.cls-meta.xml                          |    5 
 scr/pages/SWOSearchProduct.page                                                   |  222 
 scr/classes/NewQuoteEntryController.cls-meta.xml                                  |    5 
 scr/classes/SBG019Rest.cls-meta.xml                                               |    5 
 scr/pages/NewQuoteService.page                                                    |  534 
 scr/pages/OrderApproveAlert.page-meta.xml                                         |    8 
 scr/classes/PartnerSoapSforceCom.cls                                              |  380 
 scr/classes/AssetNumberChangeControllerTest.cls                                   |   66 
 scr/classes/QuoteTriggerTest.cls-meta.xml                                         |    5 
 scr/classes/ForgotPasswordController.cls                                          |   19 
 scr/pages/OrderInternalMessage.page                                               |   41 
 scr/classes/OrderWebService.cls-meta.xml                                          |    5 
 scr/pages/ChatterAnswersAgentView.page                                            |   11 
 scr/pages/OpportunityAAdvanced.page                                               |  231 
 scr/pages/SiteRegister.page                                                       |   45 
 scr/staticresources/apex20.js                                                     |   70 
 scr/classes/LoanerOrderStateTest.cls                                              |  325 
 scr/classes/BusinessActivityHandler.cls-meta.xml                                  |    5 
 scr/classes/NEWCreateSWOQuoteControllerTest.cls                                   |  288 
 scr/classes/OppInternalMessageControllerTest.cls                                  |    8 
 scr/classes/OpportunityMessageController.cls-meta.xml                             |    5 
 scr/classes/Product2TriggerHandlerTest.cls                                        |  105 
 scr/classes/TydelikeConController.cls                                             |  101 
 scr/pages/NEWCreateSWOQuoteReadOnly.page-meta.xml                                 |    7 
 scr/classes/AllAssetController.cls-meta.xml                                       |    5 
 scr/classes/PDFWbrControllerTest.cls-meta.xml                                     |    5 
 scr/classes/AssetTriggerHandlerTest.cls-meta.xml                                  |    5 
 scr/classes/NewOpportunityController.cls                                          |  171 
 scr/classes/ControllerUtil.cls                                                    |  105 
 scr/pages/NewRepairPartsRead.page-meta.xml                                        |    7 
 scr/pages/NewSearchProductPage.page-meta.xml                                      |    7 
 scr/classes/BusinessActivityHandler.cls                                           |  302 
 scr/classes/DeliveryConfirmPDFControllerTest.cls-meta.xml                         |    5 
 scr/classes/OpportunityStageProgressBarUpdate.cls-meta.xml                        |    5 
 scr/classes/NewDiagnosisPartController.cls                                        |  122 
 scr/classes/ProRegisterBatchSchedulableTest.cls-meta.xml                          |    5 
 scr/classes/CampaignRelationshipController.cls-meta.xml                           |    5 
 scr/classes/ChatterAnswers.cls-meta.xml                                           |    5 
 scr/pages/StdExceptionTemplate.page                                               |   23 
 scr/classes/OrderItemTriggerHandler.cls                                           |  700 
 scr/classes/NewQuoteEntryWebService.cls-meta.xml                                  |    5 
 scr/pages/SoftphoneConsole.page                                                   |  132 
 scr/classes/PersonalProcessInstanceController.cls                                 |   96 
 scr/classes/DeliveryConfirmPDFController.cls-meta.xml                             |    5 
 scr/classes/AgentContributionArticleController.cls                                |   16 
 scr/pages/PersonalProcessInstance.page-meta.xml                                   |    7 
 scr/classes/IENewOpportunityController.cls-meta.xml                               |    5 
 scr/classes/NewQuoteEntryControllerTest.cls                                       |  982 
 scr/classes/SBG203Rest.cls-meta.xml                                               |    5 
 scr/classes/CommunitiesSelfRegConfirmController.cls                               |    7 
 scr/pages/UnderConstruction.page-meta.xml                                         |    8 
 scr/classes/Product2TriggerHandler.cls                                            |  122 
 scr/staticresources/TrialPortalBanner.resource-meta.xml                           |    5 
 scr/classes/OrdertoZhaoEmailSchedulable.cls                                       |    5 
 scr/classes/SBGITMWebServiceTest.cls-meta.xml                                     |    5 
 scr/pages/QuotesPDF.page                                                          |  305 
 scr/pages/OpportunityMessage.page-meta.xml                                        |    7 
 scr/pages/SiteTemplate.page                                                       |   13 
 scr/classes/OrderTriggerHandler.cls                                               | 3521 +
 scr/staticresources/connection20.js                                               | 1935 
 scr/classes/TradeCustomerManagerControllerTest.cls                                |  144 
 scr/pages/CommunitiesLanding.page                                                 |    2 
 scr/pages/OrderPdf3.page-meta.xml                                                 |    7 
 scr/pages/SWOSearchProduct.page-meta.xml                                          |    7 
 scr/classes/RepairDetailsTriggerHandler.cls                                       |   63 
 scr/staticresources/jquerysuggestcss.js                                           |   28 
 scr/classes/UpdateTotalCostPriceSchedule.cls                                      |   15 
 scr/pages/OrderPdf2.page-meta.xml                                                 |    7 
 scr/classes/MyProfilePageControllerTest.cls                                       |   76 
 scr/classes/SBG200Rest.cls                                                        |  401 
 scr/classes/LoanerPortionDeliverControllerTest.cls                                |  152 
 scr/classes/LoanerApplicationWebServiceTest.cls                                   |  603 
 scr/classes/OpportunityStageProgressBarUpdate.cls                                 |   14 
 scr/staticresources/cti.js                                                        |    0 
 scr/classes/TradeCustomerManagerController.cls                                    |  300 
 scr/pages/OrderMessagePopUp.page                                                  |   51 
 scr/pages/SoftwarePhoneInformation.page-meta.xml                                  |    7 
 scr/components/SiteFooter.component-meta.xml                                      |    6 
 scr/pages/DataLoadAccount.page-meta.xml                                           |    7 
 scr/classes/superSort.cls                                                         |  139 
 scr/pages/DataLoadAccount.page                                                    |  197 
 scr/classes/DataLoadAccountControllerTest.cls-meta.xml                            |    5 
 scr/triggers/QuoteLineItemTrigger.trigger-meta.xml                                |    5 
 scr/classes/PDFWbrController.cls                                                  |   27 
 scr/classes/OpportunityVisitNotesControllerTest.cls-meta.xml                      |    5 
 scr/classes/LicenseCheckUtilTest.cls                                              |   97 
 scr/classes/IENewOpportunityControllerTest.cls-meta.xml                           |    5 
 scr/classes/SearchManagementController.cls                                        |  118 
 scr/classes/LoanerStockDownCheckController.cls                                    |  171 
 scr/classes/SSOpporToSSBDallRepBatch.cls                                          |   59 
 scr/classes/AssetTurnoverSchedulableTest.cls                                      |   20 
 scr/classes/OpportunityUpdateSendEmailBatch.cls-meta.xml                          |    5 
 scr/classes/MessageBoardControllerTest.cls-meta.xml                               |    5 
 scr/classes/SearchProductController.cls                                           |  291 
 scr/classes/NewCrossRegionalControllerText.cls-meta.xml                           |    5 
 scr/classes/NewSearchProductController.cls                                        |   60 
 scr/classes/LicenseCheckUtil.cls                                                  |  118 
 scr/classes/UserFaultInfoHandlerTest.cls                                          |  143 
 scr/classes/setOrderShareBatch.cls-meta.xml                                       |    5 
 scr/classes/QuotesPDFController.cls-meta.xml                                      |    5 
 scr/triggers/OpportunityLineItemTrigger.trigger-meta.xml                          |    5 
 scr/classes/AttachmentTriggerHandler.cls-meta.xml                                 |    5 
 scr/classes/PersonalProcessInstanceControllerTest.cls-meta.xml                    |    5 
 scr/staticresources/SWOJS.js                                                      |  549 
 scr/classes/OrdertoZhaoEmailBatch.cls                                             |   50 
 scr/classes/QuotesPDFControllerTest.cls-meta.xml                                  |    5 
 scr/classes/TS_SearchAccountControllerTest.cls                                    |   54 
 scr/triggers/loanerchangerecord.trigger-meta.xml                                  |    5 
 scr/pages/ChatterAnswersRegistration.page                                         |    6 
 scr/triggers/loanerAppDetStatusUp.trigger                                         |   21 
 scr/staticresources/blockUIcss.resource-meta.xml                                  |    5 
 scr/classes/ProRegisterLinkHandler.cls                                            |  107 
 scr/classes/SBG010WebServiceTest.cls-meta.xml                                     |    5 
 scr/classes/SBG001TriggerHandlerTest.cls                                          |  181 
 scr/triggers/loanerAppStatusUp.trigger                                            |   44 
 scr/classes/CommunitiesSelfRegControllerTest.cls-meta.xml                         |    5 
 scr/classes/MessageBoardController.cls                                            |   89 
 scr/pages/TydelikeAcc.page                                                        |  321 
 scr/triggers/OrderItemTrigger.trigger-meta.xml                                    |    5 
 scr/classes/SBG204Rest.cls                                                        |  349 
 scr/pages/scc_tour_main.page-meta.xml                                             |    7 
 scr/classes/CommunitiesLandingController.cls                                      |   12 
 scr/classes/RepairDetailsTriggerHandler.cls-meta.xml                              |    5 
 scr/classes/NewHighProductsOppController.cls                                      |  124 
 scr/classes/OpportunityStockAnswer.cls-meta.xml                                   |    5 
 scr/pages/ca_tour_style.page-meta.xml                                             |    7 
 scr/classes/TradeCustomerManagerController.cls-meta.xml                           |    5 
 scr/classes/LogAutoSendBatchProduct.cls                                           |   40 
 scr/classes/calendarUtilTest.cls-meta.xml                                         |    5 
 scr/pages/CommunitiesLanding.page-meta.xml                                        |    8 
 scr/classes/OrdertoZhaoEmailBatchTest.cls                                         |  390 
 scr/classes/NFMUtil.cls                                                           |  319 
 scr/pages/LoanerApplicationStockDownCheck.page                                    |  130 
 scr/classes/LoanerPortionDeliverController.cls-meta.xml                           |    5 
 scr/classes/QuoteLineItemTriggerHandler.cls                                       |   26 
 scr/classes/NewQuoteEntryController.cls                                           | 5058 ++
 scr/pages/NewLoanerApplication.page                                               |  386 
 scr/pages/ApplicationMessagePopUp.page-meta.xml                                   |    7 
 scr/pages/NewDiagnosisPart.page-meta.xml                                          |    7 
 scr/staticresources/SiteSamples.resource-meta.xml                                 |    6 
 scr/classes/OpportunityTriggerTest.cls-meta.xml                                   |    5 
 scr/classes/PersonalProcessInstanceController.cls-meta.xml                        |    5 
 scr/triggers/RepairTrigger.trigger                                                |    5 
 scr/classes/NewOrderControllerTest.cls                                            |  144 
 scr/classes/OpportunityMessageControllerTest.cls                                  |  113 
 scr/classes/ProRegisterBatchSchedulableTest.cls                                   |   17 
 scr/classes/SearchProductControllerTest.cls-meta.xml                              |    5 
 scr/pages/SendEmail.page                                                          |  340 
 scr/classes/CommunitiesSelfRegConfirmControllerTest.cls-meta.xml                  |    5 
 scr/pages/SiteLogin.page                                                          |   29 
 scr/staticresources/StageMapJs.js                                                 |   69 
 scr/classes/loanerChangeRecordTriggerHandler.cls-meta.xml                         |    5 
 scr/classes/BreachRecordSchedulableTest.cls                                       |   23 
 scr/classes/TS_SearchAccountController.cls                                        |   67 
 scr/pages/OpportunityProduct.page-meta.xml                                        |    7 
 scr/pages/NEWCreateSWOQuote.page                                                  |  890 
 scr/pages/ChatterAnswersForgotPasswordConfirm.page-meta.xml                       |    8 
 scr/pages/OppInternalMessagePopup.page                                            |   51 
 scr/pages/OpportunityVisitNotesPopUp.page                                         |   51 
 scr/classes/SendEmailControllerTest.cls-meta.xml                                  |    5 
 scr/pages/StageProgressBar.page                                                   |  246 
 scr/classes/AssetTurnoverBatchTest.cls-meta.xml                                   |    5 
 scr/classes/MessageBoardControllerTest.cls                                        |   21 
 scr/classes/OrderShippingNotificationControllerTest.cls                           |   79 
 scr/classes/SendEmailControllerTest.cls                                           |  166 
 scr/triggers/BusinessActivityTrigger.trigger                                      |   17 
 scr/pages/OppInternalMessage.page-meta.xml                                        |    7 
 scr/triggers/OrderTrigger.trigger                                                 |   46 
 scr/classes/BreachRecordSchedulableTest.cls-meta.xml                              |    5 
 scr/classes/AccountWebService.cls-meta.xml                                        |    5 
 scr/classes/RadiationUtilTest.cls                                                 |  607 
 scr/pages/OrderContract.page-meta.xml                                             |    7 
 scr/pages/CommunitiesSelfRegConfirm.page                                          |   28 
 scr/pages/AllAsset.page-meta.xml                                                  |    7 
 scr/pages/ChatterAnswersChangePassword.page                                       |    6 
 scr/classes/SWOUtil.cls                                                           |    3 
 scr/pages/SearchManagementCode.page-meta.xml                                      |    7 
 scr/classes/calendarUtil.cls-meta.xml                                             |    5 
 scr/staticresources/SiteSamples/img/unauthorized.png                              |    0 
 scr/classes/SBG004WebService.cls                                                  |  296 
 scr/staticresources/StageMapJsNew.resource-meta.xml                               |    5 
 scr/components/SiteFooter.component                                               |    3 
 scr/classes/DeliveryConfirmPDFControllerTest.cls                                  |  118 
 scr/pages/CommunitiesSelfRegConfirm.page-meta.xml                                 |    8 
 scr/classes/SBGITMRestTest.cls                                                    |  262 
 scr/triggers/RepairDetailsTrigger.trigger                                         |    5 
 scr/classes/BreachRecordSchedulable.cls                                           |    7 
 scr/classes/SBG010WebServiceTest.cls                                              |  174 
 scr/classes/SBGITMRestNewTest.cls                                                 |  348 
 scr/classes/NFMUtilTest.cls-meta.xml                                              |    5 
 scr/staticresources/SWO.resource-meta.xml                                         |    5 
 scr/classes/ControllerUtilTest.cls-meta.xml                                       |    5 
 scr/classes/RepairTriggerHandlerTest.cls                                          |  106 
 scr/pages/QuotesPDF.page-meta.xml                                                 |    7 
 scr/staticresources/SiteSamples/img/construction.png                              |    0 
 scr/pages/TrialCustomerPortalHomePage.page-meta.xml                               |    7 
 scr/classes/EquipmentLoanerApplyController.cls-meta.xml                           |    5 
 scr/pages/SearchSetProduct.page-meta.xml                                          |    7 
 scr/classes/AssetTriggerHandler.cls                                               |  364 
 scr/classes/NEWCreateSWOQuoteController.cls                                       |  745 
 scr/pages/OrderCSVExport.page-meta.xml                                            |    7 
 scr/staticresources/SWO.jpeg                                                      |    0 
 scr/pages/BandwidthExceeded.page-meta.xml                                         |    8 
 scr/classes/LogAutoSendSchedule.cls-meta.xml                                      |    5 
 scr/classes/SearchManagementControllerTest.cls-meta.xml                           |    5 
 scr/classes/LogAutoSendBatchProduct.cls-meta.xml                                  |    5 
 scr/classes/SBGITMRestNew.cls-meta.xml                                            |    5 
 scr/classes/StaticParameter.cls-meta.xml                                          |    5 
 scr/pages/OpportunityMessagePopUp.page-meta.xml                                   |    7 
 scr/triggers/AssetTrigger.trigger                                                 |    9 
 scr/pages/ca_tour_style.page                                                      |  224 
 scr/classes/OpportunityTriggerTest.cls                                            |  633 
 scr/pages/OrderInternalMessagePopup.page-meta.xml                                 |    7 
 scr/classes/SearchMemberPageControllerTest.cls                                    |   78 
 scr/pages/OrderShippingNotification.page                                          |   57 
 scr/pages/MessageBoardPoPuP.page                                                  |   51 
 scr/classes/OrderWebService.cls                                                   | 3224 +
 scr/classes/DeleteSSBatchTest.cls-meta.xml                                        |    5 
 scr/classes/CommunitiesLoginController.cls                                        |   14 
 scr/classes/UpdateTotalCostPriceSetTextBatch.cls                                  |   99 
 scr/classes/LoanerAppDetailTriggerHandler.cls-meta.xml                            |    5 
 scr/classes/SBG204RestTest.cls                                                    |   92 
 scr/classes/SiteRegisterControllerTest.cls                                        |   17 
 scr/classes/DeliveryTriggerHandler.cls                                            |   25 
 scr/classes/OrderPdfControllerTest.cls                                            |  601 
 scr/pages/ChatterAnswersHelp.page-meta.xml                                        |    8 
 scr/classes/IdentityContextPlugin.cls-meta.xml                                    |    5 
 scr/classes/LoanerExpressTriggerHandler.cls-meta.xml                              |    5 
 scr/classes/DataLoadAccountController.cls                                         | 1019 
 scr/pages/OpportunityCSVExport.page                                               |    7 
 scr/pages/QuoteCSVExport.page                                                     |    7 
 scr/classes/SBGITMRestNew.cls                                                     |  358 
 scr/classes/NetworkAccessTest.cls-meta.xml                                        |    5 
 scr/pages/NewCrossHighOpportunity.page                                            |  230 
 scr/pages/LoanerApplicationStockUpCheck.page-meta.xml                             |    7 
 scr/classes/CommunitiesSelfRegConfirmController.cls-meta.xml                      |    5 
 scr/pages/DeliveryConfirmPDF.page-meta.xml                                        |    7 
 scr/pages/LoanerApplicationPortionDeliver.page-meta.xml                           |    7 
 scr/classes/AllAssetControllerTest.cls-meta.xml                                   |    5 
 scr/classes/calendarUtil.cls                                                      |  155 
 scr/classes/SoftphoneConsoleController.cls-meta.xml                               |    5 
 scr/classes/SoftphoneConsoleController.cls                                        |   13 
 scr/classes/CampaignUpsertContactToSapBatchSchedule.cls-meta.xml                  |    5 
 scr/classes/SBG017WebService.cls-meta.xml                                         |    5 
 scr/classes/test001Controller.cls                                                 |    9 
 scr/classes/CaseEmailComeBackListen.cls                                           |   89 
 scr/pages/OrderApproveAlert.page                                                  |   21 
 scr/classes/ControllerUtilTest.cls                                                |    8 
 scr/pages/ApplicationMessage.page-meta.xml                                        |    7 
 scr/classes/NewLoanerApplicationControllerTest.cls                                |   97 
 scr/classes/ProRegisterHandlerTest.cls                                            |  191 
 scr/pages/OpportunityAAdvanced.page-meta.xml                                      |    7 
 scr/classes/LoanerReceiveGoodsController.cls                                      |  152 
 scr/classes/SBG005WebService.cls-meta.xml                                         |    5 
 scr/triggers/OrderItemTrigger.trigger                                             |   11 
 scr/pages/CTITest.page-meta.xml                                                   |    7 
 scr/triggers/UpdateLogisticsInformation.trigger-meta.xml                          |    5 
 scr/classes/NewRepairPartsController.cls                                          |   96 
 scr/classes/SWOSearchProductContarollerTest.cls-meta.xml                          |    5 
 scr/classes/OrderMessageControllerTest.cls-meta.xml                               |    5 
 scr/pages/SearchManagementCode.page                                               |  178 
 scr/classes/SBG203RestTest.cls-meta.xml                                           |    5 
 scr/classes/TOTPPluginTest.cls                                                    |   47 
 scr/pages/Unauthorized.page                                                       |   38 
 scr/triggers/QuoteTrigger.trigger-meta.xml                                        |    5 
 scr/staticresources/jquerysuggestjs.resource-meta.xml                             |    5 
 scr/pages/MicrobatchSelfReg.page                                                  |   24 
 scr/triggers/TaskTrigger.trigger                                                  |   10 
 scr/staticresources/cti.resource-meta.xml                                         |    5 
 scr/classes/SBG204Rest.cls-meta.xml                                               |    5 
 scr/staticresources/SiteSamples/img/warning.png                                   |    0 
 scr/classes/DeleteSSBatchTest.cls                                                 |    6 
 scr/pages/ApplicationMessagePopUp.page                                            |   51 
 scr/classes/SBG001TriggerHandler.cls                                              | 1057 
 scr/classes/SBG010TRestTest.cls                                                   |  263 
 scr/pages/LoanerApplicationStockUp.page-meta.xml                                  |    7 
 scr/classes/BreachRecordSchedulable.cls-meta.xml                                  |    5 
 scr/classes/LogAutoSendScheduleProductTest.cls-meta.xml                           |    5 
 scr/classes/OpportunityTriggerHandler.cls                                         | 1512 
 scr/classes/OrderPdf2Controller.cls                                               | 1355 
 scr/classes/SearchManagementController.cls-meta.xml                               |    5 
 scr/classes/LoanerExpressTriggerHandler.cls                                       |  178 
 scr/classes/SSOpportunitySchedule.cls-meta.xml                                    |    5 
 scr/triggers/ProRegister.trigger                                                  |   12 
 scr/staticresources/pdfSign.resource-meta.xml                                     |    5 
 scr/pages/OrderInternalMessage.page-meta.xml                                      |    7 
 scr/classes/LoanerPortionReturnController.cls                                     |  251 
 scr/pages/QuotePDF.page                                                           |  163 
 scr/classes/CertificationDetailTriggerHandler.cls                                 |   56 
 scr/pages/NewLoanerUser.page-meta.xml                                             |    7 
 scr/classes/SBG010TRestTest.cls-meta.xml                                          |    5 
 scr/pages/ChatterAnswersForgotPassword.page                                       |    6 
 scr/classes/EmailComeBackListenTest.cls                                           |   90 
 scr/classes/AccountTriggerHandler.cls-meta.xml                                    |    5 
 scr/classes/TydelikeConControllerTest.cls-meta.xml                                |    5 
 scr/classes/TSRepairControllerTest.cls                                            |  326 
 scr/classes/TydelikeConControllerTest.cls                                         |  236 
 scr/classes/LoanerApplicationStockUpController.cls-meta.xml                       |    5 
 scr/classes/OpportunityWebService.cls-meta.xml                                    |    5 
 scr/classes/ApplicationMessageController.cls-meta.xml                             |    5 
 scr/pages/PersonalProcessInstance.page                                            |  158 
 scr/pages/LoanerApplicationPortionDeliver.page                                    |  119 
 scr/classes/OpportunityUpdateSendEmailSchedulable.cls                             |    5 
 scr/classes/NewQuoteDevideControllerTest.cls                                      |   69 
 scr/pages/NewOrder.page-meta.xml                                                  |    7 
 scr/classes/Product2TriggerHandlerTest.cls-meta.xml                               |    5 
 scr/pages/TS_SearchAccount.page                                                   |    8 
 scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls-meta.xml                    |    5 
 scr/pages/CanNotDeleteCase.page-meta.xml                                          |    7 
 scr/pages/IdeasHome.page-meta.xml                                                 |    8 
 scr/classes/OrdertoZhaoEmailSchedulable.cls-meta.xml                              |    5 
 scr/classes/AssetTurnoverSchedulable.cls-meta.xml                                 |    5 
 scr/classes/LoanerApplicationFlowController.cls-meta.xml                          |    5 
 scr/classes/NEWCreateSWOQuoteController.cls-meta.xml                              |    5 
 scr/classes/SBGITMWebService.cls                                                  |  266 
 scr/classes/QuoteLineItemTriggerHandler.cls-meta.xml                              |    5 
 scr/pages/NewQuoteDevide.page                                                     |    2 
 scr/classes/OpportunityVisitNotesController.cls                                   |  116 
 scr/classes/SBG010Rest.cls                                                        |  235 
 scr/triggers/RepairTrigger.trigger-meta.xml                                       |    5 
 scr/classes/NewCrossHighOpportunityController.cls                                 |  128 
 scr/pages/SWOPage.page                                                            | 1787 
 scr/classes/NewSearchProductController.cls-meta.xml                               |    5 
 scr/classes/PrototypeToThaw.cls-meta.xml                                          |    5 
 scr/pages/CampaignRelationship.page-meta.xml                                      |    7 
 scr/staticresources/CommonUtilJs.js                                               |   64 
 scr/classes/SearchMemberPageControllerTest.cls-meta.xml                           |    5 
 scr/staticresources/SiteSamples/img/poweredby.png                                 |    0 
 scr/classes/OpportunityUpdateSendEmailSchedulable.cls-meta.xml                    |    5 
 scr/classes/SBG027TriggerHandleTest.cls-meta.xml                                  |    5 
 scr/pages/OrderShippingNotification.page-meta.xml                                 |    7 
 scr/classes/SBG004Rest.cls                                                        |  336 
 scr/classes/OpportunityTriggerHandler.cls-meta.xml                                |    5 
 scr/triggers/ServiceSummaryTrigger.trigger                                        |   11 
 scr/classes/Sbg007Sync.cls                                                        |   91 
 scr/staticresources/pdfSign.gif                                                   |    0 
 scr/classes/CampaignUpsertContactToSapBatch.cls-meta.xml                          |    5 
 scr/triggers/QuoteTrigger.trigger                                                 |   17 
 scr/pages/Unauthorized.page-meta.xml                                              |    8 
 scr/classes/OrderDivisionController.cls                                           | 1193 
 scr/classes/OrderPdf2ControllerTest.cls                                           |  845 
 scr/pages/OrderMessage.page-meta.xml                                              |    7 
 scr/triggers/CertificationDetailTrigger.trigger-meta.xml                          |    5 
 scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls                            |  150 
 scr/classes/SBG017Rest.cls-meta.xml                                               |    5 
 scr/classes/BreachRecordBatchTest.cls-meta.xml                                    |    5 
 scr/classes/MicrobatchSelfRegController.cls                                       |   57 
 scr/pages/ChatterAnswersForgotPassword.page-meta.xml                              |    8 
 scr/classes/ChatterAnswersEscalationTriggerTest.cls-meta.xml                      |    5 
 scr/classes/LicenseCheckUtil.cls-meta.xml                                         |    5 
 scr/classes/oppbatch.cls-meta.xml                                                 |    5 
 1,059 files changed, 124,849 insertions(+), 0 deletions(-)

diff --git a/scr/aura/.eslintrc.json b/scr/aura/.eslintrc.json
new file mode 100644
index 0000000..226a5a2
--- /dev/null
+++ b/scr/aura/.eslintrc.json
@@ -0,0 +1,8 @@
+{
+  "plugins": ["@salesforce/eslint-plugin-aura"],
+  "extends": ["plugin:@salesforce/eslint-plugin-aura/recommended"],
+  "rules": {
+    "vars-on-top": "off",
+    "no-unused-expressions": "off"
+  }
+}
diff --git a/scr/classes/AccountTriggerHandler.cls b/scr/classes/AccountTriggerHandler.cls
new file mode 100644
index 0000000..63f44a9
--- /dev/null
+++ b/scr/classes/AccountTriggerHandler.cls
@@ -0,0 +1,2231 @@
+public without sharing class AccountTriggerHandler {
+
+    public static void setBusinesslicense(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+
+        Map<String, String> businesslicenseMap = new Map<String, String>();
+        for (Account newAcc : newList) {
+            if (newAcc.ParentId == null && String.isNotBlank(newAcc.Business_license__c) &&
+                    newAcc.ProductSegment__c == 'BS' && newAcc.RecordTypeId == '012280000005gnE') {
+                businesslicenseMap.put(newAcc.Id, newAcc.Business_license__c);
+            }
+        }
+
+        if ( businesslicenseMap.size() > 0) {
+            List<Account> accountList = [select Id, Name, ParentId, Business_license__c
+                                         from Account
+                                         where ParentId In:businesslicenseMap.keySet()];
+            if (accountList.size() > 0) {
+
+                for (Account acc : accountList) {
+
+                    acc.Business_license__c = businesslicenseMap.get(acc.ParentId);
+                }
+                update accountList;
+            }
+
+        }
+
+    }
+    public static void setIsNew(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+        //褰撳墠鐧婚檰浜篒D
+        String now_userId = UserInfo.getUserId();
+        for (Account newAcc : newList) {
+            // String profileId = UserInfo.getProfileId().subString(0, 15);
+            //鏂扮殑鑾峰彇浜哄憳绠�妗D
+            String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+            //鏂板鏉冮檺鏁寸悊2021-05-10
+            if (new_profileId.subString(0, 15) == System.label.Market_Department || new_profileId.subString(0, 15) == System.label.Market_Department1 || new_profileId.subString(0, 15) == System.label.Service_Owner || new_profileId.subString(0, 15) == System.label.Service_OwnerMinister 
+                    || UserInfo.getUserType() == 'PowerPartner' || new_profileId.subString(0, 15) == System.label.IEPrototypeManager || newAcc.RecordTypeId == '0120T0000003Cxt') {
+            //鏂板鏉冮檺鏁寸悊2021-05-10
+                newAcc.IsNew__c = true;
+            } else {
+                newAcc.WebsiteD__c = newAcc.Website;
+                newAcc.FaxD__c = newAcc.Fax;
+                //newAcc.CreatedByD__c = newAcc.CreatedBy;
+                newAcc.PhoneD__c = newAcc.Phone;
+                newAcc.Address1D__c = newAcc.Address1__c;
+                newAcc.AssetANI4D__c = newAcc.AssetANI4__c;
+                newAcc.AssetIE7D__c = newAcc.AssetIE7__c;
+                newAcc.AssetNDT7D__c = newAcc.AssetNDT7__c;
+                //newAcc.DealerD__c = newAcc.DealerName__c;
+                //newAcc.DepartmentNameD__c = newAcc.DepartmentName__c;
+                //newAcc.DivisionNameD__c = newAcc.DivissionName__c;
+                newAcc.AssetRVI5D__c = newAcc.AssetRVI5__c;
+                newAcc.EnglishNameD__c = newAcc.EnglishName__c;
+                //newAcc.ExportRegulatedCustomerD__c = newAcc.Export_Regulated_Customer__c;
+                //newAcc.FacilityNameD__c = newAcc.FacilityName__c;
+                newAcc.AssetRVI2D__c = newAcc.AssetRVI2__c;
+                newAcc.AssetNDT4D__c = newAcc.AssetNDT4__c;
+                newAcc.IndustryCD__c = newAcc.IndustryC__c;
+                newAcc.AssetRVI4D__c = newAcc.AssetRVI4__c;
+                newAcc.AssetRVI3D__c = newAcc.AssetRVI3__c;
+                //newAcc.KeyAccountD__c = newAcc.KeyAccount__c;
+                newAcc.AssetIE5D__c = newAcc.AssetIE5__c;
+                newAcc.AssetBS3D__c = newAcc.AssetBS3__c;
+                newAcc.AssetIE3D__c = newAcc.AssetIE3__c;
+                newAcc.AssetANI7D__c = newAcc.AssetANI7__c;
+                newAcc.AssetNDT6D__c = newAcc.AssetNDT6__c;
+                newAcc.MarketVerticalsD__c = newAcc.MarketVerticals__c;
+                newAcc.AssetIE6D__c = newAcc.AssetIE6__c;
+                newAcc.AssetIE2D__c = newAcc.AssetIE2__c;
+                newAcc.AssetBS2D__c = newAcc.AssetBS2__c;
+                newAcc.AssetANI3D__c = newAcc.AssetANI3__c;
+                newAcc.AssetIE1D__c = newAcc.AssetIE1__c;
+                newAcc.AssetBS1D__c = newAcc.AssetBS1__c;
+                newAcc.AssetRVI1D__c = newAcc.AssetRVI1__c;
+                newAcc.AssetNDT1D__c = newAcc.AssetNDT1__c;
+                newAcc.AssetANI1D__c = newAcc.AssetANI1__c;
+                newAcc.AssetNDT8D__c = newAcc.AssetNDT8__c;
+                newAcc.AssetANI8D__c = newAcc.AssetANI8__c;
+                newAcc.AssetBS5D__c = newAcc.AssetBS5__c;
+                newAcc.AssetIE8D__c = newAcc.AssetIE8__c;
+                newAcc.AssetRVI8D__c = newAcc.AssetRVI8__c;
+                newAcc.AssetANI5D__c = newAcc.AssetANI5__c;
+                //newAcc.ProvinceD__c = newAcc.Province__c;
+                newAcc.AssetRVI6D__c = newAcc.AssetRVI6__c;
+                newAcc.AssetANI2D__c = newAcc.AssetANI2__c;
+                newAcc.AssetNDT3D__c = newAcc.AssetNDT3__c;
+                newAcc.AssetNDT2D__c = newAcc.AssetNDT2__c;
+                newAcc.AssetANI6D__c = newAcc.AssetANI6__c;
+                //IE涓嶭S鍒嗛噹鐨勫鍔犱笌淇敼
+                newAcc.Sub_UseA__c = newAcc.Sub_Use1__c;
+                newAcc.Sub_UseD__c = newAcc.Sub_Use__c;
+                newAcc.IndustryBD__c = newAcc.IndustryB__c;
+               
+                //IE涓嶭S鍒嗛噹鐨勫鍔犱笌淇敼
+                newAcc.UseD__c = newAcc.Use__c;
+                newAcc.AssetRVI7D__c = newAcc.AssetRVI7__c;
+                newAcc.AssetBS4D__c = newAcc.AssetBS4__c;
+                newAcc.AssetIE4D__c = newAcc.AssetIE4__c;
+                newAcc.AssetNDT5D__c = newAcc.AssetNDT5__c;
+                newAcc.AccountStatusD__c = newAcc.AccountStatus__c;
+                newAcc.CancelReasonD__c = newAcc.CancelReason__c;
+                newAcc.CityD__c = newAcc.City__c;
+                newAcc.PostCodeD__c = newAcc.PostCode__c;
+                newAcc.DealerSelectOwner__c = newAcc.OwnerId;
+                newAcc.FacilityNameD__c = newAcc.FacilityName__c;
+                newAcc.DivisionName_D__c = newAcc.DivisionName__c;
+                newAcc.DepartmentNameD__c = newAcc.DepartmentName__c;
+                if (new_profileId.subString(0,15) == '00e28000000YKLo') {
+                    newAcc.IsNew__c = true;
+                }
+               
+            }
+            //gwy 2021-06-04 LS 鏂板蹇呭~椤筄EM瀹㈡埛鐨勬爣璇�
+            if(newAcc.UserType__c == 'OEM瀹㈡埛' && newAcc.ProductSegment__c == 'BS'){
+                newAcc.Whether_OEM__c = true;
+            }
+            //鐜嬮箯浼熸坊鍔� 鏈嶅姟閮ㄥ垱寤哄鎴枫�佽仈绯讳汉
+            //00528000000YWC6 瀛� 瀛︽磱 00528000000YWC6
+            //00528000000YWE7 鍚� 鏅撲笢 00528000000YWE7
+            //00e28000000YQMx 绠�妗o細SSBG鎶�鏈湇鍔¢儴锛堥儴闀裤兓鍓儴闀匡級00e28000000YQMx
+            //00e28000001sZE6 绠�妗o細SSBG鎶�鏈湇鍔¢儴鎷呭綋 00e28000001sZE6
+            // System.debug('profileId:' + profileId);
+            System.debug('DealerSelectOwner__c:' + newAcc.DealerSelectOwner__c);
+            if ((now_userId == '00528000000YWC6' || now_userId == '00528000000YWE7' || new_profileId.subString(0, 15) == '00e28000000YQMx' || new_profileId.subString(0, 15) == '00e28000001sZE6'
+            //鏂板鏉冮檺鏁寸悊2021-05-10
+                || new_profileId.subString(0, 15) == '00e28000000YQMx' || new_profileId.subString(0, 15) == '00e28000001sZE6')
+            //鏂板鏉冮檺鏁寸悊2021-05-10
+                && String.isNotBlank(newAcc.DealerSelectOwner__c)){
+                newAcc.OwnerId = newAcc.DealerSelectOwner__c;
+            }
+            //鐜嬮箯浼熸坊鍔犵粨鏉�
+            //gwy 2021-06-08 瀹㈡埛鍙栨秷閭紪蹇呭~椤�
+            //newAcc.PostCode__c = newAcc.PostCode__c == null ? '000000' : newAcc.PostCode__c;
+            //newAcc.PostCodeD__c = newAcc.PostCodeD__c == null ? '000000' : newAcc.PostCodeD__c;
+        }
+    }
+
+    public static void setSubUse(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+    //subuse浠g爜浼樺寲,涔嬪墠鐨剆ubuse鐨勫�煎拰璧嬪�肩殑涓変釜瀛楁,鏀惧埌BatchIF杞箟琛ㄩ噷闈€��
+        List<String> externalList = new List<String>();
+        for (Account acc : newList) {
+            //2021-06-07 gwy 娣诲姞浠g爜(鑷姩濉�夐」)
+            String recordTypeId = acc.RecordTypeId;
+            recordTypeId = recordTypeId.substring(0,15);
+            // String recordTypeId = acc.RecordTypeId;
+            //鎷兼帴鍊硷紝骞朵笖鎶婂�煎叏閮ㄦ斁杩涘垪琛ㄩ噷
+            String externalValue = recordTypeId + ':' + acc.Sub_UseD__c;
+            String externalValue1 = recordTypeId + ':' + acc.Sub_Use__c;
+            if(acc.Sub_UseD__c != acc.Sub_Use__c){
+               externalList.add(externalValue);
+               externalList.add(externalValue1); 
+            }else{
+               externalList.add(externalValue);
+            }
+                
+        } 
+        //鍒涘缓涓�涓猰ap,缁忚繃soql鏂囨煡璇㈠悗,绗﹀悎鏉′欢,鏀惧叆map銆�
+        Map<String,String> batchIFMap= new Map<String,String>();
+        if (externalList.size()>0) {
+            List<BatchIF_Transfer__c> batchIFList = new List<BatchIF_Transfer__c>();
+            batchIFList = [select External_Value__c,Internal_Value__c from BatchIF_Transfer__c where External_Value__c In: externalList];
+            for (BatchIF_Transfer__c bt : batchIFList) {
+            batchIFMap.put(bt.External_Value__c,bt.Internal_Value__c);
+            }
+        }
+
+        //瀹氫箟List,浠巑ap鍙栧��,杩涜鍒嗗壊璧嬪�笺�傛湁鍙樺寲鐨勫氨缁欎粬閲嶆柊璧嬪�笺��
+        List<String> btList = new List<String>();
+        for (Account acc : newList){
+            String recordTypeid = acc.RecordTypeId;
+            recordTypeid = recordTypeid.substring(0,15);
+            String externalVal = recordTypeid + ':' + acc.Sub_UseD__c;
+            String externalVal1 = recordTypeid + ':' + acc.Sub_Use__c;
+            //acc.Sub_UseD__c
+            if(batchIFMap.containsKey(externalVal)){
+                btList = batchIFMap.get(externalVal).split(';');
+                    acc.IndustryCD__c       = btList[0];
+                    acc.MarketVerticalsD__c = btList[1];
+                    acc.UseD__c             = btList[2];
+            }else{
+                //娌℃湁鍙樺寲鐨勪笉绠★紝涓虹┖鐨勬垨鑰呭彉涓虹┖鐨勭粰浠栬祴鍊间负绌恒��
+                if ((acc.ProductSegment__c == 'NDT' || acc.ProductSegment__c == 'IE' || acc.ProductSegment__c == 'RVI' || acc.ProductSegment__c == 'ANI') && acc.Sub_UseD__c == null) {
+                    acc.IndustryCD__c       = null;
+                    acc.MarketVerticalsD__c = null;
+                    acc.UseD__c             = null;
+                }     
+            }
+            //acc.Sub_Use__c
+            if(batchIFMap.containsKey(externalVal1)){
+                btList = batchIFMap.get(externalVal1).split(';');
+                    acc.IndustryC__c       = btList[0];
+                    acc.MarketVerticals__c = btList[1];
+                    acc.Use__c             = btList[2];
+            }else{
+                //娌℃湁鍙樺寲鐨勪笉绠★紝涓虹┖鐨勬垨鑰呭彉涓虹┖鐨勭粰浠栬祴鍊间负绌恒��
+                if ((acc.ProductSegment__c == 'NDT' || acc.ProductSegment__c == 'IE' || acc.ProductSegment__c == 'RVI' || acc.ProductSegment__c == 'ANI') && acc.Sub_Use__c == null) {
+                    acc.IndustryC__c       = null;
+                    acc.MarketVerticals__c = null;
+                    acc.Use__c             = null;
+                }     
+            }
+        }
+    }
+
+        
+        
+
+        // for (Account newAcc : newList) {
+        //     Account oldAcc = oldMap == null ? null : oldMap.get(newAcc.Id);
+        //     //2021-06-07 gwy 娣诲姞浠g爜(鑷姩濉�夐」) 
+        //     if (newAcc.Sub_UseA__c != null) {
+        //         newAcc.Sub_UseD__c = newAcc.Sub_UseA__c;
+        //     }
+        //         system.debug('====='+ oldAcc == null );
+        //         system.debug('=====recordTypeId' + newAcc.recordTypeId);
+        //         system.debug('=====Sub_UseD__c' + newAcc.Sub_UseD__c);
+                
+        //     if (oldAcc == null || newAcc.Sub_UseD__c != oldAcc.Sub_UseD__c) {
+                
+        //         system.debug('=====');
+        //         system.debug('=====recordTypeId' + newAcc.recordTypeId);
+        //         system.debug('=====Sub_UseD__c' + newAcc.Sub_UseD__c);
+
+                // if (newAcc.recordTypeId == '01228000000TdF6') {
+                //     if (newAcc.Sub_UseD__c == null || newAcc.Sub_UseD__c == '') {
+                        // newAcc.IndustryCD__c = null;
+                        // newAcc.MarketVerticalsD__c = null;
+                        // newAcc.UseD__c = null;
+                    // } else if (newAcc.Sub_UseD__c == 'LED') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == 'FPD') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '鍗婂浣�') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Semiconductor';
+                    // } else if (newAcc.Sub_UseD__c == '鐢靛瓙閮ㄥ搧') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '澶槼鑳�') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '鐢靛瓙绫籣鍏朵粬') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '閲戝睘') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Casting';
+                    // } else if (newAcc.Sub_UseD__c == '浼犵粺姹借溅') {
+                    //     newAcc.IndustryCD__c = 'Automotive';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Automotive Body/Engine';
+                    // } else if (newAcc.Sub_UseD__c == '鐭虫补鍦拌川') {
+                    //     newAcc.IndustryCD__c = 'Mining/Geology';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Geology : Geological Surveys';
+                    // } else if (newAcc.Sub_UseD__c == '浜旈噾妯″叿') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Machined Parts';
+                    // } else if (newAcc.Sub_UseD__c == '閲嶅伐璁惧') {
+                    //     newAcc.IndustryCD__c = 'Fabricated Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing) Other';
+                    // } else if (newAcc.Sub_UseD__c == '鏉愭枡绫籣鍏朵粬') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Industrial Scientific research';
+                    // } else if (newAcc.Sub_UseD__c == '鍖荤枟鍣ㄦ') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing) Other';
+                    // } else if (newAcc.Sub_UseD__c == '婵�鍏夊姞宸�') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing) Other';
+                    // } else if (newAcc.Sub_UseD__c == '鍒惰嵂') {
+                    //     newAcc.IndustryCD__c = 'Pharmaceutical';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing) Other';
+                    // } else if (newAcc.Sub_UseD__c == '鍔ㄦ鐗�') {
+                    //     newAcc.IndustryCD__c = 'Food/Feed/Agriculture';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // } else if (newAcc.Sub_UseD__c == '鏂拌兘婧愭苯杞�') {
+                    //     newAcc.IndustryCD__c = 'Automotive';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Automotive Body/Engine';
+                    // } else if (newAcc.Sub_UseD__c == '5G-PCB') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '5G-鍗婂浣�') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '5G-鍏朵粬') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鍗婂浣�-鍓嶉亾') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鍗婂浣�-涓湡') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鍗婂浣�-鍚庨亾') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-FPD') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-3D 娴嬮噺浠�') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-娴嬭瘯浠櫒') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鎷夋浖鍏夎氨浠�') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-琛�娑�') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-灏挎恫/绮究') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-缁嗚優瀛�') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-閬椾紶瀛�') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鐥呯悊') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鐢熸畺') {
+                    //     newAcc.IndustryCD__c = 'Medical Device/Equipment';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-楂樼鏄惧井闀�') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-缁嗚優瑙傚療') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鐢靛瓙鏄惧井闀�') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-楂樺唴娑�') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-娴佸紡缁嗚優浠�') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-ODM') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-绮惧噯鍖荤枟') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                    // } else if (newAcc.Sub_UseD__c == 'Compo-鍏朵粬') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = '(Manufacturing)OEM';
+                //     }
+                // } else if (newAcc.recordTypeId == '01228000000TdFG') {
+                //     if (newAcc.Sub_UseD__c == null || newAcc.Sub_UseD__c == '') {
+                //         newAcc.IndustryCD__c = null;
+                //         newAcc.MarketVerticalsD__c = null;
+                //         newAcc.UseD__c = null;
+                    // } else if (newAcc.Sub_UseD__c == 'Automotive') {
+                    //     newAcc.IndustryCD__c = 'Automotive';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Automotive Body/Engine';
+                    // } else if (newAcc.Sub_UseD__c == 'Civil Aviation') {
+                    //     newAcc.IndustryCD__c = 'Aerospace';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = '(Maintenance)Aviation Airframe/Engine';
+                    // } else if (newAcc.Sub_UseD__c == 'Security/Defense') {
+                    //     newAcc.IndustryCD__c = 'Government/Security/Defense';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // } else if (newAcc.Sub_UseD__c == 'Oil,Gas&Chemical') {
+                    //     newAcc.IndustryCD__c = 'Chemical/Petrochemical/Plastics';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Weld Inspection';
+                    // } else if (newAcc.Sub_UseD__c == 'Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Heat Exchangers';
+                    // } else if (newAcc.Sub_UseD__c == 'General Manufacturing') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Machined Parts';
+                    // } else if (newAcc.Sub_UseD__c == 'Inspection/Service/Rental') {
+                    //     newAcc.IndustryCD__c = 'Inspection/Lab/Rental Sevice Provider';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Process Piping';
+                    // } else if (newAcc.Sub_UseD__c == 'Others') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // } else if (newAcc.Sub_UseD__c == 'Thermal Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Process piping';
+                    // } else if (newAcc.Sub_UseD__c == 'Nuclear Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Process piping';
+                    // } else if (newAcc.Sub_UseD__c == 'Wind Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Weld Inspection';
+                    // } else if (newAcc.Sub_UseD__c == 'Power(other)') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Corrosion';
+                //     }
+                // } else if (newAcc.recordTypeId == '01228000000TdFB') {
+                //     if (newAcc.Sub_UseD__c == null || newAcc.Sub_UseD__c == '') {
+                //         newAcc.IndustryCD__c = null;
+                //         newAcc.MarketVerticalsD__c = null;
+                //         newAcc.UseD__c = null;
+                    // } else if (newAcc.Sub_UseD__c == 'Automotive') {
+                    //     newAcc.IndustryCD__c = 'Automotive';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Automotive Body/Engine';
+                    // } else if (newAcc.Sub_UseD__c == 'Civil Aviation') {
+                    //     newAcc.IndustryCD__c = 'Aerospace';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = '(Maintenance)Aviation Airframe/Engine';
+                    // } else if (newAcc.Sub_UseD__c == 'Security/Defense') {
+                    //     newAcc.IndustryCD__c = 'Government/Security/Defense';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // } else if (newAcc.Sub_UseD__c == 'Oil,Gas&Chemical') {
+                    //     newAcc.IndustryCD__c = 'Chemical/Petrochemical/Plastics';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Weld Inspection';
+                    // } else if (newAcc.Sub_UseD__c == 'Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Heat Exchangers';
+                    // } else if (newAcc.Sub_UseD__c == 'General Manufacturing') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Machined Parts';
+                    // } else if (newAcc.Sub_UseD__c == 'Inspection/Service/Rental') {
+                    //     newAcc.IndustryCD__c = 'Inspection/Lab/Rental Sevice Provider';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Process Piping';
+                    // } else if (newAcc.Sub_UseD__c == 'Others') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // } else if (newAcc.Sub_UseD__c == 'Thermal Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Heat Exchangers';
+                    // } else if (newAcc.Sub_UseD__c == 'Nuclear Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Process Piping';
+                    // } else if (newAcc.Sub_UseD__c == 'Wind Power') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Gear Box';
+                    // } else if (newAcc.Sub_UseD__c == 'Power(other)') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'Corrosion';
+                //     }
+                // } else if (newAcc.recordTypeId == '01228000000TdFL') {
+                //     if (newAcc.Sub_UseD__c == null || newAcc.Sub_UseD__c == '') {
+                //         newAcc.IndustryCD__c = null;
+                //         newAcc.MarketVerticalsD__c = null;
+                //         newAcc.UseD__c = null;
+                    // } else if (newAcc.Sub_UseD__c == '搴熸棫閲戝睘') {
+                    //     newAcc.IndustryCD__c = 'Recycling';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Alloy : Recycling';
+                    // } else if (newAcc.Sub_UseD__c == '鐐奸挗鍘�') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Tube/Rod/Bar/Sheet Metal';
+                    // } else if (newAcc.Sub_UseD__c == 'PMI-鐭冲寲琛屼笟') {
+                    //     newAcc.IndustryCD__c = 'Chemical/Petrochemical/Plastics';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'PMI';
+                    // } else if (newAcc.Sub_UseD__c == 'PMI-绠¢亾鍒堕��') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Pipelines';
+                    // } else if (newAcc.Sub_UseD__c == 'PMI-閲戝睘鍒堕��') {
+                    //     newAcc.IndustryCD__c = 'Metal Manufacturing';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Machined Parts';
+                    // } else if (newAcc.Sub_UseD__c == 'PMI-鐢靛姏') {
+                    //     newAcc.IndustryCD__c = 'Power Generation';
+                    //     newAcc.MarketVerticalsD__c = 'Maintenance';
+                    //     newAcc.UseD__c = 'PMI';
+                    // } else if (newAcc.Sub_UseD__c == 'RoHS') {
+                    //     newAcc.IndustryCD__c = 'Electronics';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == 'ELV') {
+                    //     newAcc.IndustryCD__c = 'Automotive';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Electronic Device';
+                    // } else if (newAcc.Sub_UseD__c == '鐜╁叿&鐨潻') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Consumer Goods';
+                    // } else if (newAcc.Sub_UseD__c == '璐甸噾灞�-鍒堕��') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Consumer Goods';
+                    // } else if (newAcc.Sub_UseD__c == '璐甸噾灞�-鍥炴敹') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Alloy : Precious Metals Recycling';
+                    // } else if (newAcc.Sub_UseD__c == '鍕樻帰-鏀垮簻') {
+                    //     newAcc.IndustryCD__c = 'Mining/Geology';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Geology : Geological Surveys';
+                    // } else if (newAcc.Sub_UseD__c == '鍕樻帰-鐭夸笟鍏徃') {
+                    //     newAcc.IndustryCD__c = 'Mining/Geology';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Mining : Exploration';
+                    // } else if (newAcc.Sub_UseD__c == 'Mining-鍐剁偧') {
+                    //     newAcc.IndustryCD__c = 'Mining/Geology';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Mining : Processing & Refining & Metallurgy';
+                    // } else if (newAcc.Sub_UseD__c == 'Mining-寮�閲�') {
+                    //     newAcc.IndustryCD__c = 'Mining/Geology';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Mining : Production & Grade Control';
+                    // } else if (newAcc.Sub_UseD__c == 'EPA') {
+                    //     newAcc.IndustryCD__c = 'Government/Security/Defense';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Regulatory : Enviro-Soil';
+                    // } else if (newAcc.Sub_UseD__c == '鍦熷¥淇') {
+                    //     newAcc.IndustryCD__c = 'Recycling';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Regulatory : Enviro-Soil';
+                    // } else if (newAcc.Sub_UseD__c == '鍦熷¥鐮旂┒') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Regulatory : Enviro-Soil';
+                    // } else if (newAcc.Sub_UseD__c == '鑰冨彜&鏂囩墿') {
+                    //     newAcc.IndustryCD__c = 'Academic Research';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // } else if (newAcc.Sub_UseD__c == '褰曚簳') {
+                    //     newAcc.IndustryCD__c = 'Oil & Gas';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Mining : Exploration';
+                    // } else if (newAcc.Sub_UseD__c == '鍒惰嵂') {
+                    //     newAcc.IndustryCD__c = 'Pharmaceutical';
+                    //     newAcc.MarketVerticalsD__c = 'Manufacturing';
+                    //     newAcc.UseD__c = 'Chemical/Plastics/Rubber';
+                    // } else if (newAcc.Sub_UseD__c == '涓夊厓鍌寲鍓�') {
+                    //     newAcc.IndustryCD__c = 'Automotive';
+                    //     newAcc.MarketVerticalsD__c = 'Natural Resources';
+                    //     newAcc.UseD__c = 'Alloy : Precious Metals Recycling';
+                    // } else if (newAcc.Sub_UseD__c == 'Others') {
+                    //     newAcc.IndustryCD__c = 'Other';
+                    //     newAcc.MarketVerticalsD__c = 'Other';
+                    //     newAcc.UseD__c = '(Other) Other';
+                    // }Add 涓夊厓鍌寲鍓�  by 绗︽檽鏋� 2016骞�6鏈�6鏃�
+                
+            // if (oldAcc == null || newAcc.Sub_Use__c != oldAcc.Sub_Use__c) {
+            //     system.debug('=====');
+            //     system.debug('=====recordTypeId' + newAcc.recordTypeId);
+            //     system.debug('=====Sub_Use__c' + newAcc.Sub_Use__c);
+            //     if (newAcc.recordTypeId == '01228000000TdF6') {
+            //         //2021-06-07 gwy 娣诲姞浠g爜(鑷姩濉�夐」)
+            //         if (newAcc.Sub_Use__c == null || newAcc.Sub_Use__c == '') {
+            //             newAcc.IndustryC__c = null;
+            //             newAcc.MarketVerticals__c = null;
+            //             newAcc.Use__c = null;
+            //         } else if (newAcc.Sub_Use__c == 'LED') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == 'FPD') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '鍗婂浣�') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Semiconductor';
+            //         } else if (newAcc.Sub_Use__c == '鐢靛瓙閮ㄥ搧') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '澶槼鑳�') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '鐢靛瓙绫籣鍏朵粬') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '閲戝睘') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Casting';
+            //         } else if (newAcc.Sub_Use__c == '浼犵粺姹借溅') {
+            //             newAcc.IndustryC__c = 'Automotive';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Automotive Body/Engine';
+            //         } else if (newAcc.Sub_Use__c == '鐭虫补鍦拌川') {
+            //             newAcc.IndustryC__c = 'Mining/Geology';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Geology : Geological Surveys';
+            //         } else if (newAcc.Sub_Use__c == '浜旈噾妯″叿') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Machined Parts';
+            //         } else if (newAcc.Sub_Use__c == '閲嶅伐璁惧') {
+            //             newAcc.IndustryC__c = 'Fabricated Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing) Other';
+            //         } else if (newAcc.Sub_Use__c == '鏉愭枡绫籣鍏朵粬') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Industrial Scientific research';
+            //         } else if (newAcc.Sub_Use__c == '鍖荤枟鍣ㄦ') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing) Other';
+            //         } else if (newAcc.Sub_Use__c == '婵�鍏夊姞宸�') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing) Other';
+            //         } else if (newAcc.Sub_Use__c == '鍒惰嵂') {
+            //             newAcc.IndustryC__c = 'Pharmaceutical';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing) Other';
+            //         } else if (newAcc.Sub_Use__c == '鍔ㄦ鐗�') {
+            //             newAcc.IndustryC__c = 'Food/Feed/Agriculture';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         } else if (newAcc.Sub_Use__c == '鏂拌兘婧愭苯杞�') {
+            //             newAcc.IndustryC__c = 'Automotive';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Automotive Body/Engine';
+            //         } else if (newAcc.Sub_Use__c == '5G-PCB') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '5G-鍗婂浣�') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '5G-鍏朵粬') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鍗婂浣�-鍓嶉亾') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鍗婂浣�-涓湡') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鍗婂浣�-鍚庨亾') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-FPD') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-3D 娴嬮噺浠�') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-娴嬭瘯浠櫒') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鎷夋浖鍏夎氨浠�') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-琛�娑�') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-灏挎恫/绮究') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-缁嗚優瀛�') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-閬椾紶瀛�') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鐥呯悊') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鐢熸畺') {
+            //             newAcc.IndustryC__c = 'Medical Device/Equipment';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-楂樼鏄惧井闀�') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-缁嗚優瑙傚療') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鐢靛瓙鏄惧井闀�') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-楂樺唴娑�') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-娴佸紡缁嗚優浠�') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-ODM') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-绮惧噯鍖荤枟') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         } else if (newAcc.Sub_Use__c == 'Compo-鍏朵粬') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '(Manufacturing)OEM';
+            //         }
+            //     } else if (newAcc.recordTypeId == '01228000000TdFG') {
+            //         if (newAcc.Sub_Use__c == null || newAcc.Sub_Use__c == '') {
+            //             newAcc.IndustryC__c = null;
+            //             newAcc.MarketVerticals__c = null;
+            //             newAcc.Use__c = null;
+            //         } else if (newAcc.Sub_Use__c == 'Automotive') {
+            //             newAcc.IndustryC__c = 'Automotive';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Automotive Body/Engine';
+            //         } else if (newAcc.Sub_Use__c == 'Civil Aviation') {
+            //             newAcc.IndustryC__c = 'Aerospace';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = '(Maintenance)Aviation Airframe/Engine';
+            //         } else if (newAcc.Sub_Use__c == 'Security/Defense') {
+            //             newAcc.IndustryC__c = 'Government/Security/Defense';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         } else if (newAcc.Sub_Use__c == 'Oil,Gas&Chemical') {
+            //             newAcc.IndustryC__c = 'Chemical/Petrochemical/Plastics';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Weld Inspection';
+            //         } else if (newAcc.Sub_Use__c == 'Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Heat Exchangers';
+            //         } else if (newAcc.Sub_Use__c == 'General Manufacturing') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Machined Parts';
+            //         } else if (newAcc.Sub_Use__c == 'Inspection/Service/Rental') {
+            //             newAcc.IndustryC__c = 'Inspection/Lab/Rental Sevice Provider';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Process Piping';
+            //         } else if (newAcc.Sub_Use__c == 'Others') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         } else if (newAcc.Sub_Use__c == 'Thermal Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Process piping';
+            //         } else if (newAcc.Sub_Use__c == 'Nuclear Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Process piping';
+            //         } else if (newAcc.Sub_Use__c == 'Wind Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Weld Inspection';
+            //         } else if (newAcc.Sub_Use__c == 'Power(other)') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Corrosion';
+            //         }
+            //     } else if (newAcc.recordTypeId == '01228000000TdFB') {
+            //         if (newAcc.Sub_Use__c == null || newAcc.Sub_Use__c == '') {
+            //             newAcc.IndustryC__c = null;
+            //             newAcc.MarketVerticals__c = null;
+            //             newAcc.Use__c = null;
+            //         } else if (newAcc.Sub_Use__c == 'Automotive') {
+            //             newAcc.IndustryC__c = 'Automotive';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Automotive Body/Engine';
+            //         } else if (newAcc.Sub_Use__c == 'Civil Aviation') {
+            //             newAcc.IndustryC__c = 'Aerospace';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = '(Maintenance)Aviation Airframe/Engine';
+            //         } else if (newAcc.Sub_Use__c == 'Security/Defense') {
+            //             newAcc.IndustryC__c = 'Government/Security/Defense';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         } else if (newAcc.Sub_Use__c == 'Oil,Gas&Chemical') {
+            //             newAcc.IndustryC__c = 'Chemical/Petrochemical/Plastics';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Weld Inspection';
+            //         } else if (newAcc.Sub_Use__c == 'Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Heat Exchangers';
+            //         } else if (newAcc.Sub_Use__c == 'General Manufacturing') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Machined Parts';
+            //         } else if (newAcc.Sub_Use__c == 'Inspection/Service/Rental') {
+            //             newAcc.IndustryC__c = 'Inspection/Lab/Rental Sevice Provider';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Process Piping';
+            //         } else if (newAcc.Sub_Use__c == 'Others') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         } else if (newAcc.Sub_Use__c == 'Thermal Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Heat Exchangers';
+            //         } else if (newAcc.Sub_Use__c == 'Nuclear Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Process Piping';
+            //         } else if (newAcc.Sub_Use__c == 'Wind Power') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Gear Box';
+            //         } else if (newAcc.Sub_Use__c == 'Power(other)') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'Corrosion';
+            //         }
+            //     } else if (newAcc.recordTypeId == '01228000000TdFL') {
+            //         if (newAcc.Sub_Use__c == null || newAcc.Sub_Use__c == '') {
+            //             newAcc.IndustryC__c = null;
+            //             newAcc.MarketVerticals__c = null;
+            //             newAcc.Use__c = null;
+            //         } else if (newAcc.Sub_Use__c == '搴熸棫閲戝睘') {
+            //             newAcc.IndustryC__c = 'Recycling';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Alloy : Recycling';
+            //         } else if (newAcc.Sub_Use__c == '鐐奸挗鍘�') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = '  Tube/Rod/Bar/Sheet Metal';
+            //         } else if (newAcc.Sub_Use__c == 'PMI-鐭冲寲琛屼笟') {
+            //             newAcc.IndustryC__c = 'Chemical/Petrochemical/Plastics';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'PMI';
+            //         } else if (newAcc.Sub_Use__c == 'PMI-绠¢亾鍒堕��') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Pipelines';
+            //         } else if (newAcc.Sub_Use__c == 'PMI-閲戝睘鍒堕��') {
+            //             newAcc.IndustryC__c = 'Metal Manufacturing';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Machined Parts';
+            //         } else if (newAcc.Sub_Use__c == 'PMI-鐢靛姏') {
+            //             newAcc.IndustryC__c = 'Power Generation';
+            //             newAcc.MarketVerticals__c = 'Maintenance';
+            //             newAcc.Use__c = 'PMI';
+            //         } else if (newAcc.Sub_Use__c == 'RoHS') {
+            //             newAcc.IndustryC__c = 'Electronics';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == 'ELV') {
+            //             newAcc.IndustryC__c = 'Automotive';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Electronic Device';
+            //         } else if (newAcc.Sub_Use__c == '鐜╁叿&鐨潻') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Consumer Goods';
+            //         } else if (newAcc.Sub_Use__c == '璐甸噾灞�-鍒堕��') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Consumer Goods';
+            //         } else if (newAcc.Sub_Use__c == '璐甸噾灞�-鍥炴敹') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Alloy : Precious Metals Recycling';
+            //         } else if (newAcc.Sub_Use__c == '鍕樻帰-鏀垮簻') {
+            //             newAcc.IndustryC__c = 'Mining/Geology';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Geology : Geological Surveys';
+            //         } else if (newAcc.Sub_Use__c == '鍕樻帰-鐭夸笟鍏徃') {
+            //             newAcc.IndustryC__c = 'Mining/Geology';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Mining : Exploration';
+            //         } else if (newAcc.Sub_Use__c == 'Mining-鍐剁偧') {
+            //             newAcc.IndustryC__c = 'Mining/Geology';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Mining : Processing & Refining & Metallurgy';
+            //         } else if (newAcc.Sub_Use__c == 'Mining-寮�閲�') {
+            //             newAcc.IndustryC__c = 'Mining/Geology';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Mining : Production & Grade Control';
+            //         } else if (newAcc.Sub_Use__c == 'EPA') {
+            //             newAcc.IndustryC__c = 'Government/Security/Defense';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Regulatory : Enviro-Soil';
+            //         } else if (newAcc.Sub_Use__c == '鍦熷¥淇') {
+            //             newAcc.IndustryC__c = 'Recycling';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Regulatory : Enviro-Soil';
+            //         } else if (newAcc.Sub_Use__c == '鍦熷¥鐮旂┒') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Regulatory : Enviro-Soil';
+            //         } else if (newAcc.Sub_Use__c == '鑰冨彜&鏂囩墿') {
+            //             newAcc.IndustryC__c = 'Academic Research';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         } else if (newAcc.Sub_Use__c == '褰曚簳') {
+            //             newAcc.IndustryC__c = 'Oil & Gas';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Mining : Exploration';
+            //         } else if (newAcc.Sub_Use__c == '鍒惰嵂') {
+            //             newAcc.IndustryC__c = 'Pharmaceutical';
+            //             newAcc.MarketVerticals__c = 'Manufacturing';
+            //             newAcc.Use__c = 'Chemical/Plastics/Rubber';
+            //         } else if (newAcc.Sub_Use__c == '涓夊厓鍌寲鍓�') {
+            //             newAcc.IndustryC__c = 'Automotive';
+            //             newAcc.MarketVerticals__c = 'Natural Resources';
+            //             newAcc.Use__c = 'Alloy : Precious Metals Recycling';
+            //         } else if (newAcc.Sub_Use__c == 'Others') {
+            //             newAcc.IndustryC__c = 'Other';
+            //             newAcc.MarketVerticals__c = 'Other';
+            //             newAcc.Use__c = '(Other) Other';
+            //         }//Add 涓夊厓鍌寲鍓�  by 绗︽檽鏋� 2016骞�6鏈�6鏃�
+            //     }
+            //    }
+            //}   
+
+    public static void updateForDealer(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+        //鐜嬮箯浼� 鏈嶅姟閮ㄤ慨鏀硅仈绯讳汉閲嶆柊瀹℃壒 鍒ゆ柇褰撳墠淇敼鐨勭櫥闄嗕汉鏄惁鏄瓩瀛︽磱  鍚存檽涓�
+        String now_userId = UserInfo.getUserId();
+        Map<Id, Id> manager = new Map<Id, Id>();
+        for (Account newAcc : newList) {
+            Account oldAcc = oldMap.get(newAcc.Id);
+            /*if (newAcc.DealerSelectOwner__c != null ) {
+                manager.put(newAcc.DealerSelectOwner__c , newAcc.Id);
+            }*/
+            if (newAcc.WebsiteD__c != oldAcc.WebsiteD__c ||
+                    newAcc.FaxD__c != oldAcc.FaxD__c ||
+                    //newAcc.CreatedByD__c != oldAcc.CreatedBy ||
+                    newAcc.PhoneD__c != oldAcc.PhoneD__c ||
+                    newAcc.Address1D__c != oldAcc.Address1D__c ||
+                    newAcc.AssetANI4D__c != oldAcc.AssetANI4D__c ||
+                    newAcc.AssetIE7D__c != oldAcc.AssetIE7D__c ||
+                    newAcc.AssetNDT7D__c != oldAcc.AssetNDT7D__c ||
+                    //newAcc.DealerD__c != oldAcc.DealerD__c ||
+                    //newAcc.DepartmentNameD__c != oldAcc.DepartmentNameD__c ||
+                    //newAcc.DivisionNameD__c != oldAcc.DivissionNameD__c ||
+                    newAcc.AssetRVI5D__c != oldAcc.AssetRVI5D__c ||
+                    newAcc.EnglishNameD__c != oldAcc.EnglishNameD__c ||
+                    //newAcc.ExportRegulatedCustomerD__c != oldAcc.ExportRegulatedCustomerD__c ||
+                    //newAcc.FacilityNameD__c != oldAcc.FacilityNameD__c ||
+                    newAcc.AssetRVI2D__c != oldAcc.AssetRVI2D__c ||
+                    newAcc.AssetNDT4D__c != oldAcc.AssetNDT4D__c ||
+                    newAcc.IndustryCD__c != oldAcc.IndustryCD__c ||
+                    //gwy BS
+                    newAcc.IndustryBD__c != oldAcc.IndustryBD__c ||
+                    newAcc.AssetRVI4D__c != oldAcc.AssetRVI4D__c ||
+                    newAcc.AssetRVI3D__c != oldAcc.AssetRVI3D__c ||
+                    //newAcc.KeyAccountD__c != oldAcc.KeyAccountD__c ||
+                    newAcc.AssetIE5D__c != oldAcc.AssetIE5D__c ||
+                    newAcc.AssetBS3D__c != oldAcc.AssetBS3D__c ||
+                    newAcc.AssetIE3D__c != oldAcc.AssetIE3D__c ||
+                    newAcc.AssetANI7D__c != oldAcc.AssetANI7D__c ||
+                    newAcc.AssetNDT6D__c != oldAcc.AssetNDT6D__c ||
+                    newAcc.MarketVerticalsD__c != oldAcc.MarketVerticalsD__c ||
+                    newAcc.AssetIE6D__c != oldAcc.AssetIE6D__c ||
+                    newAcc.AssetIE2D__c != oldAcc.AssetIE2D__c ||
+                    newAcc.AssetBS2D__c != oldAcc.AssetBS2D__c ||
+                    newAcc.AssetANI3D__c != oldAcc.AssetANI3D__c ||
+                    newAcc.AssetIE1D__c != oldAcc.AssetIE1D__c ||
+                    newAcc.AssetBS1D__c != oldAcc.AssetBS1D__c ||
+                    newAcc.AssetRVI1D__c != oldAcc.AssetRVI1D__c ||
+                    newAcc.AssetNDT1D__c != oldAcc.AssetNDT1D__c ||
+                    newAcc.AssetANI1D__c != oldAcc.AssetANI1D__c ||
+                    newAcc.AssetNDT8D__c != oldAcc.AssetNDT8D__c ||
+                    newAcc.AssetANI8D__c != oldAcc.AssetANI8D__c ||
+                    newAcc.AssetBS5D__c != oldAcc.AssetBS5D__c ||
+                    newAcc.AssetIE8D__c != oldAcc.AssetIE8D__c ||
+                    newAcc.AssetRVI8D__c != oldAcc.AssetRVI8D__c ||
+                    newAcc.AssetANI5D__c != oldAcc.AssetANI5D__c ||
+                    //newAcc.ProvinceD__c != oldAcc.ProvinceD__c ||
+                    newAcc.AssetRVI6D__c != oldAcc.AssetRVI6D__c ||
+                    newAcc.AssetANI2D__c != oldAcc.AssetANI2D__c ||
+                    newAcc.AssetNDT3D__c != oldAcc.AssetNDT3D__c ||
+                    newAcc.AssetNDT2D__c != oldAcc.AssetNDT2D__c ||
+                    newAcc.AssetANI6D__c != oldAcc.AssetANI6D__c ||
+                    newAcc.Sub_UseD__c != oldAcc.Sub_UseD__c ||
+                    newAcc.Sub_UseA__c != oldAcc.Sub_UseA__c ||
+                    newAcc.UseD__c != oldAcc.UseD__c ||
+                    newAcc.AssetRVI7D__c != oldAcc.AssetRVI7D__c ||
+                    newAcc.AssetBS4D__c != oldAcc.AssetBS4D__c ||
+                    newAcc.AssetIE4D__c != oldAcc.AssetIE4D__c ||
+                    newAcc.AssetNDT5D__c != oldAcc.AssetNDT5D__c ||
+                    newAcc.AccountStatusD__c != oldAcc.AccountStatusD__c ||
+                    newAcc.CancelReasonD__c != oldAcc.CancelReasonD__c ||
+                    newAcc.CityD__c != oldAcc.CityD__c ||
+                    newAcc.PostCodeD__c != oldAcc.PostCodeD__c ||
+                    newAcc.DealerSelectOwner__c != oldAcc.DealerSelectOwner__c ||
+                    newAcc.FacilityNameD__c != oldAcc.FacilityNameD__c ||
+                    newAcc.DivisionName_D__c != oldAcc.DivisionName_D__c ||
+                    newAcc.DepartmentNameD__c != oldAcc.DepartmentNameD__c) {
+                // String profileId = UserInfo.getProfileId().subString(0, 15);
+                //鏂扮殑鑾峰彇浜哄憳绠�妗D
+                String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+                //System.debug('profileId:'+profileId+'---------'+'new_profileId:'+new_profileId);
+                //鐜嬮箯浼� 娣诲姞鍒ゆ柇  || now_userId =='00528000000YWC6' || now_userId =='00528000000YWE7'
+                //00528000000YWC6 瀛� 瀛︽磱
+                //00528000000YWE7 鍚� 鏅撲笢
+                //鐜嬮箯浼� 娣诲姞&&((oldCon.ProductSegmentIE__c == true || oldCon.ProductSegmentRVI__c == true) && oldCon.isServiceCreate__c == true)
+                //鏈嶅姟閮ㄤ慨鏀硅仈绯讳汉淇℃伅 LS銆丯DT銆丄NI鏃犻渶瀹℃壒璺宠繃瀹℃壒鐘舵�佸彉鑽夋
+                //鏂板鏉冮檺鏁寸悊2021-05-10
+                //gwy 2021-08-20 闄や簡甯傚満閮ㄧ殑浜猴紝閮藉彲浠ュ彉鑽夋
+                //List<String> markNot = new String [] {'00528000000YVIc','0050K00000B3aNb','0050K00000B3aN7','00528000001uK0Z','00528000000YVHy','00528000000YVID'};
+                if ((oldAcc.MarkisorNo__c == false
+                        //鏂板鏉冮檺鏁寸悊2021-05-10 
+                        || UserInfo.getUserType() == 'PowerPartner')
+                        && !((oldAcc.ProductSegment__c == 'BS' || oldAcc.ProductSegment__c == 'NDT' || oldAcc.ProductSegment__c == 'ANI') && oldAcc.serviceCreate__c == true)) {
+                    newAcc.stautesD__c = 'Draft';
+                }
+            }
+
+
+            if (newAcc.Website != oldAcc.Website) {
+                newAcc.WebsiteD__c = newAcc.Website;
+            }
+            if (newAcc.Fax != oldAcc.Fax) {
+                newAcc.FaxD__c = newAcc.Fax;
+            }
+            //newAcc.CreatedByD__c = newAcc.CreatedBy;
+            if (newAcc.Phone != oldAcc.Phone) {
+                newAcc.PhoneD__c = newAcc.Phone;
+            }
+            if (newAcc.Address1__c != oldAcc.Address1__c) {
+                newAcc.Address1D__c = newAcc.Address1__c;
+            }
+            if (newAcc.AssetANI4__c != oldAcc.AssetANI4__c) {
+                newAcc.AssetANI4D__c = newAcc.AssetANI4__c;
+            }
+            if (newAcc.AssetIE7__c != oldAcc.AssetIE7__c) {
+                newAcc.AssetIE7D__c = newAcc.AssetIE7__c;
+            }
+            if (newAcc.AssetNDT7__c != oldAcc.AssetNDT7__c) {
+                newAcc.AssetNDT7D__c = newAcc.AssetNDT7__c;
+            }
+            //newAcc.DealerD__c = newAcc.DealerName__c;
+            //newAcc.DepartmentNameD__c = newAcc.DepartmentName__c;
+            //newAcc.DivisionNameD__c = newAcc.DivissionName__c;
+            if (newAcc.AssetRVI5__c != oldAcc.AssetRVI5__c) {
+                newAcc.AssetRVI5D__c = newAcc.AssetRVI5__c;
+            }
+            if (newAcc.EnglishName__c != oldAcc.EnglishName__c) {
+                newAcc.EnglishNameD__c = newAcc.EnglishName__c;
+            }
+            //newAcc.ExportRegulatedCustomerD__c = newAcc.Export_Regulated_Customer__c;
+            //newAcc.FacilityNameD__c = newAcc.FacilityName__c;
+            if (newAcc.AssetRVI2__c != oldAcc.AssetRVI2__c) {
+                newAcc.AssetRVI2D__c = newAcc.AssetRVI2__c;
+            }
+            if (newAcc.AssetNDT4__c != oldAcc.AssetNDT4__c) {
+                newAcc.AssetNDT4D__c = newAcc.AssetNDT4__c;
+            }
+            //gwy BS
+            if (newAcc.IndustryB__c != oldAcc.IndustryB__c) {
+                newAcc.IndustryBD__c = newAcc.IndustryB__c;
+            }
+            if (newAcc.IndustryC__c != oldAcc.IndustryC__c) {
+                newAcc.IndustryCD__c = newAcc.IndustryC__c;
+            }
+            if (newAcc.AssetRVI4__c != oldAcc.AssetRVI4__c) {
+                newAcc.AssetRVI4D__c = newAcc.AssetRVI4__c;
+            }
+            if (newAcc.AssetRVI3__c != oldAcc.AssetRVI3__c) {
+                newAcc.AssetRVI3D__c = newAcc.AssetRVI3__c;
+            }
+            //newAcc.KeyAccountD__c = newAcc.KeyAccount__c;
+            if (newAcc.AssetIE5__c != oldAcc.AssetIE5__c) {
+                newAcc.AssetIE5D__c = newAcc.AssetIE5__c;
+            }
+            if (newAcc.AssetBS3__c != oldAcc.AssetBS3__c) {
+                newAcc.AssetBS3D__c = newAcc.AssetBS3__c;
+            }
+            if (newAcc.AssetIE3__c != oldAcc.AssetIE3__c) {
+                newAcc.AssetIE3D__c = newAcc.AssetIE3__c;
+            }
+            if (newAcc.AssetANI7__c != oldAcc.AssetANI7__c) {
+                newAcc.AssetANI7D__c = newAcc.AssetANI7__c;
+            }
+            if (newAcc.AssetNDT6__c != oldAcc.AssetNDT6__c) {
+                newAcc.AssetNDT6D__c = newAcc.AssetNDT6__c;
+            }
+            if (newAcc.MarketVerticals__c != oldAcc.MarketVerticals__c) {
+                newAcc.MarketVerticalsD__c = newAcc.MarketVerticals__c;
+            }
+            if (newAcc.AssetIE6__c != oldAcc.AssetIE6__c) {
+                newAcc.AssetIE6D__c = newAcc.AssetIE6__c;
+            }
+            if (newAcc.AssetIE2__c != oldAcc.AssetIE2__c) {
+                newAcc.AssetIE2D__c = newAcc.AssetIE2__c;
+            }
+            if (newAcc.AssetBS2__c != oldAcc.AssetBS2__c) {
+                newAcc.AssetBS2D__c = newAcc.AssetBS2__c;
+            }
+            if (newAcc.AssetANI3__c != oldAcc.AssetANI3__c) {
+                newAcc.AssetANI3D__c = newAcc.AssetANI3__c;
+            }
+            if (newAcc.AssetIE1__c != oldAcc.AssetIE1__c) {
+                newAcc.AssetIE1D__c = newAcc.AssetIE1__c;
+            }
+            if (newAcc.AssetBS1__c != oldAcc.AssetBS1__c) {
+                newAcc.AssetBS1D__c = newAcc.AssetBS1__c;
+            }
+            if (newAcc.AssetRVI1__c != oldAcc.AssetRVI1__c) {
+                newAcc.AssetRVI1D__c = newAcc.AssetRVI1__c;
+            }
+            if (newAcc.AssetNDT1__c != oldAcc.AssetNDT1__c) {
+                newAcc.AssetNDT1D__c = newAcc.AssetNDT1__c;
+            }
+            if (newAcc.AssetANI1__c != oldAcc.AssetANI1__c) {
+                newAcc.AssetANI1D__c = newAcc.AssetANI1__c;
+            }
+            if (newAcc.AssetNDT8__c != oldAcc.AssetNDT8__c) {
+                newAcc.AssetNDT8D__c = newAcc.AssetNDT8__c;
+            }
+            if (newAcc.AssetANI8__c != oldAcc.AssetANI8__c) {
+                newAcc.AssetANI8D__c = newAcc.AssetANI8__c;
+            }
+            if (newAcc.AssetBS5__c != oldAcc.AssetBS5__c) {
+                newAcc.AssetBS5D__c = newAcc.AssetBS5__c;
+            }
+            if (newAcc.AssetIE8__c != oldAcc.AssetIE8__c) {
+                newAcc.AssetIE8D__c = newAcc.AssetIE8__c;
+            }
+            if (newAcc.AssetRVI8__c != oldAcc.AssetRVI8__c) {
+                newAcc.AssetRVI8D__c = newAcc.AssetRVI8__c;
+            }
+            if (newAcc.AssetANI5__c != oldAcc.AssetANI5__c) {
+                newAcc.AssetANI5D__c = newAcc.AssetANI5__c;
+            }
+            //newAcc.ProvinceD__c = newAcc.Province__c;
+            if (newAcc.AssetRVI6__c != oldAcc.AssetRVI6__c) {
+                newAcc.AssetRVI6D__c = newAcc.AssetRVI6__c;
+            }
+            if (newAcc.AssetANI2__c != oldAcc.AssetANI2__c) {
+                newAcc.AssetANI2D__c = newAcc.AssetANI2__c;
+            }
+            if (newAcc.AssetNDT3__c != oldAcc.AssetNDT3__c) {
+                newAcc.AssetNDT3D__c = newAcc.AssetNDT3__c;
+            }
+            if (newAcc.AssetNDT2__c != oldAcc.AssetNDT2__c) {
+                newAcc.AssetNDT2D__c = newAcc.AssetNDT2__c;
+            }
+            if (newAcc.AssetANI6__c != oldAcc.AssetANI6__c) {
+                newAcc.AssetANI6D__c = newAcc.AssetANI6__c;
+            }
+            if (newAcc.Sub_Use1__c != oldAcc.Sub_Use1__c) {
+                newAcc.Sub_UseA__c = newAcc.Sub_Use1__c;
+            }
+            if (newAcc.Sub_Use__c != oldAcc.Sub_Use__c) {
+                newAcc.Sub_UseD__c = newAcc.Sub_Use__c;
+            }
+            if (newAcc.Use__c != oldAcc.Use__c) {
+                newAcc.UseD__c = newAcc.Use__c;
+            }
+            if (newAcc.AssetRVI7__c != oldAcc.AssetRVI7__c) {
+                newAcc.AssetRVI7D__c = newAcc.AssetRVI7__c;
+            }
+            if (newAcc.AssetBS4__c != oldAcc.AssetBS4__c) {
+                newAcc.AssetBS4D__c = newAcc.AssetBS4__c;
+            }
+            if (newAcc.AssetIE4__c != oldAcc.AssetIE4__c) {
+                newAcc.AssetIE4D__c = newAcc.AssetIE4__c;
+            }
+            if (newAcc.AssetNDT5__c != oldAcc.AssetNDT5__c) {
+                newAcc.AssetNDT5D__c = newAcc.AssetNDT5__c;
+            }
+
+            if (newAcc.AccountStatus__c != oldAcc.AccountStatus__c) {
+                newAcc.AccountStatusD__c = newAcc.AccountStatus__c;
+            }
+            if (newAcc.CancelReason__c != oldAcc.CancelReason__c) {
+                newAcc.CancelReasonD__c = newAcc.CancelReason__c;
+            }
+            if (newAcc.City__c != oldAcc.City__c) {
+                newAcc.CityD__c = newAcc.City__c;
+            }
+            if (newAcc.PostCode__c != oldAcc.PostCode__c) {
+                newAcc.PostCodeD__c = newAcc.PostCode__c;
+            }
+
+            if (newAcc.OwnerId != oldAcc.OwnerId) {
+                newAcc.DealerSelectOwner__c = newAcc.OwnerId;
+            }
+            //鐜嬮箯浼� 鏂板姞  澶у尯缁忕悊闅忓鎵逛汉瀹炴椂鍙樺寲 寮�濮�
+            if (newAcc.DealerSelectOwner__c != null ) {
+                manager.put(newAcc.DealerSelectOwner__c , newAcc.Id);
+            }
+            //鐜嬮箯浼� 鏂板姞  澶у尯缁忕悊闅忓鎵逛汉瀹炴椂鍙樺寲 缁撴潫
+            if (newAcc.FacilityName__c != oldAcc.FacilityName__c) {
+                newAcc.FacilityNameD__c = newAcc.FacilityName__c;
+            }
+            if (newAcc.DivisionName__c != oldAcc.DivisionName__c) {
+                newAcc.DivisionName_D__c = newAcc.DivisionName__c;
+            }
+            if (newAcc.DepartmentName__c != oldAcc.DepartmentName__c) {
+                newAcc.DepartmentNameD__c = newAcc.DepartmentName__c;
+            }
+            //gwy 2021-06-08 瀹㈡埛鍙栨秷閭紪蹇呭~椤�
+           /* if (newAcc.PostCodeD__c == null) {
+                newAcc.PostCodeD__c = '000000';
+            }*/
+            //鐜嬮箯浼熸柊鍔� 鏈嶅姟閮ㄥ垱寤哄鎴疯仈绯讳汉
+            if ((newAcc.DealerSelectOwner__c != oldAcc.DealerSelectOwner__c) && String.isNotBlank(newAcc.DealerSelectOwner__c) && newAcc.serviceCreate__c == true) {
+                newAcc.OwnerId = newAcc.DealerSelectOwner__c;
+            }
+            //鐜嬮箯浼熸柊鍔� 缁撴潫
+            //   鎷兼帴瀹㈡埛  by hanchao 20160809
+            // String new_profileId1 = UserInfo.getProfileId().subString(0,15);
+            //鏂扮殑鑾峰彇浜哄憳绠�妗D
+            String new_profileId1 = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+            //System.debug('new_profileId1:'+new_profileId1+'---------'+'new_profileId1:'+new_profileId1);
+
+            if ((new_profileId1.subString(0, 15) == System.label.Market_Department1 || new_profileId1.subString(0, 15) == System.label.Market_Department || new_profileId1.subString(0, 15) == System.label.Service_Owner 
+                    || UserInfo.getUserType() == 'PowerPartner') &&
+                    newAcc.IsNew__c == true && (newAcc.FacilityNameD__c != oldAcc.FacilityNameD__c ||
+                                                newAcc.DivisionName_D__c != oldAcc.DivisionName_D__c ||
+                                                newAcc.DepartmentNameD__c != oldAcc.DepartmentNameD__c )) {
+
+                String DivisionName1;
+                String DepartmentName1;
+                if (newAcc.DivisionName_D__c == '鏃�' || newAcc.DivisionName_D__c == null) {
+                    DivisionName1 = '';
+                } else {DivisionName1 = newAcc.DivisionName_D__c;}
+                if (newAcc.DepartmentNameD__c == '鏃�' || newAcc.DepartmentNameD__c == null) {
+                    DepartmentName1 = '';
+                } else {DepartmentName1 = newAcc.DepartmentNameD__c;}
+
+                newAcc.Name = newAcc.FacilityNameD__c + DivisionName1 + ' ' + DepartmentName1;
+
+
+            }
+        }
+
+        List<User> userList = new List<User>();
+        Set<Id> userid = new Set<Id>();
+        userid.addAll(manager.keySet());
+        system.debug(manager);
+        system.debug(userid);
+        userList = [select id,SalesManager__c,BS_AsistGenManger__c from User where id in :userid];
+        system.debug(userList);
+        if (userList.size() > 0) {
+            for (User use : userList) {
+                Id accid = manager.get(use.Id);
+                system.debug('Manager__c--accid:'+accid);
+                system.debug('use:'+use);
+                system.debug(newMap);
+                if (newMap.get(accid).ProductSegment__c == 'BS') {
+                    newMap.get(accid).Manager__c = use.BS_AsistGenManger__c;
+                }else {
+                    newMap.get(accid).Manager__c = use.SalesManager__c;
+                }
+                system.debug(newMap.get(accid).Manager__c);
+            }
+        }
+    }
+
+    public static void dealerAccountApproval(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+        for (Account newAcc : newList) {
+            Account oldAcc = oldMap.get(newAcc.Id);
+            // String new_profileId1 = UserInfo.getProfileId().subString(0,15);
+            //鏂扮殑鑾峰彇浜哄憳绠�妗D
+            String new_profileId1 = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+            //System.debug('new_profileId1:'+new_profileId1+'---------'+'new_profileId1:'+new_profileId1);
+
+            String record = newAcc.RecordTypeId;
+            system.debug(record);
+            //鐜嬮箯浼� 鏈嶅姟閮ㄥ垱寤哄鎴疯仈绯讳汉 淇敼  娣诲姞鍒ゆ柇鏉′欢 || newAcc.serviceCreate__c == true
+            if (new_profileId1.subString(0, 15) == System.label.Market_Department || new_profileId1.subString(0, 15) == System.label.Market_Department1 || newAcc.serviceCreate__c == true
+                ){
+                if (newAcc.stautesD__c == 'Pass') {
+                    newAcc.Website = newAcc.WebsiteD__c;
+                    newAcc.Fax = newAcc.FaxD__c;
+                    //newAcc.CreatedBy = newAcc.CreatedByD__c;
+                    newAcc.Phone = newAcc.PhoneD__c;
+                    newAcc.Address1__c = newAcc.Address1D__c;
+                    newAcc.AssetANI4__c = newAcc.AssetANI4D__c;
+                    newAcc.AssetIE7__c = newAcc.AssetIE7D__c;
+                    newAcc.AssetNDT7__c = newAcc.AssetNDT7D__c;
+                    //newAcc.Dealer__c = newAcc.DealerNameD__c;
+                    //newAcc.DepartmentName__c = newAcc.DepartmentNameD__c;
+                    //newAcc.DivisionName__c = newAcc.DivissionNameD__c;
+                    newAcc.AssetRVI5__c = newAcc.AssetRVI5D__c;
+                    newAcc.EnglishName__c = newAcc.EnglishNameD__c;
+                    //newAcc.ExportRegulatedCustomer__c = newAcc.Export_Regulated_CustomerD__c;
+                    //newAcc.FacilityName__c = newAcc.FacilityNameD__c;
+                    newAcc.AssetRVI2__c = newAcc.AssetRVI2D__c;
+                    newAcc.AssetNDT4__c = newAcc.AssetNDT4D__c;
+                    //gwy 2021-06-15 鏇存敼
+                    newAcc.IndustryC__c = newAcc.IndustryCD__c;
+                    newAcc.IndustryB__c = newAcc.IndustryBD__c;
+                    //newAcc.IndustryB__c = newAcc.IndustryBD__c;
+                    newAcc.AssetRVI4__c = newAcc.AssetRVI4D__c;
+                    newAcc.AssetRVI3__c = newAcc.AssetRVI3D__c;
+                    //newAcc.KeyAccount__c = newAcc.KeyAccountD__c;
+                    newAcc.AssetIE5__c = newAcc.AssetIE5D__c;
+                    newAcc.AssetBS3__c = newAcc.AssetBS3D__c;
+                    newAcc.AssetIE3__c = newAcc.AssetIE3D__c;
+                    newAcc.AssetANI7__c = newAcc.AssetANI7D__c;
+                    newAcc.AssetNDT6__c = newAcc.AssetNDT6D__c;
+                    newAcc.MarketVerticals__c = newAcc.MarketVerticalsD__c;
+                    newAcc.AssetIE6__c = newAcc.AssetIE6D__c;
+                    newAcc.AssetIE2__c = newAcc.AssetIE2D__c;
+                    newAcc.AssetBS2__c = newAcc.AssetBS2D__c;
+                    newAcc.AssetANI3__c = newAcc.AssetANI3D__c;
+                    newAcc.AssetIE1__c = newAcc.AssetIE1D__c;
+                    newAcc.AssetBS1__c = newAcc.AssetBS1D__c;
+                    newAcc.AssetRVI1__c = newAcc.AssetRVI1D__c;
+                    newAcc.AssetNDT1__c = newAcc.AssetNDT1D__c;
+                    newAcc.AssetANI1__c = newAcc.AssetANI1D__c;
+                    newAcc.AssetNDT8__c = newAcc.AssetNDT8D__c;
+                    newAcc.AssetANI8__c = newAcc.AssetANI8D__c;
+                    newAcc.AssetBS5__c = newAcc.AssetBS5D__c;
+                    newAcc.AssetIE8__c = newAcc.AssetIE8D__c;
+                    newAcc.AssetRVI8__c = newAcc.AssetRVI8D__c;
+                    newAcc.AssetANI5__c = newAcc.AssetANI5D__c;
+                    //newAcc.Province__c = newAcc.ProvinceD__c;
+                    newAcc.AssetRVI6__c = newAcc.AssetRVI6D__c;
+                    newAcc.AssetANI2__c = newAcc.AssetANI2D__c;
+                    newAcc.AssetNDT3__c = newAcc.AssetNDT3D__c;
+                    newAcc.AssetNDT2__c = newAcc.AssetNDT2D__c;
+                    newAcc.AssetANI6__c = newAcc.AssetANI6D__c;
+                    newAcc.Sub_Use1__c = newAcc.Sub_UseA__c;
+                    newAcc.Sub_Use__c = newAcc.Sub_UseD__c;
+                    newAcc.Use__c = newAcc.UseD__c;
+                    newAcc.AssetRVI7__c = newAcc.AssetRVI7D__c;
+                    newAcc.AssetBS4__c = newAcc.AssetBS4D__c;
+                    newAcc.AssetIE4__c = newAcc.AssetIE4D__c;
+                    newAcc.AssetNDT5__c = newAcc.AssetNDT5D__c;
+
+                    newAcc.AccountStatus__c = newAcc.AccountStatusD__c;
+                    newAcc.CancelReason__c = newAcc.CancelReasonD__c;
+                    newAcc.City__c = newAcc.CityD__c;
+                    newAcc.PostCode__c = newAcc.PostCodeD__c;
+                    newAcc.FacilityName__c = newAcc.FacilityNameD__c;
+                    newAcc.DivisionName__c = newAcc.DivisionName_D__c;
+                    newAcc.DepartmentName__c = newAcc.DepartmentNameD__c;
+
+                    String DivisionName;
+                    String DepartmentName;
+                    if (newAcc.DivisionName__c == '鏃�' || newAcc.DivisionName__c == null) {
+                        DivisionName = '';
+                    } else {DivisionName = newAcc.DivisionName__c;}
+                    if (newAcc.DepartmentName__c == '鏃�' || newAcc.DepartmentName__c == null) {
+                        DepartmentName = '';
+                    } else {DepartmentName = newAcc.DepartmentName__c;}
+
+                    newAcc.Name = newAcc.FacilityNameD__c + DivisionName + ' ' + DepartmentName;
+
+                    if (newAcc.IsNew__c = true) {
+                        newAcc.IsNew__c = false;
+                    }
+                    if (String.isNotBlank(newAcc.DealerSelectOwner__c)) {
+                        newAcc.OwnerId = newAcc.DealerSelectOwner__c;
+                    }
+                }
+            }
+            if (newAcc.stautesD__c != oldAcc.stautesD__c && record.substring(0, 15) != '012280000005gnE') {
+                // 鎵瑰噯鏃�
+                if (newAcc.stautesD__c == 'Pass') {
+                    newAcc.Website = newAcc.WebsiteD__c;
+                    newAcc.Fax = newAcc.FaxD__c;
+                    //newAcc.CreatedBy = newAcc.CreatedByD__c;
+                    newAcc.Phone = newAcc.PhoneD__c;
+                    newAcc.Address1__c = newAcc.Address1D__c;
+                    newAcc.AssetANI4__c = newAcc.AssetANI4D__c;
+                    newAcc.AssetIE7__c = newAcc.AssetIE7D__c;
+                    newAcc.AssetNDT7__c = newAcc.AssetNDT7D__c;
+                    //newAcc.Dealer__c = newAcc.DealerNameD__c;
+                    //newAcc.DepartmentName__c = newAcc.DepartmentNameD__c;
+                    //newAcc.DivisionName__c = newAcc.DivissionNameD__c;
+                    newAcc.AssetRVI5__c = newAcc.AssetRVI5D__c;
+                    newAcc.EnglishName__c = newAcc.EnglishNameD__c;
+                    //newAcc.ExportRegulatedCustomer__c = newAcc.Export_Regulated_CustomerD__c;
+                    //newAcc.FacilityName__c = newAcc.FacilityNameD__c;
+                    newAcc.AssetRVI2__c = newAcc.AssetRVI2D__c;
+                    newAcc.AssetNDT4__c = newAcc.AssetNDT4D__c;
+                    //gwy 2021-06-15 鏇存敼
+                    newAcc.IndustryB__c = newAcc.IndustryBD__c;
+                    newAcc.IndustryC__c = newAcc.IndustryCD__c;
+                    //newAcc.IndustryC__c = newAcc.IndustryBD__c;
+                    //newAcc.IndustryB__c = newAcc.IndustryBD__c;
+                    newAcc.AssetRVI4__c = newAcc.AssetRVI4D__c;
+                    newAcc.AssetRVI3__c = newAcc.AssetRVI3D__c;
+                    //newAcc.KeyAccount__c = newAcc.KeyAccountD__c;
+                    newAcc.AssetIE5__c = newAcc.AssetIE5D__c;
+                    newAcc.AssetBS3__c = newAcc.AssetBS3D__c;
+                    newAcc.AssetIE3__c = newAcc.AssetIE3D__c;
+                    newAcc.AssetANI7__c = newAcc.AssetANI7D__c;
+                    newAcc.AssetNDT6__c = newAcc.AssetNDT6D__c;
+                    newAcc.MarketVerticals__c = newAcc.MarketVerticalsD__c;
+                    newAcc.AssetIE6__c = newAcc.AssetIE6D__c;
+                    newAcc.AssetIE2__c = newAcc.AssetIE2D__c;
+                    newAcc.AssetBS2__c = newAcc.AssetBS2D__c;
+                    newAcc.AssetANI3__c = newAcc.AssetANI3D__c;
+                    newAcc.AssetIE1__c = newAcc.AssetIE1D__c;
+                    newAcc.AssetBS1__c = newAcc.AssetBS1D__c;
+                    newAcc.AssetRVI1__c = newAcc.AssetRVI1D__c;
+                    newAcc.AssetNDT1__c = newAcc.AssetNDT1D__c;
+                    newAcc.AssetANI1__c = newAcc.AssetANI1D__c;
+                    newAcc.AssetNDT8__c = newAcc.AssetNDT8D__c;
+                    newAcc.AssetANI8__c = newAcc.AssetANI8D__c;
+                    newAcc.AssetBS5__c = newAcc.AssetBS5D__c;
+                    newAcc.AssetIE8__c = newAcc.AssetIE8D__c;
+                    newAcc.AssetRVI8__c = newAcc.AssetRVI8D__c;
+                    newAcc.AssetANI5__c = newAcc.AssetANI5D__c;
+                    //newAcc.Province__c = newAcc.ProvinceD__c;
+                    newAcc.AssetRVI6__c = newAcc.AssetRVI6D__c;
+                    newAcc.AssetANI2__c = newAcc.AssetANI2D__c;
+                    newAcc.AssetNDT3__c = newAcc.AssetNDT3D__c;
+                    newAcc.AssetNDT2__c = newAcc.AssetNDT2D__c;
+                    newAcc.AssetANI6__c = newAcc.AssetANI6D__c;
+                    newAcc.Sub_Use1__c = newAcc.Sub_UseA__c;
+                    newAcc.Sub_Use__c = newAcc.Sub_UseD__c;
+                    newAcc.Use__c = newAcc.UseD__c;
+                    newAcc.AssetRVI7__c = newAcc.AssetRVI7D__c;
+                    newAcc.AssetBS4__c = newAcc.AssetBS4D__c;
+                    newAcc.AssetIE4__c = newAcc.AssetIE4D__c;
+                    newAcc.AssetNDT5__c = newAcc.AssetNDT5D__c;
+
+                    newAcc.AccountStatus__c = newAcc.AccountStatusD__c;
+                    newAcc.CancelReason__c = newAcc.CancelReasonD__c;
+                    newAcc.City__c = newAcc.CityD__c;
+                    newAcc.PostCode__c = newAcc.PostCodeD__c;
+                    newAcc.FacilityName__c = newAcc.FacilityNameD__c;
+                    newAcc.DivisionName__c = newAcc.DivisionName_D__c;
+                    newAcc.DepartmentName__c = newAcc.DepartmentNameD__c;
+
+                    String DivisionName;
+                    String DepartmentName;
+                    if (newAcc.DivisionName__c == '鏃�' || newAcc.DivisionName__c == null) {
+                        DivisionName = '';
+                    } else {DivisionName = newAcc.DivisionName__c;}
+                    if (newAcc.DepartmentName__c == '鏃�' || newAcc.DepartmentName__c == null) {
+                        DepartmentName = '';
+                    } else {DepartmentName = newAcc.DepartmentName__c;}
+
+                    newAcc.Name = newAcc.FacilityNameD__c + DivisionName + ' ' + DepartmentName;
+
+                    if (newAcc.IsNew__c = true) {
+                        newAcc.IsNew__c = false;
+                    }
+                    if (String.isNotBlank(newAcc.DealerSelectOwner__c)) {
+                        newAcc.OwnerId = newAcc.DealerSelectOwner__c;
+                    }
+                }
+                if (newAcc.stautesD__c == 'Reject' && newAcc.IsNew__c == false) {
+                    newAcc.WebsiteD__c = newAcc.Website;
+                    newAcc.FaxD__c = newAcc.Fax;
+                    //newAcc.CreatedByD__c = newAcc.CreatedBy;
+                    newAcc.PhoneD__c = newAcc.Phone;
+                    newAcc.Address1D__c = newAcc.Address1__c;
+                    newAcc.AssetANI4D__c = newAcc.AssetANI4__c;
+                    newAcc.AssetIE7D__c = newAcc.AssetIE7__c;
+                    newAcc.AssetNDT7D__c = newAcc.AssetNDT7__c;
+                    //newAcc.DealerD__c = newAcc.DealerName__c;
+                    //newAcc.DepartmentNameD__c = newAcc.DepartmentName__c;
+                    //newAcc.DivisionNameD__c = newAcc.DivissionName__c;
+                    newAcc.AssetRVI5D__c = newAcc.AssetRVI5__c;
+                    newAcc.EnglishNameD__c = newAcc.EnglishName__c;
+                    //newAcc.ExportRegulatedCustomerD__c = newAcc.Export_Regulated_Customer__c;
+                    //newAcc.FacilityNameD__c = newAcc.FacilityName__c;
+                    newAcc.AssetRVI2D__c = newAcc.AssetRVI2__c;
+                    newAcc.AssetNDT4D__c = newAcc.AssetNDT4__c;
+                    //gwy 2021-06-15 鏇存敼
+                    newAcc.IndustryBD__c = newAcc.IndustryB__c;
+                    newAcc.IndustryCD__c = newAcc.IndustryC__c;
+                    //newAcc.IndustryCD__c = newAcc.IndustryB__c;
+                    //newAcc.IndustryBD__c = newAcc.IndustryB__c;
+                    newAcc.AssetRVI4D__c = newAcc.AssetRVI4__c;
+                    newAcc.AssetRVI3D__c = newAcc.AssetRVI3__c;
+                    //newAcc.KeyAccountD__c = newAcc.KeyAccount__c;
+                    newAcc.AssetIE5D__c = newAcc.AssetIE5__c;
+                    newAcc.AssetBS3D__c = newAcc.AssetBS3__c;
+                    newAcc.AssetIE3D__c = newAcc.AssetIE3__c;
+                    newAcc.AssetANI7D__c = newAcc.AssetANI7__c;
+                    newAcc.AssetNDT6D__c = newAcc.AssetNDT6__c;
+                    newAcc.MarketVerticalsD__c = newAcc.MarketVerticals__c;
+                    newAcc.AssetIE6D__c = newAcc.AssetIE6__c;
+                    newAcc.AssetIE2D__c = newAcc.AssetIE2__c;
+                    newAcc.AssetBS2D__c = newAcc.AssetBS2__c;
+                    newAcc.AssetANI3D__c = newAcc.AssetANI3__c;
+                    newAcc.AssetIE1D__c = newAcc.AssetIE1__c;
+                    newAcc.AssetBS1D__c = newAcc.AssetBS1__c;
+                    newAcc.AssetRVI1D__c = newAcc.AssetRVI1__c;
+                    newAcc.AssetNDT1D__c = newAcc.AssetNDT1__c;
+                    newAcc.AssetANI1D__c = newAcc.AssetANI1__c;
+                    newAcc.AssetNDT8D__c = newAcc.AssetNDT8__c;
+                    newAcc.AssetANI8D__c = newAcc.AssetANI8__c;
+                    newAcc.AssetBS5D__c = newAcc.AssetBS5__c;
+                    newAcc.AssetIE8D__c = newAcc.AssetIE8__c;
+                    newAcc.AssetRVI8D__c = newAcc.AssetRVI8__c;
+                    newAcc.AssetANI5D__c = newAcc.AssetANI5__c;
+                    //newAcc.ProvinceD__c = newAcc.Province__c;
+                    newAcc.AssetRVI6D__c = newAcc.AssetRVI6__c;
+                    newAcc.AssetANI2D__c = newAcc.AssetANI2__c;
+                    newAcc.AssetNDT3D__c = newAcc.AssetNDT3__c;
+                    newAcc.AssetNDT2D__c = newAcc.AssetNDT2__c;
+                    newAcc.AssetANI6D__c = newAcc.AssetANI6__c;
+                    newAcc.Sub_UseA__c = newAcc.Sub_Use1__c;
+                    newAcc.Sub_UseD__c = newAcc.Sub_Use__c;
+                    newAcc.UseD__c = newAcc.Use__c;
+                    newAcc.AssetRVI7D__c = newAcc.AssetRVI7__c;
+                    newAcc.AssetBS4D__c = newAcc.AssetBS4__c;
+                    newAcc.AssetIE4D__c = newAcc.AssetIE4__c;
+                    newAcc.AssetNDT5D__c = newAcc.AssetNDT5__c;
+
+                    newAcc.AccountStatusD__c = newAcc.AccountStatus__c;
+                    newAcc.CancelReasonD__c = newAcc.CancelReason__c;
+                    newAcc.CityD__c = newAcc.City__c;
+                    newAcc.PostCodeD__c = newAcc.PostCode__c;
+
+                    newAcc.DealerSelectOwner__c = newAcc.OwnerId;
+                    newAcc.FacilityNameD__c = newAcc.FacilityName__c;
+                    newAcc.DivisionName_D__c = newAcc.DivisionName__c;
+                    newAcc.DepartmentNameD__c = newAcc.DepartmentName__c;
+                }
+            }
+            //gwy 2021-06-04 LS 鏂板蹇呭~椤筄EM瀹㈡埛鐨勬爣璇�
+            if(newAcc.UserType__c == 'OEM瀹㈡埛' && newAcc.ProductSegment__c == 'BS'){
+                newAcc.Whether_OEM__c = true;
+            }else{
+                newAcc.Whether_OEM__c = false;
+            }
+        }
+    }
+
+    public static void dealerAccountApproval2(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+        List<String> accIdList = new List<String>();
+
+        for (Account newAcc : newList) {
+            Account oldAcc = oldMap.get(newAcc.Id);
+            if (newAcc.stautesD__c != oldAcc.stautesD__c) {
+                // 鎵瑰噯鏃�
+                if (newAcc.stautesD__c == 'Pass') {
+                    accIdList.add(newAcc.Id);
+                }
+                // 甯傚満鎴樼暐閮ㄤ汉鍛樻柊寤烘彁浜ゆ椂 锛堥煩瓒咃級
+                if (newAcc.stautesD__c == 'Submit' && newAcc.IsStrCreated__c == true && newAcc.IsNew__c == true ) {
+                    accIdList.add(newAcc.Id);
+                }
+
+            }
+        }
+
+        if (accIdList.size() > 0) {
+            List<AccountShare> accsList = [select Id, accountId, UserOrGroupId, AccountAccessLevel, RowCause from AccountShare where accountId = :accIdList and RowCause = 'Team' and AccountAccessLevel = 'Read'];
+            for (AccountShare accs : accsList) {
+                accs.AccountAccessLevel = 'Edit';
+            }
+            if (accsList != null && accsList.size() > 0) {
+                update accsList;
+            }
+        }
+    }
+
+    public static void setDealerGroup(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+        List<String> groupIdList = new List<String>();
+        List<String> accIdList = new List<String>();
+        List<String> specialDealerList = new List<String>();
+
+        Map<String, String> userMap = new Map<String, String>();
+        List<User> userList = [select id, accountId from User where ContactId != null];
+        for (User u : userList) {
+            userMap.put(u.id, u.accountId);
+        }
+        for (Account newAcc : newList) {
+
+            accIdList.add(newAcc.Id);
+            String dealerId = userMap.get(newAcc.OwnerId);
+            String groupId = StaticParameter.dealerGroupMap.get(dealerId == null ? '' : dealerId.substring(0, 15));
+            Boolean flag = StaticParameter.specialDealerList.contains(dealerId == null ? '' : dealerId.substring(0, 15));
+            if (flag) {
+                specialDealerList.add(newAcc.Id);
+            }
+            if (groupId == null || groupId.length() == 0) {
+                continue;
+            }
+            groupIdList.add(groupId);
+            //accIdList.add(newAcc.Id);
+        }
+        List<GroupMember> gmList = [select id, groupId, userOrGroupId from GroupMember where groupId = :groupIdList];
+
+        List<AccountTeamMember> insertList = new list<AccountTeamMember>();
+        for (Account newAcc : newList) {
+            String dealerId = userMap.get(newAcc.OwnerId);
+            String groupId = StaticParameter.dealerGroupMap.get(dealerId == null ? '' : dealerId.substring(0, 15));
+            // 甯傚満鎴樼暐閮ㄦ柊寤轰繚瀛樻椂灏嗗垱寤鸿�呮彃鍏ュ鎴峰皬缁�
+            if (newAcc.IsStrCreated__c == true) {
+                AccountTeamMember atm2 = new AccountTeamMember();
+                atm2.accountId = newAcc.Id;
+                atm2.userId = newAcc.CreatedById;
+                atm2.teamMemberRole = 'Sales Manager';
+                insertList.add(atm2);
+            }
+            if (specialDealerList.contains(newAcc.Id)) {
+                AccountTeamMember atm = new AccountTeamMember();
+                atm.accountId = newAcc.Id;
+                atm.userId = newAcc.CreatedById;
+                atm.teamMemberRole = 'Sales Manager';
+                insertList.add(atm);
+                continue;
+            }
+            //
+            if (groupId == null || groupId.length() == 0) {
+                continue;
+            }
+
+            for (GroupMember gm : gmList) {
+                if (gm.groupId == groupId) {
+                    AccountTeamMember atm = new AccountTeamMember();
+                    atm.accountId = newAcc.Id;
+                    atm.userId = gm.userOrGroupId;
+                    atm.teamMemberRole = 'Sales Manager';
+                    insertList.add(atm);
+                }
+            }
+
+
+        }
+
+
+        if (insertList != null && insertList.size() > 0) {
+            insert insertList;
+        }
+
+        List<AccountShare> accsList = new List<AccountShare>();
+        accsList = [select Id, accountId, UserOrGroupId, AccountAccessLevel, RowCause from AccountShare where accountId = :accIdList and RowCause = 'Team'];
+        for (AccountShare accs : accsList) {
+            accs.AccountAccessLevel = 'Edit';
+        }
+        if (accsList != null && accsList.size() > 0) {
+            update accsList;
+        }
+    }
+    /**
+     * [updateCampaignRelationship description]甯傚満娲诲姩椤甸潰鍒涘缓瀹㈡埛
+     * @param  newList    [description]
+     * @param  newMap     [description]
+     * @param  oldList    [description]
+     * @param  oldMap     [description]
+     * @param  HandleType [description]1.鏂板銆�2.鍙樻洿銆�3.鍒犻櫎
+     * @return            [description]
+     */
+    public static void  updateCampaignRelationship(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap, string HandleType) {
+
+        List<Account> accountList = new List<Account>();
+        if ('1'.equals(HandleType)) {
+            accountList = newList;
+        } else {
+            accountList = oldList;
+        }
+        List<CampaignRelationship__c> insertCampaignRelationshipList = new List<CampaignRelationship__c>();
+        for (Account newAcc : accountList) {
+
+            if (newAcc.AccountCampaign__c !=  null) {
+                CampaignRelationship__c campaignRelationship = new CampaignRelationship__c();
+                campaignRelationship.RelationshipCampaign__c = newAcc.AccountCampaign__c;
+                campaignRelationship.RelationshipAccount__c = newAcc.Id;
+                if (newAcc.RecordTypeId == '01228000000TdF6' || newAcc.RecordTypeId == '01228000000PvwI') {
+                    campaignRelationship.RelationshipProductSegment__c = 'IE';
+                } else if (newAcc.RecordTypeId == '01228000000TdFB' || newAcc.RecordTypeId == '01228000000PvwK') {
+                    campaignRelationship.RelationshipProductSegment__c = 'RVI';
+                } else if (newAcc.RecordTypeId == '01228000000TdFG' || newAcc.RecordTypeId == '01228000000PvwJ') {
+                    campaignRelationship.RelationshipProductSegment__c = 'NDT';
+                } else if (newAcc.RecordTypeId == '01228000000TdFL' || newAcc.RecordTypeId == '01228000000PvwG') {
+                    campaignRelationship.RelationshipProductSegment__c = 'ANI';
+                }
+                insertCampaignRelationshipList.add(campaignRelationship);
+            }
+        }
+        system.debug('insertCampaignRelationshipList--->' + insertCampaignRelationshipList);
+        if (insertCampaignRelationshipList != null && insertCampaignRelationshipList.size() > 0) {
+            insert insertCampaignRelationshipList;
+        }
+    }
+
+    public static void CheckAccoutnNameChange(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+        List<String> idList = new List<String>();
+        List<Account> checkAccountList = new List<Account>();
+        //鏂扮殑鑾峰彇浜哄憳绠�妗D
+        // String profileId = UserInfo.getProfileId().subString(0, 15);
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        
+        //鏃х殑鑾峰彇绠�妗D  UserInfo.getProfileId().subString(0, 15)
+        for (Account acc : newList) {
+            Account oldAcc = oldMap.get(acc.Id);
+            //鏂板鏉冮檺鏁寸悊2021-05-10
+            if (UserInfo.getUserType() != 'PowerPartner' && 
+                new_profileId.subString(0, 15) != '00e28000000wAuN' && new_profileId.subString(0, 15) != '00e28000000eN67' && new_profileId.subString(0, 15) != '00e28000001sIDP'
+                ) {
+            //鏂板鏉冮檺鏁寸悊2021-05-10
+                System.debug(acc.Name);
+                System.debug(oldAcc.Name);
+                if ((acc.Name.trim() != oldAcc.Name.trim() || acc.FacilityName__c != oldAcc.FacilityName__c ||
+                    acc.DivisionName__c != oldAcc.DivisionName__c || acc.DepartmentName__c  != oldAcc.DepartmentName__c ||
+                    acc.FacilityNameD__c != oldAcc.FacilityNameD__c || acc.DivisionName_D__c != oldAcc.DivisionName_D__c ||
+                    acc.DepartmentNameD__c != oldAcc.DepartmentNameD__c ) && oldAcc.stautesD__c != 'Submit') {
+
+                    idList.add(acc.Id);
+                    checkAccountList.add(acc);
+                }
+            }
+        }
+
+        if(idList.size() > 0){
+            List<AccountTeamMember> accTeamList = new List<AccountTeamMember>();
+            Set<String> havePartnerSet = new Set<String>();
+            accTeamList = [SELECT id,user.userType,accountId FROM AccountTeamMember WHERE accountId IN : idList];
+            if(accTeamList.size() > 0){
+                for(AccountTeamMember atm : accTeamList){
+                    if(atm.user.userType == 'PowerPartner'){
+                        havePartnerSet.add(atm.accountId);
+                    }
+                }
+            }
+
+            for (Account acc : checkAccountList) {
+               if (havePartnerSet.contains(acc.Id)) {
+                   newMap.get(acc.Id).addError('涓嶈兘淇敼宸茬粡鍒嗛厤缁欎唬鐞嗙殑瀹㈡埛銆�');
+               }else{
+                    if(acc.MarketingStrategyCreated__c || (acc.serviceCreate__c && (acc.ProductSegment__c == 'NDT' ||acc.ProductSegment__c == 'ANI' ||acc.ProductSegment__c == 'BS' ))){
+
+                    }else{
+                        newMap.get(acc.Id).stautesD__c = 'Draft';
+                    }
+               }
+            }
+        }
+    }
+
+
+   
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    public static void asd() {
+        Integer i = 1;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/AccountTriggerHandler.cls-meta.xml b/scr/classes/AccountTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/AccountTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AccountTriggerHandlerTest.cls b/scr/classes/AccountTriggerHandlerTest.cls
new file mode 100644
index 0000000..fdc659d
--- /dev/null
+++ b/scr/classes/AccountTriggerHandlerTest.cls
@@ -0,0 +1,427 @@
+@isTest
+private class AccountTriggerHandlerTest {
+
+    static testMethod void tsetBusinesslicense() {
+        AccountTriggerHandler.asd();
+        List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+        
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        //Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        Account dealerParent = new Account();
+        dealerParent.Name = 'test dealer';
+        dealerParent.RecordTypeId = rectDealer[0].Id;
+        dealerParent.ProductSegment__c = 'BS';
+        dealerParent.PostCode__c='000000';
+        dealerParent.ManagementCode_Ext__c = 'P11111';
+        insert dealerParent;
+
+        Account dealer1 = new Account();
+        dealer1.Name = 'test dealer';
+        dealer1.RecordTypeId = rectDealer[0].Id;
+        dealer1.ProductSegment__c = 'BS';
+        dealer1.PostCode__c='000000';
+        dealer1.ManagementCode_Ext__c = 'C22222';
+        dealer1.ParentId = dealerParent.Id;
+        insert dealer1;
+
+        Account dealer2 = new Account();
+        dealer2.Name = 'test dealer';
+        dealer2.RecordTypeId = rectDealer[0].Id;
+        dealer2.ProductSegment__c = 'BS';
+        dealer2.PostCode__c='000000';
+        dealer2.ManagementCode_Ext__c = 'C33333';
+        dealer2.ParentId = dealerParent.Id;
+        insert dealer2;
+
+        dealerParent.Business_license__c = 'Test20191227';
+        update dealerParent;
+
+
+
+        
+    }
+    static testMethod void myUnitTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'IE';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        
+        User user = new User();
+        user.LastName = 'testAccount';
+        user.FirstName = 'test';
+        user.Alias = '2105';
+        user.Email = 'testAccount@test.com';
+        user.Username = 'testAccount@test222.com';
+        user.CommunityNickname = 'testAccount';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+        
+        Account acc = new Account();
+        acc.Name = '*';
+        acc.Website = 'Website';
+        acc.Fax = 'Fax';
+        acc.Phone = 'Phone';
+        acc.Address1__c = 'Address1__c';
+        acc.AssetANI4__c = 'AssetANI4__c';
+        acc.AssetIE7__c = 'AssetIE7__c';
+        acc.AssetNDT7__c = 'AssetNDT7__c';
+        acc.Dealer__c = dealer.id;
+        acc.DepartmentName__c = 'DepartmentName__c';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.AssetRVI5__c = 'AssetRVI5__c';
+        acc.EnglishName__c = 'EnglishName__c';
+        acc.ExportRegulatedCustomer__c = true;
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.AssetRVI2__c = 'AssetRVI2__c';
+        acc.AssetNDT4__c = 'AssetNDT4__c';
+        acc.IndustryC__c = 'Academic Research';
+        acc.AssetRVI4__c = 'AssetRVI4__c';
+        acc.AssetRVI3__c = 'AssetRVI3__c';
+        acc.KeyAccount__c = 'Large Account';
+        acc.AssetIE5__c = 'AssetIE5__c';
+        acc.AssetBS3__c = 'AssetBS3__c';
+        acc.AssetIE3__c = 'AssetIE3__c';
+        acc.AssetANI7__c = 'AssetANI7__c';
+        acc.AssetNDT6__c = 'AssetNDT6__c';
+        acc.MarketVerticals__c = 'LS Research';
+        acc.AssetIE6__c = 'AssetIE6__c';
+        acc.AssetIE2__c = 'AssetIE2__c';
+        acc.AssetBS2__c = 'AssetBS2__c';
+        acc.AssetANI3__c = 'AssetANI3__c';
+        acc.AssetIE1__c = 'AssetIE1__c';
+        acc.AssetBS1__c = 'AssetBS1__c';
+        acc.AssetRVI1__c = 'AssetRVI1__c';
+        acc.AssetNDT1__c = 'AssetNDT1__c';
+        acc.AssetANI1__c = 'AssetANI1__c';
+        acc.AssetNDT8__c = 'AssetNDT8__c';
+        acc.AssetANI8__c = 'AssetANI8__c';
+        acc.AssetBS5__c = 'AssetBS5__c';
+        acc.AssetIE8__c = 'AssetIE8__c';
+        acc.AssetRVI8__c = 'AssetRVI8__c';
+        acc.AssetANI5__c = 'AssetANI5__c';
+        acc.Province__c = '鍖椾含';
+        acc.AssetRVI6__c = 'AssetRVI6__c';
+        acc.AssetANI2__c = 'AssetANI2__c';
+        acc.AssetNDT3__c = 'AssetNDT3__c';
+        acc.AssetNDT2__c = 'AssetNDT2__c';
+        acc.AssetANI6__c = 'AssetANI6__c';
+        acc.Sub_Use__c = 'LED';
+        acc.Use__c = '(LS Research) Other';
+        acc.AssetRVI7__c = 'AssetRVI7__c';
+        acc.AssetBS4__c = 'AssetBS4__c';
+        acc.AssetIE4__c = 'AssetIE4__c';
+        acc.AssetNDT5__c = 'AssetNDT5__c';
+        acc.AccountStatus__c = 'Active';
+        acc.CancelReason__c = 'CancelReason__c';
+        acc.City__c = 'City__c';
+        acc.PostCode__c = '100111';
+        acc.serviceCreate__c = true;
+        acc.stautesD__c = 'Pass';
+        
+        insert acc;
+        
+        acc.Website = 'WebsiteD__c';
+        acc.Fax = 'FaxD__c';
+        acc.Phone = 'PhoneD__c';
+        acc.Address1__c = 'Address1D__c';
+        acc.AssetANI4__c = 'AssetANI4D__c';
+        acc.AssetIE7__c = 'AssetIE7D__c';
+        acc.AssetNDT7__c = 'AssetNDT7D__c';
+        acc.AssetRVI5__c = 'AssetRVI5D__c';
+        acc.EnglishName__c = 'EnglishNameD__c';
+        acc.AssetRVI2__c = 'AssetRVI2D__c';
+        acc.AssetNDT4__c = 'AssetNDT4D__c';
+        acc.IndustryC__c = 'Electronics';
+        acc.AssetRVI4__c = 'AssetRVI4D__c';
+        acc.AssetRVI3__c = 'AssetRVI3D__c';
+        acc.AssetIE5__c = 'AssetIE5D__c';
+        acc.AssetBS3__c = 'AssetBS3D__c';
+        acc.AssetIE3__c = 'AssetIE3D__c';
+        acc.AssetANI7__c = 'AssetANI7D__c';
+        acc.AssetNDT6__c = 'AssetNDT6D__c';
+        acc.MarketVerticals__c = 'Other';
+        acc.AssetIE6__c = 'AssetIE6D__c';
+        acc.AssetIE2__c = 'AssetIE2D__c';
+        acc.AssetBS2__c = 'AssetBS2D__c';
+        acc.AssetANI3__c = 'AssetANI3D__c';
+        acc.AssetIE1__c = 'AssetIE1D__c';
+        acc.AssetBS1__c = 'AssetBS1D__c';
+        acc.AssetRVI1__c = 'AssetRVI1D__c';
+        acc.AssetNDT1__c = 'AssetNDT1D__c';
+        acc.AssetANI1__c = 'AssetANI1D__c';
+        acc.AssetNDT8__c = 'AssetNDT8D__c';
+        acc.AssetANI8__c = 'AssetANI8D__c';
+        acc.AssetBS5__c = 'AssetBS5D__c';
+        acc.AssetIE8__c = 'AssetIE8D__c';
+        acc.AssetRVI8__c = 'AssetRVI8D__c';
+        acc.AssetANI5__c = 'AssetANI5D__c';
+        acc.AssetRVI6__c = 'AssetRVI6D__c';
+        acc.AssetANI2__c = 'AssetANI2D__c';
+        acc.AssetNDT3__c = 'AssetNDT3D__c';
+        acc.AssetNDT2__c = 'AssetNDT2D__c';
+        acc.AssetANI6__c = 'AssetANI6D__c';
+        acc.Sub_Use__c = 'Compo-FPD';
+        acc.Use__c = '(Other) Other';
+        acc.AssetRVI7__c = 'AssetRVI7D__c';
+        acc.AssetBS4__c = 'AssetBS4D__c';
+        acc.AssetIE4__c = 'AssetIE4D__c';
+        acc.AssetNDT5__c = 'AssetNDT5D__c';
+        acc.AccountStatus__c = 'Cancel';
+        acc.CancelReason__c = 'CancelReasonD__c';
+        acc.City__c = 'CityD__c';
+        acc.PostCode__c = '100222';
+        acc.OwnerId = user.Id;
+        
+        update acc;
+        
+        acc.WebsiteD__c = 'WebsiteD__c';
+        acc.FaxD__c = 'FaxD__c';
+        acc.PhoneD__c = 'PhoneD__c';
+        acc.Address1D__c = 'Address1D__c';
+        acc.AssetANI4D__c = 'AssetANI4D__c';
+        acc.AssetIE7D__c = 'AssetIE7D__c';
+        acc.AssetNDT7D__c = 'AssetNDT7D__c';
+        acc.AssetRVI5D__c = 'AssetRVI5D__c';
+        acc.EnglishNameD__c = 'EnglishNameD__c';
+        acc.AssetRVI2D__c = 'AssetRVI2D__c';
+        acc.AssetNDT4D__c = 'AssetNDT4D__c';
+        acc.IndustryCD__c = 'Mining/Geology';
+        acc.AssetRVI4D__c = 'AssetRVI4D__c';
+        acc.AssetRVI3D__c = 'AssetRVI3D__c';
+        acc.AssetIE5D__c = 'AssetIE5D__c';
+        acc.AssetBS3D__c = 'AssetBS3D__c';
+        acc.AssetIE3D__c = 'AssetIE3D__c';
+        acc.AssetANI7D__c = 'AssetANI7D__c';
+        acc.AssetNDT6D__c = 'AssetNDT6D__c';
+        acc.MarketVerticalsD__c = 'Other';
+        acc.AssetIE6D__c = 'AssetIE6D__c';
+        acc.AssetIE2D__c = 'AssetIE2D__c';
+        acc.AssetBS2D__c = 'AssetBS2D__c';
+        acc.AssetANI3D__c = 'AssetANI3D__c';
+        acc.AssetIE1D__c = 'AssetIE1D__c';
+        acc.AssetBS1D__c = 'AssetBS1D__c';
+        acc.AssetRVI1D__c = 'AssetRVI1D__c';
+        acc.AssetNDT1D__c = 'AssetNDT1D__c';
+        acc.AssetANI1D__c = 'AssetANI1D__c';
+        acc.AssetNDT8D__c = 'AssetNDT8D__c';
+        acc.AssetANI8D__c = 'AssetANI8D__c';
+        acc.AssetBS5D__c = 'AssetBS5D__c';
+        acc.AssetIE8D__c = 'AssetIE8D__c';
+        acc.AssetRVI8D__c = 'AssetRVI8D__c';
+        acc.AssetANI5D__c = 'AssetANI5D__c';
+        acc.AssetRVI6D__c = 'AssetRVI6D__c';
+        acc.AssetANI2D__c = 'AssetANI2D__c';
+        acc.AssetNDT3D__c = 'AssetNDT3D__c';
+        acc.AssetNDT2D__c = 'AssetNDT2D__c';
+        acc.AssetANI6D__c = 'AssetANI6D__c';
+        acc.Sub_UseD__c = '鐭虫补鍦拌川';
+        acc.UseD__c = 'Geology : Geological Surveys';
+        acc.AssetRVI7D__c = 'AssetRVI7D__c';
+        acc.AssetBS4D__c = 'AssetBS4D__c';
+        acc.AssetIE4D__c = 'AssetIE4D__c';
+        acc.AssetNDT5D__c = 'AssetNDT5D__c';
+        acc.AccountStatusD__c = 'Cancel';
+        acc.CancelReasonD__c = 'CancelReasonD__c';
+        acc.CityD__c = 'CityD__c';
+        acc.PostCodeD__c = '100222';
+        acc.DealerSelectOwner__c = UserInfo.getUserId();
+        
+        update acc;
+        
+        acc.stautesD__c = 'Completed';
+        update acc;
+        acc.stautesD__c = 'Submit';
+        update acc;
+
+        acc.stautesD__c = 'Pass';
+        update acc;
+        
+        acc.stautesD__c = 'Reject';
+        update acc;
+    }
+    
+    static testMethod void testSubUse1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        List<Account> acclist = new List<Account>();
+        String[] ieSubUse = new String[] {'LED','FPD','鍗婂浣�','鐢靛瓙閮ㄥ搧','鐢靛瓙绫籣鍏朵粬','閲戝睘','姹借溅','鐭虫补鍦拌川','浜旈噾妯″叿','閲嶅伐璁惧','鏉愭枡绫籣鍏朵粬'};
+        for (Integer i = 0; i < ieSubUse.size(); i++) {
+            Account acc1 = new Account();
+            acc1.Name = '*';
+            acc1.FacilityName__c = 'Account';
+            acc1.DivisionName__c = ieSubUse[i];
+            acc1.RecordTypeId = rectIE[0].Id;
+            acc1.ProductSegment__c = 'IE';
+            acc1.Sub_UseD__c = ieSubUse[i];
+            acc1.Sub_Use__c = ieSubUse[i];
+            acc1.PostCode__c = '000000';
+            acclist.add(acc1);
+        }
+        insert acclist;
+    }
+    
+    static testMethod void testSubUse2() {
+        List<RecordType> rectRVI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer RVI'];
+        
+        List<Account> acclist = new List<Account>();
+        String[] rviSubUse = new String[] {'Automotive','Civil Aviation','Security/Defense','Oil,Gas&Chemical','Power','General Manufacturing','Inspection/Service/Rental','Others','Thermal Power','Nuclear Power','Wind Power','Power(other)'};
+        for (Integer i = 0; i < rviSubUse.size(); i++) {
+            Account acc1 = new Account();
+            acc1.Name = '*';
+            acc1.FacilityName__c = 'Account';
+            acc1.DivisionName__c = rviSubUse[i];
+            acc1.RecordTypeId = rectRVI[0].Id;
+            acc1.ProductSegment__c = 'RVI';
+            acc1.Sub_UseD__c = rviSubUse[i];
+            acc1.Sub_Use__c = rviSubUse[i];
+            acc1.PostCode__c = '000001';
+            acclist.add(acc1);
+        }
+        insert acclist;
+    }
+    
+    static testMethod void testSubUse3() {
+        List<RecordType> rectANI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        
+        List<Account> acclist = new List<Account>();
+        String[] aniSubUse = new String[] {'搴熸棫閲戝睘','鐐奸挗鍘�','PMI-鐭冲寲琛屼笟','PMI-绠¢亾鍒堕��','PMI-閲戝睘鍒堕��','PMI-鐢靛姏','RoHS','ELV','鐜╁叿&鐨潻','璐甸噾灞�-鍒堕��','璐甸噾灞�-鍥炴敹','鍕樻帰-鏀垮簻','鍕樻帰-鐭夸笟鍏徃','Mining-鍐剁偧','Mining-寮�閲�','EPA','鍦熷¥淇','鍦熷¥鐮旂┒','鑰冨彜&鏂囩墿','褰曚簳','鍒惰嵂','涓夊厓鍌寲鍓�'};
+        for (Integer i = 0; i < aniSubUse.size(); i++) {
+            Account acc1 = new Account();
+            acc1.Name = '*';
+            acc1.FacilityName__c = 'Account';
+            acc1.DivisionName__c = aniSubUse[i];
+            acc1.RecordTypeId = rectANI[0].Id;
+            acc1.ProductSegment__c = 'ANI';
+            acc1.Sub_UseD__c = aniSubUse[i];
+            acc1.Sub_Use__c = aniSubUse[i];
+            acc1.PostCode__c = '000002';
+            acclist.add(acc1);
+        }
+        insert acclist;
+    }
+    static testMethod void testSubUse5() {
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        
+        List<Account> acclist = new List<Account>();
+        String[] bSIndu = new String[] {'Biotech',' Food/Feed/Agriculture','Clinic/Hospital','Commercial Diagnostic Laboratories','Education','Government/Security/Defense'};
+        for (Integer i = 0; i < bSIndu.size(); i++) {
+            Account acc1 = new Account();
+            acc1.Name = '*';
+            acc1.FacilityName__c = 'Account';
+            acc1.DivisionName__c = bSIndu[i];
+            acc1.RecordTypeId = rectBS[0].Id;
+            acc1.ProductSegment__c = 'BS';
+            acc1.IndustryBD__c = bSIndu[i];
+            acc1.IndustryB__c = bSIndu[i];
+            acc1.PostCode__c = '000002';
+            acclist.add(acc1);
+        }
+        insert acclist;
+    }
+    static testMethod void testSubUse4() {
+        List<RecordType> rectNDT = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+        
+        List<Account> acclist = new List<Account>();
+        String[] rviSubUse = new String[] {'Automotive','Civil Aviation','Security/Defense','Oil,Gas&Chemical','Power','General Manufacturing','Inspection/Service/Rental','Others','Thermal Power','Nuclear Power','Wind Power','Power(other)'};
+        for (Integer i = 0; i < rviSubUse.size(); i++) {
+            Account acc1 = new Account();
+            acc1.Name = '*';
+            acc1.FacilityName__c = 'Account';
+            acc1.DivisionName__c = rviSubUse[i];
+            acc1.RecordTypeId = rectNDT[0].Id;
+            acc1.ProductSegment__c = 'NDT';
+            acc1.Sub_UseD__c = rviSubUse[i];
+            acc1.Sub_Use__c = rviSubUse[i];
+            acc1.PostCode__c = '000003';
+            acclist.add(acc1);
+        }
+        insert acclist;
+    }
+    static testMethod void tsetTriggerAccount() {
+        AccountTriggerHandler.asd();
+        List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+        
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        //Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        Account dealerParent = new Account();
+        dealerParent.Name = 'test dealer';
+        dealerParent.RecordTypeId = rectDealer[0].Id;
+        dealerParent.ProductSegment__c = 'IE';
+        dealerParent.PostCode__c='000000';
+        dealerParent.ManagementCode_Ext__c = 'P11111';
+        dealerParent.Sub_UseA__c = '鐢靛瓙閮ㄥ搧';
+        dealerParent.compo_Acc__c = '闈濩OMPO瀹㈡埛';
+        insert dealerParent;
+
+
+        Account dealer1 = new Account();
+        dealer1.Name = 'test dealer';
+        dealer1.RecordTypeId = rectDealer[0].Id;
+        dealer1.ProductSegment__c = 'IE';
+        dealer1.PostCode__c='000000';
+        dealer1.ManagementCode_Ext__c = 'C22222';
+        dealer1.ParentId = dealerParent.Id;
+        dealer1.compo_Acc__c = '闈濩OMPO瀹㈡埛';
+        insert dealer1;
+
+        Account dealer2 = new Account();
+        dealer2.Name = 'test dealer';
+        dealer2.RecordTypeId = rectDealer[0].Id;
+        dealer2.ProductSegment__c = 'IE';
+        dealer2.PostCode__c='000000';
+        dealer2.ManagementCode_Ext__c = 'C33333';
+        dealer2.ParentId = dealerParent.Id;
+        dealer2.compo_Acc__c = '闈濩OMPO瀹㈡埛';
+        insert dealer2;
+
+        dealerParent.Sub_UseA__c = '鐢靛瓙閮ㄥ搧';
+        dealerParent.Sub_Use1__c = '鐢靛瓙閮ㄥ搧';
+        dealerParent.Business_license__c = 'Test20191227';
+        update dealerParent;   
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/AccountTriggerHandlerTest.cls-meta.xml b/scr/classes/AccountTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/AccountTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AccountWebService.cls b/scr/classes/AccountWebService.cls
new file mode 100644
index 0000000..54b5770
--- /dev/null
+++ b/scr/classes/AccountWebService.cls
@@ -0,0 +1,265 @@
+global class AccountWebService {
+	WebService static String AccountCancel(String accountId) {
+		Account account = new Account();
+		List<Account> accountList = [select Id, OwnerId, AccountStatus__c, CancelReason__c from Account where Id =:accountId];
+		if (accountList.size() == 0) {
+			return '鏃犳晥鐨勫鎴�';
+		} else {
+			account = accountList[0];
+		}
+		if (account.AccountStatus__c == 'Cancel') {
+			return '瀹㈡埛宸茬粡鍙栨秷';
+		}
+		if (account.CancelReason__c == null || account.CancelReason__c.length() == 0) {
+			return '蹇呴』杈撳叆鍙栨秷鐞嗙敱';
+		}
+		account.AccountStatus__c = 'Cancel';
+		account.OwnerId = System.Label.BatchUserId;
+		update account;
+		
+		return '1';
+	}
+
+	WebService static String UpdateShare(String accountId, String ownerOld, String ownerNew) {
+		try {
+			Account acc = new Account(
+				Id = accountId,
+				OwnerId = ownerNew
+			);
+			update acc;
+
+			List<AccountShare> asList = [select Id, AccountId, UserOrGroupId, AccountAccessLevel, RowCause from AccountShare where AccountId = :accountId and UserOrGroupId = :ownerOld and RowCause = 'Team' and AccountAccessLevel = 'Read'];
+			for (AccountShare ash : asList) {
+				ash.AccountAccessLevel = 'Edit';
+			}
+			if (asList.size() > 0) {
+				update asList;
+			}
+		} catch (Exception ex) {
+			return ex.getMessage();
+		}
+		
+		return '1';
+	}
+	// 鎶�鏈湇鍔¢儴鎷呭綋銆佹妧鏈湇鍔¢儴(閮ㄩ暱銆佸壇閮ㄩ暱)銆両E 鏍锋満绠$悊鑰� 绠�妗� 鍒涘缓瀹㈡埛璺宠繃蹇呭~瀛楁楠岃瘉锛屾敼涓烘彁浜ゅ鎵规椂楠岃瘉
+	// CHAN-BU98HT XHL 20201014
+	WebService static String RequiredField(String accountId) {
+		String result = '1';
+
+		List<String> errorMessageList = new List<String>();
+		// 鐜嬮箯浼熶慨鏀瑰墠 SQL 澶囦唤
+		//List<Account> accList = [select Id,Name,FacilityNameD__c,DivisionName_D__c,DealerSelectOwner__c,Province__c,CityD__c,Address1D__c,Sub_UseD__c,AccountStatusD__c,PostCodeD__c,DepartmentNameD__c,IndustryCD__c,MarketVerticalsD__c,UseD__c,EnglishNameD__c,TargetCustomer__c,CustomerSource__c,UserType__c,RecordTypeId from Account where  Id = :accountId ];
+		List<Account> accList = [select Id,Name,FacilityNameD__c,DivisionName_D__c,DealerSelectOwner__c,Province__c,CityD__c,Address1D__c,Sub_UseD__c,AccountStatusD__c,PostCodeD__c,DepartmentNameD__c,IndustryCD__c,MarketVerticalsD__c,UseD__c,EnglishNameD__c,TargetCustomer__c,CustomerSource__c,UserType__c,RecordTypeId,DealerAccount__c,AssetRVI1D__c,serviceCreate__c from Account where  Id = :accountId ];
+		if (accList.size() > 0) {
+
+			// 鍏卞悓閮ㄥ垎8涓瓧娈�
+			Account account = accList[0];
+			// 瀹㈡埛/浠g悊鍟嗗悕绉�.
+			if (String.isBlank(account.FacilityNameD__c)) {
+				String errorMessage = '瀹㈡埛/浠g悊鍟嗗悕绉�.';
+				errorMessageList.add(errorMessage);
+			}
+			// 閮ㄩ棬鍚嶇О.
+			if (String.isBlank(account.DivisionName_D__c)) {
+				String errorMessage = '閮ㄩ棬鍚嶇О.';
+				errorMessageList.add(errorMessage);
+			}
+			// 瀹℃壒浜�
+			if (String.isBlank(account.DealerSelectOwner__c)) {
+				String errorMessage = '瀹℃壒浜�';
+				errorMessageList.add(errorMessage);
+			}
+			// 鐪�
+			if (String.isBlank(account.Province__c)) {
+				String errorMessage = '鐪�';
+				errorMessageList.add(errorMessage);
+			}
+			// 鍩庡競.
+			if (String.isBlank(account.CityD__c)) {
+				String errorMessage = '鍩庡競.';
+				errorMessageList.add(errorMessage);
+			}
+			// 鍦板潃1.	
+			if (String.isBlank(account.Address1D__c)) {
+				String errorMessage = '鍦板潃1.';
+				errorMessageList.add(errorMessage);
+			}
+			// 璐︽埛鐘舵��.
+			/*if (String.isBlank(account.AccountStatusD__c)) {
+				String errorMessage = '璐︽埛鐘舵��. 蹇呭~ 璇风‘璁�;';
+				errorMessageList.add(errorMessage);
+			}*/
+			// 閭紪.
+			/*if (String.isBlank(account.PostCodeD__c)) {
+				String errorMessage = '閭紪. 蹇呭~ 璇风‘璁�;';
+				errorMessageList.add(errorMessage);
+			}*/
+			// Sub Use.
+			if (String.isBlank(account.Sub_UseD__c)) {
+				String errorMessage = 'Sub Use.';
+				errorMessageList.add(errorMessage);
+			}
+			// ANI NDT RVI IE
+			/*if ('01228000000TdFL'.equals(account.RecordTypeId) || '01228000000TdFG'.equals(account.RecordTypeId) || 
+				'01228000000TdFB'.equals(account.RecordTypeId) || '01228000000TdF6'.equals(account.RecordTypeId)) {
+				// Sub Use.
+				if (String.isBlank(account.Sub_UseD__c)) {
+					String errorMessage = 'Sub Use. 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}
+			}*/
+			// RVI IE 鐜嬮箯浼熸柊鍔�
+			if(('01228000000TdFB'.equals(account.RecordTypeId) || '01228000000TdF6'.equals(account.RecordTypeId)) && account.serviceCreate__c == true){
+				//浠g悊鍟�
+				if(!String.isNotBlank(String.valueOf(account.DealerAccount__c))){
+					String errorMessage = '浠g悊鍟�';
+					errorMessageList.add(errorMessage);
+				}
+			}
+			// RVI 鍒ゆ柇RVI浜у搧淇℃伅
+			if('01228000000TdFB'.equals(account.RecordTypeId)){
+				//
+				if(!String.isNotBlank(account.AssetRVI1D__c)){
+					String errorMessage = 'RVI浜у搧淇℃伅';
+					errorMessageList.add(errorMessage);
+				}
+			}
+			// IE
+			if ('01228000000TdF6'.equals(account.RecordTypeId)) {
+				// 鑻辨枃鍚嶇О.
+				/*if (String.isBlank(account.EnglishNameD__c)) {
+					String errorMessage = '鑻辨枃鍚嶇О. 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}*/
+				// 瀹㈡埛绫诲瀷
+				/*if (String.isBlank(account.TargetCustomer__c)) {
+					String errorMessage = '瀹㈡埛绫诲瀷 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}*/
+				// 瀹㈡埛鏉ユ簮.
+				if (String.isBlank(account.CustomerSource__c)) {
+					String errorMessage = '瀹㈡埛鏉ユ簮.';
+					errorMessageList.add(errorMessage);
+				}
+				// 鐢ㄦ埛灞炴��
+				if (String.isBlank(account.UserType__c)) {
+					String errorMessage = '鐢ㄦ埛灞炴��';
+					errorMessageList.add(errorMessage);
+				}
+			}
+			// BS
+			/*if ('01228000000TdF1'.equals(account.RecordTypeId)) {
+				// 绉戝.
+				if (String.isBlank(account.DepartmentNameD__c)) {
+					String errorMessage = '绉戝. 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}
+				// 琛屼笟.
+				if (String.isBlank(account.IndustryCD__c)) {
+					String errorMessage = '琛屼笟. 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}
+				// 甯傚満鍒嗙被.
+				if (String.isBlank(account.MarketVerticalsD__c)) {
+					String errorMessage = '甯傚満鍒嗙被. 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}
+				// 鐢ㄩ��.
+				if (String.isBlank(account.UseD__c)) {
+					String errorMessage = '鐢ㄩ��. 蹇呭~ 璇风‘璁�;';
+					errorMessageList.add(errorMessage);
+				}
+			}
+*/
+			if (errorMessageList.size() > 0){
+				result = '';
+				for (String error :errorMessageList) {
+					result += error +'\n';
+				}
+				result += '蹇呭~锛岃纭锛�';
+			}
+			
+		}
+		return result;
+	}
+	// 鎶�鏈湇鍔¢儴鎷呭綋銆佹妧鏈湇鍔¢儴(閮ㄩ暱銆佸壇閮ㄩ暱)銆両E 鏍锋満绠$悊鑰� 绠�妗� 鍒涘缓鑱旂郴浜鸿烦杩囧繀濉瓧娈甸獙璇侊紝鏀逛负鎻愪氦瀹℃壒鏃堕獙璇�
+	// CHAN-BU98HT XHL 20201014
+	WebService static String ContactRequiredField(String contactId) {
+		String result = '1';
+		List<String> errorMessageList = new List<String>();
+		List<Contact> contactList = [Select Id,Name,MobilePhone,MobilePhoneD__c,Postcode__c,PostcodeD__c,Address1__c,Address1D__c,CreatedById,ContactStatusD__c,RecordTypeId,CreatedBy.ProfileId,ProductSegmentBS__c  From Contact where Id = : contactId ];
+		String userId = UserInfo.getUserId();
+		if (contactList.size() > 0) {
+			Contact contact = contactList[0];
+			String profileId = contact.CreatedBy.ProfileId;
+			//鎶�鏈湇鍔¢儴鎷呭綋
+			if ('00e28000001sZE6'.equals(profileId.subString(0,15)) ||
+				'00e28000000eN67'.equals(profileId.subString(0,15))) {
+				if (String.isBlank(contact.MobilePhoneD__c)) {
+					String errorMessage = '鎵嬫満.';
+					errorMessageList.add(errorMessage);
+				}
+				if (String.isBlank(contact.Name)) {
+					String errorMessage = '濮撳悕';
+					errorMessageList.add(errorMessage);
+				}
+				
+				if (String.isBlank(contact.Address1D__c)) {
+					String errorMessage = '鍦板潃1.';
+					errorMessageList.add(errorMessage);
+				}
+				if(contact.ProductSegmentBS__c == true){
+					if (String.isBlank(contact.PostcodeD__c)) {
+					String errorMessage = '閭斂缂栫爜.';
+					errorMessageList.add(errorMessage);
+					}
+					if (String.isBlank(contact.ContactStatusD__c)) {
+						String errorMessage = '鐘舵��.	';
+						errorMessageList.add(errorMessage);
+					}
+				}
+			}
+			
+			// SSBG IE 鏍锋満绠$悊鑰咃紝SSBG鎶�鏈湇鍔¢儴锛堥儴闀裤兓鍓儴闀匡級
+			if ('00e28000000YQMx'.equals(profileId.subString(0,15)) || 
+				'00e0K000001l0l9'.equals(profileId.subString(0,15)) ||
+				'00e28000000eN67'.equals(profileId.subString(0,15))) {
+
+				if (String.isBlank(contact.MobilePhone)) {
+					String errorMessage = '鎵嬫満';
+					errorMessageList.add(errorMessage);
+				}
+				if (String.isBlank(contact.Name)) {
+					String errorMessage = '濮撳悕';
+					errorMessageList.add(errorMessage);
+				}
+				
+				if (String.isBlank(contact.Address1__c)) {
+					String errorMessage = '鍦板潃1';
+					errorMessageList.add(errorMessage);
+				}
+				
+				if(contact.ProductSegmentBS__c == true){
+					if (String.isBlank(contact.PostcodeD__c)) {
+					String errorMessage = '閭斂缂栫爜.';
+					errorMessageList.add(errorMessage);
+					}
+					if (String.isBlank(contact.ContactStatusD__c)) {
+						String errorMessage = '鐘舵��.	';
+						errorMessageList.add(errorMessage);
+					}
+				}
+			}
+		}
+
+		if (errorMessageList.size() > 0){
+			result = '';
+			for (String error :errorMessageList) {
+				result += error +'\n';
+			}
+			result += '蹇呭~锛岃纭锛�';
+		}
+		return result;
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/AccountWebService.cls-meta.xml b/scr/classes/AccountWebService.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/AccountWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AccountWebServiceTest.cls b/scr/classes/AccountWebServiceTest.cls
new file mode 100644
index 0000000..aa0b5ac
--- /dev/null
+++ b/scr/classes/AccountWebServiceTest.cls
@@ -0,0 +1,166 @@
+@isTest
+private class AccountWebServiceTest {
+
+    static testMethod void myUnitTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        Account acc2 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456'
+        );
+        Account acc3 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            CancelReason__c = 'test',
+            PostCode__c = '123456'
+        );
+        insert new List<Account> {acc1,acc2,acc3};
+        
+        String rs = '';
+        rs = AccountWebService.AccountCancel('12345678');
+        System.assertEquals('鏃犳晥鐨勫鎴�', rs);
+        
+        rs = AccountWebService.AccountCancel(acc1.Id);
+        System.assertEquals('瀹㈡埛宸茬粡鍙栨秷', rs);
+        
+        rs = AccountWebService.AccountCancel(acc2.Id);
+        System.assertEquals('蹇呴』杈撳叆鍙栨秷鐞嗙敱', rs);
+        
+        rs = AccountWebService.AccountCancel(acc3.Id);
+        System.assertEquals('1', rs);
+        List<Account> accList = [select Id,AccountStatus__c from Account where Id = :acc3.Id];
+        System.assertEquals('Cancel', accList[0].AccountStatus__c);
+    }
+
+    static testMethod void myUnitTest2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        String localid = UserInfo.getUserId();
+
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        insert acc1;
+
+        User user = new User();
+        user.LastName = 'test20201014';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'test@test.com';
+        user.Username = 'test111@test222.com';
+        user.CommunityNickname = 'test20201014';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+
+        AccountTeamMember atm = new AccountTeamMember(
+            AccountId = acc1.Id,
+            userId = localid,
+            teamMemberRole = 'Sales Manager'
+        );
+        AccountTeamMember atm2 = new AccountTeamMember(
+            AccountId = acc1.Id,
+            userId = user.Id,
+            teamMemberRole = 'Sales Manager'
+        );
+        insert new AccountTeamMember[] {atm,atm2};
+
+        String rs = '';
+        rs = AccountWebService.UpdateShare(acc1.Id, localid, user.Id);
+        System.assertEquals('1', rs);
+
+        List<AccountTeamMember> atmList = [select Id, AccountAccessLevel from AccountTeamMember where Id = :atm.Id];
+        System.assertEquals('Edit', atmList[0].AccountAccessLevel);
+    }
+    // 鎶�鏈湇鍔¢儴瀹㈡埛涓庤仈绯讳汉鐢宠鎻愪氦鏃跺瓧娈甸獙璇�
+    static testMethod void TechnicalServiceCreated() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456',
+            serviceCreate__c = true
+        );
+        Account acc2 = new Account(
+            name = '*',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            //DivisionName__c = 'Customer BS',
+            FacilityName__c = 'abc'
+        );
+        Account acc3 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            CancelReason__c = 'test',
+            PostCode__c = '123456'
+        );
+        User hpOwner = new User( LastName = 'hp', FirstName = 'owner', Alias = 'hp', CommunityNickname = 'hpOwner', Email = 'olympus_hpowner@sunbridge.com', Username = 'olympus_hpowner@sunbridge.com', IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja', ProfileId = System.Label.SystemAdmin2,MarketingStrategy__c =true);
+        insert hpOwner;
+        System.runAs(hpOwner){
+            insert new List<Account> {acc1,acc2,acc3};
+            
+            // insert dealer;
+            Contact core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=acc1.id);
+            insert core;
+
+            String rs = '';
+            // rs = AccountWebService.AccountCancel('12345678');
+            // System.assertEquals('鏃犳晥鐨勫鎴�', rs);
+            
+            rs = AccountWebService.RequiredField(acc1.Id);
+            // System.assertEquals('瀹㈡埛宸茬粡鍙栨秷', rs);
+            
+            rs = AccountWebService.RequiredField(acc2.Id);
+            // System.assertEquals('蹇呴』杈撳叆鍙栨秷鐞嗙敱', rs);
+            rs = AccountWebService.ContactRequiredField(core.Id);
+            // rs = AccountWebService.AccountCancel(acc3.Id);
+            // System.assertEquals('1', rs);
+            // List<Account> accList = [select Id,AccountStatus__c from Account where Id = :acc3.Id];
+            // System.assertEquals('Cancel', accList[0].AccountStatus__c);
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AccountWebServiceTest.cls-meta.xml b/scr/classes/AccountWebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/AccountWebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AgentContributionArticleController.cls b/scr/classes/AgentContributionArticleController.cls
new file mode 100644
index 0000000..8a0eb7e
--- /dev/null
+++ b/scr/classes/AgentContributionArticleController.cls
@@ -0,0 +1,16 @@
+public class AgentContributionArticleController {
+    // The constructor must take a ApexPages.KnowledgeArticleVersionStandardController as an argument
+    public AgentContributionArticleController(ApexPages.KnowledgeArticleVersionStandardController ctl) {
+        SObject article = ctl.getRecord();   //this is the SObject for the new article. 
+                                             //It can optionally be cast to the proper article type, e.g. FAQ__kav article = (FAQ__kav) ctl.getRecord();
+        
+        String sourceId = ctl.getSourceId(); //this returns the id of the case that was closed.
+        Case c = [select subject, description from Case where id=:sourceId];
+        
+        article.put('title', 'From Case: '+c.subject);  //this overrides the default behavior of pre-filling the title of the article with the subject of the closed case. 
+        article.put('Details__c',c.description);  
+        
+        ctl.selectDataCategory('Geography','USA');  //Only one category per category group can be specified.
+        ctl.selectDataCategory('Topics','Maintenance');                        
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AgentContributionArticleController.cls-meta.xml b/scr/classes/AgentContributionArticleController.cls-meta.xml
new file mode 100644
index 0000000..d75b058
--- /dev/null
+++ b/scr/classes/AgentContributionArticleController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>51.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AllAssetController.cls b/scr/classes/AllAssetController.cls
new file mode 100644
index 0000000..c51063a
--- /dev/null
+++ b/scr/classes/AllAssetController.cls
@@ -0,0 +1,227 @@
+public with sharing class AllAssetController {
+	
+	public String assECcode { get; set; }
+	public String assName { get; set; }
+	public Asset rec { get; set; }
+	public String setId { get; set; }
+
+	public List<EquipmentSetInfo> equipmentSetRecords { get; set; }
+	public List<EquipmentSetInfo> loanerSetRecords { get; set; }
+
+    private Integer dayCount = 0;
+
+
+	private Integer Select_Limit = 200;
+
+
+
+	public AllAssetController() {
+		 equipmentSetRecords = new List<EquipmentSetInfo>();
+	}
+
+	public Integer loanerSetNo {
+        get {
+            return loanerSetRecords == null ? 0 : loanerSetRecords.size();
+        }
+    }
+
+    public Integer pageRecordNo { 
+        get {
+            return equipmentSetRecords == null ? 0 : equipmentSetRecords.size();
+        }
+    }
+
+	public void init() {
+        List<Asset> assList = [select Id,Name, SerialNumber, Internal_Asset_number__c, OT_Code__c,EC_Code__c, Name__c,ProductName__c,
+        					AssetType__c,status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c,Remarks2__c,
+        					Rental_Customer__r.Name,Rental_End_Date__c,Description,Rental_Start_Date__c 
+        					from Asset 
+        					WHERE Id != null AND Equipment_Type__c = 'BS'];
+   		
+       	for(Integer i = 0 ;i<assList.size();i++){
+       		if (i == Select_Limit ){
+       			break;
+       		}
+
+       		equipmentSetRecords.add(new EquipmentSetInfo(assList[i]));
+       	}
+       	this.getLoanerSet();
+   		rec = new Asset();
+   		rec.Equipment_Type__c = 'BS';
+    }
+
+    public void getLoanerSet() {
+        // 鎵�鏈夋牱鏈篠et
+        loanerSetRecords = new List<EquipmentSetInfo>();
+        List<loaner_Set__c> loanerSetSearch = [select Id, Name, Equipment_Type__c,Remarks__c,SerialNumber__c,Internal_Asset_number__c,Status__c,loaner_place__c,Reservation_information__c
+                                                 from  Loaner_Set__c
+                                                 WHERE Equipment_Type__c = 'BS'
+                                                 order by Name];
+        Integer line = 0;
+        for(loaner_Set__c ls : loanerSetSearch){
+            EquipmentSetInfo li = new EquipmentSetInfo(line, ls);
+            loanerSetRecords.add(li);
+            line += 1;
+        }
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'loanerSetRecords' + loanerSetRecords));
+    }
+
+     public void getLoanerSetdet() {
+        
+       
+        // 鏍锋満set涓墍鏈夋牱鏈�
+        List<String> loanerSetDetIDList = new List<String>();
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+        for(Loaner_Set_Detail__c lSD : [SELECT Id,Asset__c FROM Loaner_Set_Detail__c WHERE Loaner_Set__c = :setId]){
+            loanerSetDetIDList.add(lSD.Asset__c);
+        }
+
+        List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c,Name__c,AssetType__c,
+                                        OT_Code__c, EC_Code__c, status,Count_can_allocate_F__c,
+                                        RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,ProductName__c
+                                        ,Description,Rental_Start_Date__c 
+                                    from Asset
+                                    where Id in :loanerSetDetIDList];
+                                   
+        // 鏂版槑缁嗚鍋氭垚  
+        for (Integer i = 0;  i < queryList.size(); i++) {
+            if (i == Select_Limit) {
+            	break;
+            }
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+             
+        }
+       
+    }
+
+      public void searchLoanerApp() {
+        //宸查�夋嫨涓綋绠$悊鏍锋満
+        List<String> loanerindividualList = new List<String>();
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+       
+        String soql = 'select Id,Name, SerialNumber, Loaner__c,Internal_Asset_number__c, OT_Code__c,EC_Code__c, Name__c,ProductName__c,AssetType__c,';
+              soql += ' status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c ,Description,Rental_Start_Date__c from Asset WHERE Id != null ';
+
+
+        if (!String.isBlank(assName)) {
+            soql += ' and Name like \'%' + String.escapeSingleQuotes(assName.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(rec.OT_Code__c)) {
+            soql += ' and OT_Code__c like \'%' + String.escapeSingleQuotes(rec.OT_Code__c.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(assECcode)) {
+            soql += ' and EC_Code__c like \'%' + String.escapeSingleQuotes(assECcode.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+       
+            soql += ' and Equipment_Type__c = \'BS\'';
+       
+        if (!String.isBlank(rec.loaner_place__c)) {
+            soql += ' and loaner_place__c = \'' + String.escapeSingleQuotes(rec.loaner_place__c) + '\'';
+        }
+        if (!String.isBlank(rec.Status)) {
+            soql += ' and status = \'' + String.escapeSingleQuotes(rec.Status) + '\'';
+        }
+         if (!String.isBlank(rec.SerialNumber)) {
+            soql += ' and SerialNumber like \'%' + String.escapeSingleQuotes(rec.SerialNumber.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(rec.Internal_Asset_number__c)) {
+            soql += ' and Internal_Asset_number__c like \'%' + String.escapeSingleQuotes(rec.Internal_Asset_number__c.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+
+
+
+
+        List<Asset> queryList = Database.query(soql);
+        System.debug(soql);
+        System.debug(queryList);
+        // 鏂版槑缁嗚鍋氭垚
+        for (Integer i = 0;  i < queryList.size(); i++) {
+            if (i == Select_Limit) {
+                break;
+            }
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+             
+        }
+        System.debug(equipmentSetRecords);
+
+    }
+
+
+    /* private void makeMessage() {
+        if (Over_Limit) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '鏁版嵁瓒呰繃' + Select_Limit + '浠讹紝鍙樉绀哄墠' + Select_Limit + '浠�'));
+            Over_Limit = false;
+        }
+    }*/
+
+
+    class EquipmentSetInfo implements Comparable {
+     	public Boolean check { get; set; }
+        public Boolean oldcheck { get; set; }
+        public loaner_application_detail__c lad { get; set; }
+        public Asset aset { get; set; }
+        public Loaner_Set__c lSet { get; set; }
+        public Date Rental_Start_Date { get; set; }
+        public Date Rental_End_Date { get; set; }
+        //鏈�鏃╁彲鍊熷嚭鏃堕棿
+        public Date earliest_Lend_Date { get; set; }
+        public Integer SEdayCount { get; set; }
+        public Integer deatilNo { get; set; }
+        public Boolean canInput { get; set; }
+        public Boolean showNo { get; set; }
+        public String remark { get; set; }
+        //public Date endDate {get; set; }
+        //杞�熷厓鐢宠鏄庣粏鏍囪
+        public Boolean firstDet { get; set; }
+
+        // 宸插瓨浜у搧鏄庣粏
+        public EquipmentSetInfo(loaner_application_detail__c e) {
+            check = true;
+            oldcheck= true;
+            lad = e;
+            aset = e.LOANER__r;
+            //endDate = aset.Rental_End_Date__c;
+            if(String.isNotBlank(lad.Remark__c)){
+                remark = lad.Remark__c;
+            }else{
+                remark = aset.Remarks2__c;
+            }
+            deatilNo = 1;
+            canInput = false;
+            firstDet = false;
+            if(String.valueOf(aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
+                showNo = true;
+            }else{
+                showNo = false;
+            }
+        }
+
+        public EquipmentSetInfo(Integer in_line, Loaner_Set__c e) {
+            deatilNo = in_line;
+            lSet = e;
+
+        }
+
+        public EquipmentSetInfo(Asset e) {
+            check = false;
+            oldcheck = false;
+            lad = new loaner_application_detail__c();
+            aset = e;
+            remark = aset.Remarks2__c;
+            firstDet = false;
+            if(String.valueOf(aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
+                canInput = true;
+                showNo = true;
+            }else{
+                //lad.loaner_ApplyNo__c = 1;
+                deatilNo = 1;
+                canInput = false;
+                showNo = false;
+            }
+        }
+        // 鎺掑簭
+        public Integer compareTo(Object compareTo) {
+            return null;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AllAssetController.cls-meta.xml b/scr/classes/AllAssetController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AllAssetController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AllAssetControllerTest.cls b/scr/classes/AllAssetControllerTest.cls
new file mode 100644
index 0000000..4ecb69e
--- /dev/null
+++ b/scr/classes/AllAssetControllerTest.cls
@@ -0,0 +1,146 @@
+@isTest
+private class AllAssetControllerTest {
+	
+	static Product2 prd1;
+    static Product2 prd2;
+    static Account acc;
+    static Account dealer;
+    static Contact core;
+    static User testUser;
+    static loaner_Set__c loanerSet;
+
+    //杞�熷厓浠g悊鍟�
+    static Account leaddealer;
+	static testMethod void setupTestData() {
+
+		List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'BS';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        loanerSet = new loaner_Set__c();
+        loanerSet.Equipment_Type__c = 'BS';
+        loanerSet.Set_No__c = 'IETEST0001';
+        loanerSet.Name = 'IETEST0001';
+
+        insert loanerSet;
+
+		// 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'BS';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'BS';
+        assetC1.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'BS';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        insert new Asset[] {asset,assetC1};
+
+        Loaner_Set_Detail__c lSD1 = new Loaner_Set_Detail__c();
+        lSD1.Loaner_Set__c = loanerSet.Id;
+        lSD1.Asset__c = asset.Id;
+        Loaner_Set_Detail__c lSD2 = new Loaner_Set_Detail__c();
+        lSD2.Loaner_Set__c = loanerSet.Id;
+        lSD2.Asset__c = assetC1.Id;
+        insert new Loaner_Set_Detail__c[] {lSD1,lSD2};
+
+        AllAssetController assetTest = new AllAssetController();
+        assetTest.init();
+
+        assetTest.assName = '1'; 
+        assetTest.assECcode = '1';
+        assetTest.rec.loaner_place__c = '1';
+        assetTest.rec.Status = '1';
+        assetTest.rec.SerialNumber = '1';
+        assetTest.rec.Internal_Asset_number__c = '1';
+
+        assetTest.searchLoanerApp();
+
+        assetTest.setId = loanerSet.id;
+        assetTest.getLoanerSetdet();
+
+        Integer i = assetTest.loanerSetNo;
+        i = assetTest.pageRecordNo;
+
+
+      }
+	
+}
\ No newline at end of file
diff --git a/scr/classes/AllAssetControllerTest.cls-meta.xml b/scr/classes/AllAssetControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AllAssetControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ApplicationMessageController.cls b/scr/classes/ApplicationMessageController.cls
new file mode 100644
index 0000000..a07d0ed
--- /dev/null
+++ b/scr/classes/ApplicationMessageController.cls
@@ -0,0 +1,123 @@
+public without sharing class ApplicationMessageController {
+    String oldResponse;
+    // 澶囧搧鍊熷嚭鐢宠
+    public loaner_application__c ra { get; set; }
+    public loaner_application__c ra1 { get; set; }
+    public loaner_application__c cc { get; set; }
+    // 澶囧搧鍊熷嚭鐢宠ID
+    public Id raid { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    
+
+    public ApplicationMessageController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+    }
+
+    public ApplicationMessageController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new loaner_application__c();
+        cc = new loaner_application__c();
+        List<loaner_application__c> raList = [select Id, Name, OCN_Internal_Notes__c from loaner_application__c where 
+
+Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        ra1 = new loaner_application__c();
+        List<loaner_application__c> ra1List = [select Id, Name, OCN_Internal_Notes__c from loaner_application__c where 
+
+Id = :raid];
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+        oldResponse = ra1.OCN_Internal_Notes__c;
+        ra1.OCN_Internal_Notes__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = ra1.OCN_Internal_Notes__c;
+        if (response == null || response.trim().length() == 0) {
+            ra1.OCN_Internal_Notes__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        // 鍘熺暀瑷�-oldResponse
+        // oldResponse = ra.OCN_Internal_Notes__c;
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += ra1.OCN_Internal_Notes__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+    //        loaner_application__c updra = new loaner_application__c();
+    //        updra.Id = ra.Id;
+            ra1.OCN_Internal_Notes__c = temp;
+
+            update ra1;
+            ra1.OCN_Internal_Notes__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new 
+
+Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+            //messageNEW.Subject = '澶囧搧鍊熷嚭鐢宠' + ra.Name + '' + 'OCN鍐呴儴鐣欒█';
+            messageNEW.Subject = '澶囧搧鍊熷嚭鐢宠 ' + ra1.Name + '-OCSM鍐呴儴鐣欒█';
+            messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');          
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ApplicationMessageController.cls-meta.xml b/scr/classes/ApplicationMessageController.cls-meta.xml
new file mode 100644
index 0000000..fec71a2
--- /dev/null
+++ b/scr/classes/ApplicationMessageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>42.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ApplicationMessageControllerTest.cls b/scr/classes/ApplicationMessageControllerTest.cls
new file mode 100644
index 0000000..a48c469
--- /dev/null
+++ b/scr/classes/ApplicationMessageControllerTest.cls
@@ -0,0 +1,79 @@
+@isTest
+public with sharing class ApplicationMessageControllerTest {
+
+    static testMethod void myTest1() {       
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+            loaner_application__c odr = new loaner_application__c(
+            Name = '',
+            Equipment_Type__c = 'IE',
+            OCN_Internal_Notes__c = ''
+        );
+        insert odr;
+        
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/ApplicationMessagePopUp?raid=' + 
+
+odr.Id );
+        System.Test.setCurrentPage(page);
+        
+        ApplicationMessageController controller = new ApplicationMessageController();
+        
+
+        //鍙栧緱澶囧搧鍊熷嚭鐢宠
+        loaner_application__c odr1 = [select Id, Name, OCN_Internal_Notes__c from 
+
+loaner_application__c where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1.OCN_Internal_Notes__c = 'test1';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+
+
+
+    }
+
+    static testMethod void myTest2() {       
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c odr = new loaner_application__c(
+            Name = '',
+            Equipment_Type__c = 'IE',
+            OCN_Internal_Notes__c = 'test1'
+        );
+        insert odr;
+        
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/ApplicationMessagePopUp?raid=' + 
+
+        odr.Id );
+        System.Test.setCurrentPage(page);
+        
+        ApplicationMessageController controller = new ApplicationMessageController();
+        
+
+        //鍙栧緱澶囧搧鍊熷嚭鐢宠
+        loaner_application__c odr1 = [select Id, Name, OCN_Internal_Notes__c from 
+
+        loaner_application__c where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init();
+        //System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        controller.ra1 = odr1;
+
+        //鍙戦�佹寜閽�
+        controller.ra1.OCN_Internal_Notes__c = '';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+
+
+
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/ApplicationMessageControllerTest.cls-meta.xml b/scr/classes/ApplicationMessageControllerTest.cls-meta.xml
new file mode 100644
index 0000000..fec71a2
--- /dev/null
+++ b/scr/classes/ApplicationMessageControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>42.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetNumberChangeController.cls b/scr/classes/AssetNumberChangeController.cls
new file mode 100644
index 0000000..e4c9d47
--- /dev/null
+++ b/scr/classes/AssetNumberChangeController.cls
@@ -0,0 +1,89 @@
+public with sharing class AssetNumberChangeController {
+    // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満ID
+    public String astId { get; private set; }
+    public Asset ast { get; private set; }
+    // 鏍锋満搴撳瓨璋冩暣鍘嗗彶
+    public Loaner_change_history__c lch { get; set; }
+
+    public AssetNumberChangeController() {
+        astId = System.currentPageReference().getParameters().get('id');
+    }
+
+    public AssetNumberChangeController(ApexPages.StandardController controller) {
+        astId = controller.getRecord().Id;
+    }
+
+    public PageReference init() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏍锋満淇℃伅鍙栧緱
+        if (String.isBlank(astId) == true) {
+            return null;
+        }
+        List<Asset> astList = [select id, Name, AccountId, EC_Code__c, SerialNumber,
+                                      Equipment_Type__c, lonar_owner__c, loaner_place__c, total_number__c
+                                 from Asset
+                                where Id = :astId];
+        if (astList.size() == 0) {
+            return null;
+        }
+        ast = astList[0];
+        // 鏂板缓鏍锋満搴撳瓨璋冩暣鍘嗗彶
+        lch = new Loaner_change_history__c();
+
+        return null;
+    }
+
+    public PageReference saveBtn() {
+        // 椤圭洰check
+        if (lch.change_content__c == null) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇疯緭鍏ヨ皟鏁村唴瀹广��'));
+            return null;
+        }
+        if (lch.change_number__c == null) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇疯緭鍏ヨ皟鏁存暟閲忋��'));
+            return null;
+        }
+
+        // 鏍锋満鎬绘暟璁$畻
+        if (ast.total_number__c == null) ast.total_number__c = 0;
+        Decimal total_number = ast.total_number__c + lch.change_number__c;
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鎻掑叆鏍锋満搴撳瓨璋冩暣鍘嗗彶
+            lch.Asset__c = ast.Id;
+            lch.change_day__c = Date.today();
+            lch.total_number__c = total_number;
+            insert lch;
+            // 鏍锋満鎬绘暟璁$畻
+            Asset upd_ast = new Asset(Id = ast.Id);
+            upd_ast.total_number__c = total_number;
+            update upd_ast;
+            // 杩斿洖鏍锋満璇︾粏鐢婚潰
+            String url = baseUrl;
+            url += '\\' + ast.Id;
+            return new Pagereference(url);
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+        }
+
+        return null;
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満璇︾粏鐢婚潰
+        String url = baseUrl;
+        url += '\\' + ast.Id;
+        return new Pagereference(url);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AssetNumberChangeController.cls-meta.xml b/scr/classes/AssetNumberChangeController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/AssetNumberChangeController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetNumberChangeControllerTest.cls b/scr/classes/AssetNumberChangeControllerTest.cls
new file mode 100644
index 0000000..5586088
--- /dev/null
+++ b/scr/classes/AssetNumberChangeControllerTest.cls
@@ -0,0 +1,66 @@
+@isTest
+private class AssetNumberChangeControllerTest {
+	@isTest static void test_method_one() {
+		List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+        //鏍锋満瀹㈡埛
+        Account acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'IE';
+        acc.PostCode__c='000000';
+        insert acc;
+
+		// 浜у搧
+        Product2 prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        Product2 prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'IE';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        insert asset;
+
+        PageReference page = new PageReference('/apex/AssetNumberChange?id=' + asset.Id);
+        page.setRedirect(true);
+        System.Test.setCurrentPage(page);
+        AssetNumberChangeController loanerApplyCon = new AssetNumberChangeController();
+        loanerApplyCon.init();
+        System.assertEquals('asset', loanerApplyCon.ast.Name);
+        loanerApplyCon.saveBtn();
+        loanerApplyCon.lch.change_content__c= '杩藉姞';
+        loanerApplyCon.saveBtn();
+        loanerApplyCon.lch.change_number__c= 30;
+        loanerApplyCon.saveBtn();
+        asset = [select Id,total_number__c from asset where Id = :asset.Id];
+        System.assertEquals(50, asset.total_number__c);
+
+        loanerApplyCon.cancelBtn();
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/AssetNumberChangeControllerTest.cls-meta.xml b/scr/classes/AssetNumberChangeControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/AssetNumberChangeControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetTriggerHandler.cls b/scr/classes/AssetTriggerHandler.cls
new file mode 100644
index 0000000..a070c9b
--- /dev/null
+++ b/scr/classes/AssetTriggerHandler.cls
@@ -0,0 +1,364 @@
+public without sharing class AssetTriggerHandler {
+
+    /*
+     *鍒ゆ柇鏍锋満绠$悊鑰呮槸鍚﹀彲浠ヤ慨鏀规牱鏈虹姸鎬�
+     *2018/10/17
+    */
+	public static void checkStatus(List<Asset> newList, Map<Id, Asset> newMap, List<Asset> oldList, Map<Id, Asset> oldMap) {
+        List<String> assetIdList = new List<String>();
+        Set<Asset> assSet = new Set<Asset>();
+        for(Asset ass : newList){
+            Asset oldAsset = oldMap.get(ass.Id);
+            //濡傛灉Status_text__c瀛楁涓嶄负绌� 锛屽垯鍒ゆ柇涓烘牱鏈虹鐞嗚�呬慨鏀�
+            if(ass.Status_text__c != null && ass.Status_text__c != ''){
+                //濡傛灉鏍锋満鐘舵�佷负鍦ㄥ簱锛屽垯璁や负鏍锋満绠$悊鑰呭彲浠ヤ慨鏀广��
+                if(oldAsset.Status == '鍦ㄥ簱') {
+                    assSet.add(ass);
+                    continue;
+                }
+                //濡傛灉鏍锋満鐘舵�佷笉涓� 鍦ㄥ簱 锛岃褰旾D鐢ㄤ簬鍒ゆ柇鏍锋満鐘舵�佽兘鍚︿慨鏀�
+                assetIdList.add(ass.Id);
+            }
+        }
+
+        Set<String> assetIdSet = new Set<String>();
+        Set<String> assetIDSet1 = new Set<String>();
+        if(assetIdList.size() > 0){
+            List<loaner_application_detail__c> ladList= [select id,LOANER__c,RAESD_Status__c,loaner_application__r.Status__c from loaner_application_detail__c where LOANER__c = : assetIdList];
+            
+            if(ladList.size()>0){
+                for(loaner_application_detail__c lad : ladList ){
+                    //濡傛灉鏄庣粏鐘舵�佷笉涓哄凡鍥炲簱锛屽垯璁や负鏍锋満澶勪簬鍊熺敤鍗曚箣涓紝涓嶈兘杩涜鎿嶄綔銆�
+                    if(lad.RAESD_Status__c == '宸插洖搴�' || (lad.RAESD_Status__c == '宸插垎閰�' && lad.loaner_application__r.Status__c == '鑽夋涓�')){
+                       assetIdSet.add(lad.LOANER__c);
+                    }else{
+                        assetIDSet1.add(lad.LOANER__c);
+                    }
+                }
+            }else{
+                assetIdSet.addAll(assetIdList);
+            }
+        }
+        
+        if(assetIDSet1.size() >0){
+            for(String ass : assetIDSet1){
+                newMap.get(ass).addError('璇ユ牱鏈哄湪绯荤粺涓湁鏍锋満鍊熺敤鐢宠鍗曪紝涓嶈兘淇敼');
+                return;
+            }
+        }
+        if(assetIdSet.size() > 0){
+            for(String ass : assetIdSet){
+                for(Integer i = 0; i < newList.size();i++){
+                    if(ass == newList[i].Id){
+                        newList[i].Status = newList[i].Status_text__c;
+                        newList[i].Status_text__c = null;
+                    }
+                } 
+            }
+        }
+        if(assSet.size() >0){
+            for(Asset ass : assSet){
+                ass.Status = ass.Status_text__c;
+                ass.Status_text__c = null;
+            }
+        }
+        AssetTriggerHandler.tes();
+
+    }
+
+    //鏍锋満鐘舵�佷慨鏀规椂锛屼慨鏀瑰瑁呮槑缁嗕腑鐨勪俊鎭�
+    public static void isInstock(List<Asset> newList, Map<Id, Asset> newMap, List<Asset> oldList, Map<Id, Asset> oldMap) {
+
+        List<String> idString = new List<String>();
+
+        for(Asset ass : newList){
+            Asset old = oldMap.get(ass.Id);
+            if(ass.Status != old.Status){
+                idString.add(ass.Id);
+            }
+        }
+
+        if(idString.size() == 0){
+            return;
+        }
+        
+        List<Loaner_Set_Detail__c> lsdList = [select id,Asset__c from Loaner_Set_Detail__c where Asset__c in :idString];
+        if(lsdList.size() == 0){
+            return;
+        }
+
+        for(Loaner_Set_Detail__c lsd : lsdList){
+            if(newMap.get(lsd.Asset__c).Status=='鍦ㄥ簱'){
+                lsd.is_instock__c = true;
+            }else{
+                lsd.is_instock__c = false;
+            }
+        }
+        
+        update lsdList;
+
+    }
+
+    //鍙湁鏍锋満鐘舵�佷负鍦ㄥ簱鏃�,ANI鍜孨DT鐨勬牱鏈虹鐞嗚�呮墠鑳戒慨鏀规牱鏈哄瓨鏀惧湴銆�
+    public static void checkPlace(List<Asset> newList, Map<Id, Asset> newMap, List<Asset> oldList, Map<Id, Asset> oldMap) {
+        String userId = UserInfo.getUserId();
+        userId.substring(0,15);
+        for(Asset ass : newList){
+            Asset old = oldMap.get(ass.Id);
+            if (ass.Status != '鍦ㄥ簱' && ass.ANI_NDTmanager__c == true) {
+                if (ass.loaner_place__c != old.loaner_place__c) {
+                    ass.loaner_place__c.addError('闈炲湪搴撶姸鎬佷笅涓嶈兘淇敼鏍锋満瀛樻斁鍦帮紒');
+                }
+            }
+            if (ass.ANI_NDTmanager__c == true) {
+                if (ass.Name != old.Name) {
+                    ass.Name.addError('涓嶅厑璁镐慨鏀逛繚鏈夎澶囧悕绉帮紒');
+                }
+            }
+            if (ass.ANI_NDTmanager__c == true) {
+                if (ass.Equipment_Type__c != old.Equipment_Type__c) {
+                    ass.Equipment_Type__c.addError('涓嶅厑璁镐慨鏀规牱鏈哄垎绫伙紒');
+                }
+            }
+        }
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    
+private static void tes(){
+    Integer i =1;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/AssetTriggerHandler.cls-meta.xml b/scr/classes/AssetTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/AssetTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetTriggerHandlerTest.cls b/scr/classes/AssetTriggerHandlerTest.cls
new file mode 100644
index 0000000..51bbadc
--- /dev/null
+++ b/scr/classes/AssetTriggerHandlerTest.cls
@@ -0,0 +1,325 @@
+@isTest
+private class AssetTriggerHandlerTest {
+	
+	static Product2 prd1;
+    static Product2 prd2;
+    static Account acc;
+    static Account dealer;
+    static Contact core;
+    static User testUser;
+    static Asset asset;
+    static Asset assetC1;
+    static Asset assetC2;
+	static void setupTestData() {
+
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+
+		List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'IE';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'IE';
+        acc.PostCode__c='000000';
+        insert acc;
+
+		// 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'IE';
+        assetC1.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd2.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        insert new Asset[] {assetC2,assetC1};
+    }
+	@isTest static void test_method_one() {
+
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+
+		// Implement test code
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        insert loanerApp;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+
+
+
+        assetC2.Status_text__c = '寰呬慨鐞�';
+        update assetC2;
+	}
+
+    @isTest static void test_01(){
+        List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'BS';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        loaner_Set__c loanerSet = new loaner_Set__c();
+        loanerSet.Equipment_Type__c = 'BS';
+        loanerSet.Set_No__c = 'IETEST0001';
+        loanerSet.Name = 'IETEST0001';
+
+        insert loanerSet;
+
+        // 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'BS';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍑哄��';
+        assetC1.Equipment_Type__c = 'BS';
+        assetC1.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍑哄��';
+        assetC2.Equipment_Type__c = 'BS';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        insert new Asset[] {asset,assetC1};
+
+        Loaner_Set_Detail__c lSD1 = new Loaner_Set_Detail__c();
+        lSD1.Loaner_Set__c = loanerSet.Id;
+        lSD1.Asset__c = asset.Id;
+        Loaner_Set_Detail__c lSD2 = new Loaner_Set_Detail__c();
+        lSD2.Loaner_Set__c = loanerSet.Id;
+        lSD2.Asset__c = assetC1.Id;
+        insert new Loaner_Set_Detail__c[] {lSD1,lSD2};
+
+        asset.Status = '鍑哄��';
+
+        update asset;
+
+        assetC1.Status = '鍦ㄥ簱';
+
+        update assetC1;
+
+    }
+
+	@isTest static void test_method_two() {
+
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+
+		// Implement test code
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        insert loanerApp;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '宸插洖搴�';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC1.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        assetC1.Status = '鍑哄��';
+        update assetC1;
+
+        
+    	assetC1.Status_text__c = '寰呬慨鐞�';
+    	update assetC1;
+    	
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/AssetTriggerHandlerTest.cls-meta.xml b/scr/classes/AssetTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AssetTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetTurnoverBatch.cls b/scr/classes/AssetTurnoverBatch.cls
new file mode 100644
index 0000000..f4e0446
--- /dev/null
+++ b/scr/classes/AssetTurnoverBatch.cls
@@ -0,0 +1,309 @@
+global without sharing class AssetTurnoverBatch implements Database.Batchable<sObject> {
+	public static Integer FIELDMAX = 62;
+    private final List<Id> TEST_ID = null;
+    private BatchIF_Log__c iflog;
+	
+	global AssetTurnoverBatch(List<Id> testId) {
+		TEST_ID = testId;
+        System.debug('TEST_ID=' + TEST_ID);
+        iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'PushNotification';
+        iflog.Log__c  = 'AssetTurnoverBatch start\n';
+        iflog.ErrorLog__c = '';
+        insert iflog;
+	}
+	
+	global AssetTurnoverBatch(){
+		iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'PushNotification';
+        iflog.Log__c  = 'AssetTurnoverBatch start\n';
+        iflog.ErrorLog__c = '';
+        insert iflog;
+	}
+  /**
+    *鏌ヨ鏍锋満鍊熷嚭鏄庣粏鐨勪俊鎭�
+  */
+	global Database.QueryLocator start(Database.BatchableContext BC) {
+		SS_Batch_Column_Mapping__c ladMapping = SS_Batch_Column_Mapping__c.getValues('loaner_application_detail__c');
+        Set<String> apiTempSet = new Set<String>();
+        apiTempSet.add('Id');
+        for (Integer i = 1; i <= FIELDMAX; i++) {
+            String lpadI = ('00' + i).right(3);
+            String fromColumn = 'From_Column_' + lpadI + '__c';
+            String apiStr = String.valueOf(ladMapping.get(fromColumn));
+            if (String.isBlank(apiStr) == false && apiTempSet.contains(apiStr) == false) {
+                apiTempSet.add(apiStr);
+            }
+        }
+        String soql = 'Select ' + String.join(new List<String>(apiTempSet), ',') + ' from ' + ladMapping.Name;
+        if (TEST_ID <> null) {
+            soql += ' where Id IN: TEST_ID';
+        } 
+        System.debug('soql=' + soql);
+        return Database.getQueryLocator(soql);
+	}
+  /**
+    *鏍锋満鍛ㄨ浆琛ㄧ敓鎴�
+  */
+  global void execute(Database.BatchableContext BC, List<loaner_application_detail__c> ladList) {
+		List<loaner_report__c> lrList = new List<loaner_report__c>();
+		SS_Batch_Column_Mapping__c ladMapping = SS_Batch_Column_Mapping__c.getValues('loaner_application_detail__c');
+   		//灏嗘牱鏈哄�熺敤鐢宠鏄庣粏鐨勫瓧娈电殑鍊煎鍒跺埌鍛ㄨ浆琛ㄤ腑銆�
+   		for(loaner_application_detail__c lad : ladList){
+   			Boolean insflag = false;
+   			loaner_report__c lr = new loaner_report__c();
+   			for(Integer i = 1; i <= FIELDMAX; i++){
+   				String lpadI = ('00' + i).right(3);
+	            String fromColumn = 'From_Column_' + lpadI + '__c';
+	            String apiStr = String.valueOf(ladMapping.get(fromColumn));
+	            if (String.isBlank(apiStr) == false) {
+	                String ssColumn = 'SS_Column_' + lpadI + '__c';
+                    String ssApiStr = String.valueOf(ladMapping.get(ssColumn));
+            		try{
+            			lr.put(ssApiStr, lad.get(apiStr));
+            		}catch(Exception e){
+            			iflog.ErrorLog__c = 'ERROR ' + String.valueOf(ladMapping.get('SS_TableName__c')) + ' [' + apiStr + '] => [' + ssApiStr + ']' + e.getMessage() + '\n';
+            		}
+            	}
+   			}
+   			System.debug(lr);
+   			lrList.add(lr);
+   		}
+     
+   		for(loaner_report__c lr : lrList){
+   			Integer thisMonth = Date.today().month() == 1 ? 12 : Date.today().month() -1;
+   			Integer lronMonth = null;
+   			Integer lroutMonth = null;
+
+   			Integer thisYear =  Date.today().month() == 1 ? Date.today().year() -1 : Date.today().year();
+   			Integer lronYear = null;
+   			Integer lroutYear = null;
+
+
+   			if(lr.Detail_Received_loaner_Date__c != null){
+   				lronMonth = lr.Detail_Received_loaner_Date__c.month();
+   				lronYear = lr.Detail_Received_loaner_Date__c.year();
+   			}
+   			if(lr.Detail_Shipment_Request_Date__c != null){
+   				lroutMonth = lr.Detail_Shipment_Request_Date__c.month();
+   				lroutYear = lr.Detail_Shipment_Request_Date__c.year();
+   			}
+   			
+   			System.debug('thisYear : ' + thisYear + '\tlronYear : ' + lronYear + '\tlroutYear : ' + lroutYear);
+   			System.debug('thisMonth : ' + thisMonth + '\tlronMonth : ' + lronMonth + '\tlroutMonth : ' + lroutMonth);
+        //鑾峰彇鏈湀澶╂暟,鏈堜唤,骞翠唤
+   			lr.DayOfTheMonth__c = Date.daysInMonth(thisYear, thisMonth);
+   			lr.Month__c = thisMonth;
+   			lr.Year__c =  String.valueOf(thisYear);
+   			lr.StatisticsTime__c = Date.newInstance(thisYear, thisMonth, 1);
+   			System.debug('dayInMonth : ' + lr.DayOfTheMonth__c);
+   			//鍒ゆ柇鏈湀鍊熷嚭澶╂暟
+   			if(thisMonth == lronMonth && thisYear == lronYear){
+   				if(thisMonth != lroutMonth ){
+            System.debug('1');
+   					lr.loan_days__c = Date.newInstance(thisYear, thisMonth, 1).daysBetween(lr.Detail_Received_loaner_Date__c) + 1;
+            lr.OutTime__c = Datetime.newInstance(thisYear, thisMonth, 1, 0, 0, 0);
+   				}else{
+            System.debug('666');
+   					lr.loan_days__c = lr.Detail_Shipment_Request_Date__c.daysBetween(lr.Detail_Received_loaner_Date__c) + 1;
+   				}
+   			}else if(lronMonth == null){
+   				if(thisMonth == lroutMonth && thisYear == lroutYear){
+   					lr.loan_days__c = lr.Detail_Shipment_Request_Date__c.daysBetween(Date.newInstance(thisYear, thisMonth, Date.daysInMonth(thisYear, thisMonth))) + 1;
+   				  lr.inTime__c = Datetime.newInstance(thisYear,thisMonth+1,1,0,0,0);
+          }else if(lroutMonth > thisMonth && thisYear == lroutYear){
+   					lr.loan_days__c = 0;
+            System.debug('2');
+            lr.inTime__c = null;
+            lr.OutTime__c = null;
+   				}else if(lroutMonth == null){
+   					lr.loan_days__c = 0;
+            System.debug('3');
+            lr.inTime__c = null;
+            lr.OutTime__c = null;
+   				}else{
+   					lr.loan_days__c = lr.DayOfTheMonth__c;
+            lr.OutTime__c = Datetime.newInstance(thisYear, thisMonth, 1, 0, 0, 0);
+            lr.inTime__c = Datetime.newInstance(thisYear,thisMonth+1,1,0,0,0);
+   				}
+   			}else{
+   				if(lroutMonth == thisMonth && lroutYear == thisYear && lronMonth > thisMonth){
+   					lr.loan_days__c = lr.Detail_Shipment_Request_Date__c.daysBetween(Date.newInstance(thisYear, thisMonth, Date.daysInMonth(thisYear, thisMonth))) + 1;
+   				  lr.inTime__c = Datetime.newInstance(thisYear, thisMonth+1, 1, 0, 0, 0);
+          }else{
+            System.debug('4');
+   					lr.loan_days__c = 0;
+            lr.inTime__c = null;
+            lr.OutTime__c = null;
+   				}
+   			}
+   		}
+
+   		System.debug(lrList);
+      this.aa();
+   		try{
+   			insert lrList;
+   		}catch(Exception e){
+   			System.debug(e);
+   		}
+	}
+	
+	global void finish(Database.BatchableContext BC) {
+		
+	}
+
+	
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  public void aa(){
+    Integer i = 1;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+  }
+}
\ No newline at end of file
diff --git a/scr/classes/AssetTurnoverBatch.cls-meta.xml b/scr/classes/AssetTurnoverBatch.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AssetTurnoverBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetTurnoverBatchTest.cls b/scr/classes/AssetTurnoverBatchTest.cls
new file mode 100644
index 0000000..33dad07
--- /dev/null
+++ b/scr/classes/AssetTurnoverBatchTest.cls
@@ -0,0 +1,123 @@
+@isTest
+private class AssetTurnoverBatchTest {
+	
+	@isTest(SeeAllData = true) static void test_method_one() {
+		// Implement test code
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6).addMonths(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7).addMonths(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12).addMonths(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+       	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner.Request_return_Date__c = Date.today().addDays(10);
+        loaner.Status__c = '閮ㄥ垎鍙戣揣';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        Loaner_Express__c le = new Loaner_Express__c(
+    	Name = 'test01',
+    	loaner_application__c = loaner.Id,
+    	NotReceivingNum__c = 3
+    	);
+
+        insert le;
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        detail.Loaner_Express__c = le.id;
+        detail.Received_loaner_Date__c = Date.today().addMonths(-1);
+        detail.Shipment_Request_Date__c  = Date.today().addMonths(-1);
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        detail.Loaner_Express__c = le.id;
+		//detail.Shipment_Request_Date__c = Date.today();
+        detail.Received_loaner_Date__c = Date.today().addMonths(-1);
+        detail.Shipment_Request_Date__c  = Date.today().addMonths(-1);
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        detail.Received_loaner_Date__c = Date.today().addMonths(-1);
+        detail.Shipment_Request_Date__c  = Date.today().addMonths(-1);
+        detail.Loaner_Express__c = le.id;
+        In_detail.add(detail);
+
+        insert In_detail;
+        List<Id> ladIdList = new List<Id>();
+        for(loaner_application_detail__c lad : In_detail){
+        	if(lad.Id != null){
+        		ladIdList.add(lad.Id);
+        	}
+        }
+
+        SS_Batch_Column_Mapping__c ladMapping = SS_Batch_Column_Mapping__c.getValues('loaner_application_detail__c');
+        String lpadI = ('00' + 1).right(3);
+        String fromColumn = 'From_Column_' + lpadI + '__c';
+        String apiStr = String.valueOf(ladMapping.get(fromColumn)); 
+        Database.executeBatch(new AssetTurnoverBatch(ladIdList), 200);
+
+	}
+	
+	
+}
\ No newline at end of file
diff --git a/scr/classes/AssetTurnoverBatchTest.cls-meta.xml b/scr/classes/AssetTurnoverBatchTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AssetTurnoverBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetTurnoverSchedulable.cls b/scr/classes/AssetTurnoverSchedulable.cls
new file mode 100644
index 0000000..c15b35d
--- /dev/null
+++ b/scr/classes/AssetTurnoverSchedulable.cls
@@ -0,0 +1,7 @@
+global class AssetTurnoverSchedulable implements Schedulable {
+	global void execute(SchedulableContext sc) {
+		//MyBatchClass b = new MyBatchClass();
+		//database.executebatch(b);
+		Id execBTId = Database.executeBatch(new AssetTurnoverBatch(), 200);
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/AssetTurnoverSchedulable.cls-meta.xml b/scr/classes/AssetTurnoverSchedulable.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AssetTurnoverSchedulable.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AssetTurnoverSchedulableTest.cls b/scr/classes/AssetTurnoverSchedulableTest.cls
new file mode 100644
index 0000000..47446cc
--- /dev/null
+++ b/scr/classes/AssetTurnoverSchedulableTest.cls
@@ -0,0 +1,20 @@
+@isTest
+private class AssetTurnoverSchedulableTest {
+
+    static testMethod void testExecute() {
+        // This test runs a scheduled job at midnight Sept. 3rd. 2022
+        String CRON_EXP = '0 0 0 3 9 ? 2032';
+
+        System.Test.startTest();
+        // Schedule the test job
+        String jobId = system.schedule('AssetTurnoverSchedulableTest', CRON_EXP, new AssetTurnoverSchedulable());
+        // Get the information from the CronTrigger API object
+        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
+        // Verify the expressions are the same
+        System.assertEquals(CRON_EXP, ct.CronExpression);
+        // Verify the job has not run
+        System.assertEquals(0, ct.TimesTriggered);
+        // Verify the next time the job will run
+        System.assertEquals('2032-09-03 00:00:00', String.valueOf(ct.NextFireTime));
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AssetTurnoverSchedulableTest.cls-meta.xml b/scr/classes/AssetTurnoverSchedulableTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/AssetTurnoverSchedulableTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AttachmentTriggerHandler.cls b/scr/classes/AttachmentTriggerHandler.cls
new file mode 100644
index 0000000..7eb3708
--- /dev/null
+++ b/scr/classes/AttachmentTriggerHandler.cls
@@ -0,0 +1,537 @@
+public without sharing class AttachmentTriggerHandler {
+
+    public static void fileCheck(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<String> orderIdList = new List<String>();
+        List<String> orderIdList2 = new List<String>();
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            String name = newAtt.Name;
+            if (parentId.startsWith('801') && name.startsWith('ORDER-')) {
+                orderIdList.add(newAtt.parentId);
+            }
+            if (parentId.startsWith('801')) {
+                orderIdList2.add(newAtt.parentId);
+            }
+        }
+
+        Map<String, String> isUploadMap = new Map<String, String>();
+        Map<String, String> draftMap = new Map<String, String>();
+        Map<String, String> submitMap = new Map<String, String>();
+        Map<String, String> passMap = new Map<String, String>();
+        if (orderIdList.size() > 0) {
+            List<Order> orderList = [select id,IsUpload__c,ApproveStatus__c from Order where id = :orderIdList];
+            for (Order o : orderList) {
+                if (o.IsUpload__c) {
+                    isUploadMap.put(o.Id, o.Id);
+                }
+                if (o.ApproveStatus__c == 'Draft' || o.ApproveStatus__c == 'Completed' || o.ApproveStatus__c == 'Reject') {
+                    draftMap.put(o.Id, o.Id);
+                }
+            }
+        }
+        if (orderIdList2.size() > 0) {
+            List<Order> orderList2 = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c from Order where id = :orderIdList2];
+            for (Order o : orderList2) {
+                if (o.ApproveStatus__c == 'Submit' || o.ApproveStatus__c == 'OrderSubmit') {
+                    submitMap.put(o.Id, o.Id);
+                }
+                if (o.IsOrderPassed__c) {
+                    passMap.put(o.Id, o.Id);
+                }
+            }
+        }
+        //鏂扮殑鑾峰彇浜哄憳绠�妗D 鑾峰彇鍒扮殑ID鏄�15浣�
+        // String profileId = UserInfo.getProfileId().substring(0, 15);
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        for (Attachment newAtt : newList) {
+//            if (UserInfo.getProfileId() != System.Label.SystemAdmin && passMap.containsKey(newAtt.parentId)
+//                && UserInfo.getProfileId() != System.Label.Business_department) {
+//                newAtt.addError('鍚堝悓鎵瑰噯鍚庝笉鑳芥洿鏀归檮浠躲��');
+//            }
+             
+            if (new_profileId != System.Label.Business_department && new_profileId != System.Label.SystemAdmin 
+                && submitMap.containsKey(newAtt.parentId)) {
+                newAtt.addError('鍚堝悓琚攣瀹氾紝涓嶈兘涓婁紶闄勪欢銆�');
+            }
+            if (isUploadMap.containsKey(newAtt.parentId)) {
+                newAtt.addError('鍚堝悓闄勪欢宸茬粡瀛樺湪锛屼笉鑳戒笂浼犲涓��');
+            }
+            if (draftMap.containsKey(newAtt.parentId)) {
+                newAtt.addError('璇峰厛瀹℃壒瀹岀壒娈婃潯浠跺啀鎻愪氦鍚堝悓鏂囦欢銆�');
+            }
+        }
+    }
+    //绂佹涓婁紶澶氫釜鏀惰揣纭鍗曞拰瑁呮満纭鍗�
+    public static void fileCheck5(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<String> lacIdList1 = new List<String>();
+        List<String> lacIdList2 = new List<String>();
+        List<String> lacIdList3 = new List<String>();
+        List<String> lacIdList4 = new List<String>();
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            String name = newAtt.Name;
+            if (parentId.startsWith('a0Q') && name.startsWith('鏀惰揣纭-')) {
+                lacIdList1.add(newAtt.parentId);
+            }
+            if(parentId.startsWith('a0Q') && name.startsWith('瑁呮満纭')){
+                lacIdList2.add(newAtt.parentId);
+            }
+            if(parentId.startsWith('a0Q') && (name.startsWith('鍊熺敤鍗忚') || name.startsWith('鍊熺敤鍗�') || name.startsWith('DeliveryConfirmPDF'))){
+                lacIdList3.add(newAtt.parentId);
+            }
+            if(parentId.startsWith('a0Q') && name.startsWith('杞�熺‘璁�')){
+                lacIdList4.add(newAtt.parentId);
+            }
+
+        }
+        Map<String,String> isUploadMap1 = new Map<String,String>();
+        Map<String,String> isUploadMap2 = new Map<String,String>();
+        Map<String,String> isUploadMap3 = new Map<String,String>();
+        Map<String,String> isUploadMap4 = new Map<String,String>();
+        if(lacIdList1.size()>0){
+            List<loaner_application__c> lacList1 = [select id,Receipt_Attachment__c from loaner_application__c where id = :lacIdList1];
+            for(loaner_application__c lac :lacList1){
+                if(lac.Receipt_Attachment__c){
+                    isUploadMap1.put(lac.Id, lac.Id);
+                }
+            }
+        }
+        if(lacIdList2.size()>0){
+            List<loaner_application__c> lacList2 = [select id,Installation_Qualification_Attachment__c from loaner_application__c where id = :lacIdList2];
+            for(loaner_application__c lac : lacList2){
+                if(lac.Installation_Qualification_Attachment__c){
+                    isUploadMap2.put(lac.Id, lac.Id);
+                }
+            }
+        }
+        if(lacIdList3.size()>0){
+            List<loaner_application__c> lacList3 = [select id,Loaner_AgreementPDF__c from loaner_application__c where id = :lacIdList3];
+            for(loaner_application__c lac : lacList3){
+                if(lac.Loaner_AgreementPDF__c){
+                    isUploadMap3.put(lac.Id, lac.Id);
+                }
+            }
+        }
+        if(lacIdList4.size()>0){
+            List<loaner_application__c> lacList4 = [select id,Loaner_Confirm_Photo__c from loaner_application__c where id = :lacIdList4];
+            for(loaner_application__c lac : lacList4){
+                if(lac.Loaner_Confirm_Photo__c){
+                    isUploadMap4.put(lac.Id, lac.Id);
+                }
+            }
+        }
+        for(Attachment newAtt : newList){
+            if(isUploadMap1.containsKey(newAtt.parentId)){
+                newAtt.addError('鏀惰揣纭闄勪欢宸茬粡瀛樺湪锛屼笉鑳戒笂浼犲涓��');
+            }
+            if(isUploadMap2.containsKey(newAtt.parentId)){
+                newAtt.addError('瑁呮満纭闄勪欢宸茬粡瀛樺湪锛屼笉鑳戒笂浼犲涓��');
+            }
+            if(isUploadMap3.containsKey(newAtt.parentId)){
+                newAtt.addError('鍊熺敤鍗忚闄勪欢宸茬粡瀛樺湪锛屼笉鑳戒笂浼犲涓��');
+            }
+            if(isUploadMap4.containsKey(newAtt.parentId)){
+                newAtt.addError('杞�熺‘璁ら檮浠跺凡缁忓瓨鍦紝涓嶈兘涓婁紶澶氫釜銆�');
+            }
+        }
+
+    }
+    //瑁呮満纭鍚�,绂佹鍒犻櫎纭鍗�
+    public static void fileCheck6(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+
+        List<String> lacIdList = new List<String>();
+        List<String> lacIdList1 = new List<String>();
+        for(Attachment oldAtt : oldList){
+            String parentId = oldAtt.parentId;
+            String name = oldAtt.Name;
+            if(parentId.startsWith('a0Q') && name.startsWith('瑁呮満纭')){
+                lacIdList.add(parentId);
+            }
+            if(parentId.startsWith('a0Q') && (name.startsWith('鍊熺敤鍗忚') || name.startsWith('鍊熺敤鍗�') || name.startsWith('DeliveryConfirmPDF'))){
+                lacIdList1.add(parentId);
+            }
+        }
+
+        Map<String,String> deleteMap = new Map<String,String>();
+        Map<String,String> deleteMap1 = new Map<String,String>();
+        if(lacIdList.size()>0){
+            List<loaner_application__c> lacList = [select id,HP_Received_Sign_Date__c from loaner_application__c where id = :lacIdList];
+            for(loaner_application__c lac : lacList){
+                if(lac.HP_Received_Sign_Date__c != null){
+                    deleteMap.put(lac.id,lac.id);
+                }
+            }
+        }
+        if(lacIdList1.size() >0 ){
+            List<loaner_application__c> lacList1 = [select id,Bollow_Date__c from loaner_application__c where id = :lacIdList1];
+            for(loaner_application__c lac: lacList1){
+                if(lac.Bollow_Date__c != null){
+                    deleteMap1.put(lac.id,lac.id);
+                }
+            }
+        }
+        for(Attachment oldAtt : oldList){
+            if(deleteMap.containsKey(oldAtt.parentId)){
+                oldAtt.addError('宸茶鏈虹‘璁�,涓嶈兘鍒犻櫎瑁呮満纭闄勪欢');
+            }
+            if(deleteMap1.containsKey(oldAtt.parentId)){
+                oldAtt.addError('宸插嚭搴撴寚绀�,涓嶈兘鍒犻櫎鍊熺敤鍗忚闄勪欢');
+            }
+        }
+
+    }
+
+    public static void uploadContract(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<Order> orderList = new List<Order>();
+       
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            String name = newAtt.Name;
+            if (parentId.startsWith('801') && name.startsWith('ORDER-')) {
+                Order ord = new Order();
+                ord.Id = parentId;
+                //ord.Name = name.substring(6, name.indexOf('.'));
+                ord.Upload_IsChanged__c = true;
+                ord.IsUpload__c = true;
+
+                orderList.add(ord);
+            }
+        }
+
+        if (orderList.size() > 0) {
+            update orderList;
+        }
+
+    }
+
+    // Added by HANCHAO 20170123
+    public static void AfterPassUpload(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<Order> orderList = new List<Order>();
+
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            if (parentId.startsWith('801')) {
+                Order ord1 = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c from Order where id = :parentId];
+                if (ord1.IsOrderPassed__c) {
+                    Order ord = new Order();
+                    ord.Id = parentId;
+                    ord.AfterPassAttachmentUpload__c = true;
+                    orderList.add(ord);
+                }
+            }
+        }
+
+        if (orderList.size() > 0) {
+            update orderList;
+        }
+
+    }
+    //娣诲姞纭鍗曟椂娣诲姞瀵瑰簲鏍囪
+    public static void fileCheck4(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
+
+        List<loaner_application__c> lacList = new List<loaner_application__c>();
+
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            String name = newAtt.Name;
+            //鍒ゆ柇鏄惁涓婁紶鏀惰揣纭闄勪欢鍜屽畨瑁呯‘璁ら檮浠�
+            if(parentId.startsWith('a0Q')){
+                if(name.startsWith('鏀惰揣纭-')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+ //                    [select id,Receipt_Attachment__c from loaner_application__c where id = :parentId];
+                    lac.Receipt_Attachment__c = true;
+                    lacList.add(lac);
+                }
+                if(name.startsWith('瑁呮満纭')){
+                    loaner_application__c lac =new loaner_application__c();
+                    lac.id = parentId;
+ //                   [select id,Installation_Qualification_Attachment__c from loaner_application__c where id = :parentId];
+                    lac.Installation_Qualification_Attachment__c = true;
+                    lacList.add(lac);  
+                }
+                if(name.startsWith('鍊熺敤鍗忚') || name.startsWith('鍊熺敤鍗�') || name.startsWith('DeliveryConfirmPDF')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+                    lac.Loaner_AgreementPDF__c = true;
+                    lacList.add(lac);
+                }
+                 if(name.startsWith('杞�熺‘璁�')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+                    lac.Loaner_Confirm_Photo__c = true;
+                    lacList.add(lac);
+                }
+            }
+        }
+
+
+        if(lacList.size() > 0){
+            try{
+                update lacList;
+            }catch(Exception ex){
+                newList[0].addError(ex.getMessage().mid((ex.getMessage().indexOf('first error:') + 12),ex.getMessage().length()));
+            }
+        }
+
+    }
+
+    public static void fileCheck2(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<String> orderIdList = new List<String>();
+
+        for (Attachment oldAtt : oldList) {
+            String parentId = oldAtt.parentId;
+            if (parentId.startsWith('801')) {
+                orderIdList.add(oldAtt.parentId);
+            }
+        }
+
+        Map<String, String> submitMap = new Map<String, String>();
+        Map<String, Order> passMap = new Map<String, Order>();
+
+        if (orderIdList.size() > 0) {
+            List<Order> orderList = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c, Is_Already_Splited__c from Order where id = :orderIdList];
+            for (Order o : orderList) {
+                if (o.ApproveStatus__c == 'Submit' || o.ApproveStatus__c == 'OrderSubmit') {
+                    submitMap.put(o.Id, o.Id);
+                }
+                if (o.IsOrderPassed__c) {
+                    passMap.put(o.Id, o);
+                }
+            }
+        }
+        //鏂扮殑鑾峰彇浜哄憳绠�妗D 鑾峰彇鍒扮殑ID鏄�15浣�
+        // String profileId = UserInfo.getProfileId().substring(0, 15);
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        for (Attachment oldAtt : oldList) {
+            /*if (UserInfo.getProfileId() != System.Label.SystemAdmin && submitMap.containsKey(oldAtt.parentId)) {
+                oldAtt.addError('鍚堝悓琚攣瀹氾紝涓嶈兘鏇存敼闄勪欢銆�');
+            }
+            if (UserInfo.getProfileId() != System.Label.SystemAdmin && passMap.containsKey(oldAtt.parentId)
+                && UserInfo.getProfileId() != System.Label.Business_department && passMap.get(oldAtt.parentId).Is_Already_Splited__c == false) {
+                oldAtt.addError('鍚堝悓鎵瑰噯鍚庝笉鑳芥洿鏀归檮浠躲��');
+            }*/
+            if (new_profileId != System.Label.SystemAdmin
+                && submitMap.containsKey(oldAtt.parentId)) {
+                oldAtt.addError('鍚堝悓琚攣瀹氾紝涓嶈兘鏇存敼闄勪欢銆�');
+            }
+            if (new_profileId != System.Label.SystemAdmin && passMap.containsKey(oldAtt.parentId)
+                && new_profileId != System.Label.Business_department && passMap.get(oldAtt.parentId).Is_Already_Splited__c == false) {
+                oldAtt.addError('鍚堝悓鎵瑰噯鍚庝笉鑳芥洿鏀归檮浠躲��');
+            }
+        }
+    }
+
+    public static void fileCheck3(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<String> orderIdList = new List<String>();
+
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            if (parentId.startsWith('801')) {
+                orderIdList.add(newAtt.parentId);
+            }
+        }
+
+        Map<String, String> submitMap = new Map<String, String>();
+        Map<String, Order> passMap = new Map<String, Order>();
+
+        if (orderIdList.size() > 0) {
+            List<Order> orderList = [select id,IsUpload__c,ApproveStatus__c,IsOrderPassed__c, Is_Already_Splited__c from Order where id = :orderIdList];
+            for (Order o : orderList) {
+                if (o.ApproveStatus__c == 'Submit' || o.ApproveStatus__c == 'OrderSubmit') {
+                    submitMap.put(o.Id, o.Id);
+                }
+                if (o.IsOrderPassed__c) {
+                    passMap.put(o.Id, o);
+                }
+            }
+        }
+        //鏂扮殑鑾峰彇浜哄憳绠�妗D 鑾峰彇鍒扮殑ID鏄�15浣�
+        // String profileId = UserInfo.getProfileId().substring(0, 15);
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        /*for (Attachment newAtt : newList) {
+            if (UserInfo.getProfileId() != System.Label.SystemAdmin && submitMap.containsKey(newAtt.parentId)) {
+                newAtt.addError('鍚堝悓琚攣瀹氾紝涓嶈兘鏇存敼闄勪欢銆�');
+            }
+            if (UserInfo.getProfileId() != System.Label.SystemAdmin && passMap.containsKey(newAtt.parentId)
+                && UserInfo.getProfileId() != System.Label.Business_department && passMap.get(newAtt.parentId).Is_Already_Splited__c == false) {
+                newAtt.addError('鍚堝悓鎵瑰噯鍚庝笉鑳芥洿鏀归檮浠躲��');
+            }
+        }*/
+        for (Attachment newAtt : newList) {
+            if (new_profileId != System.Label.SystemAdmin  
+                && submitMap.containsKey(newAtt.parentId)) {
+                newAtt.addError('鍚堝悓琚攣瀹氾紝涓嶈兘鏇存敼闄勪欢銆�');
+            }
+            if (new_profileId != System.Label.SystemAdmin && passMap.containsKey(newAtt.parentId)
+                && new_profileId != System.Label.Business_department && passMap.get(newAtt.parentId).Is_Already_Splited__c == false) {
+                newAtt.addError('鍚堝悓鎵瑰噯鍚庝笉鑳芥洿鏀归檮浠躲��');
+            }
+        }
+    }
+
+    public static void deleteContract(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<Order> orderList = new List<Order>();
+
+        for (Attachment oldAtt : oldList) {
+            String parentId = oldAtt.parentId;
+            String name = oldAtt.Name;
+            if (parentId.startsWith('801') && name.startsWith('ORDER-')) {
+                Order ord = new Order();
+                ord.Id = parentId;
+                //ord.Name = '';
+                ord.Upload_IsChanged__c = true;
+                ord.IsUpload__c = false;
+
+                orderList.add(ord);
+            }
+        }
+
+        if (orderList.size() > 0) {
+            update orderList;
+        }
+    }
+
+    //鍒犻櫎纭鍗曟椂鍙栨秷瀵瑰簲鏍囪;
+    public static void deleteconfirm(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
+        List<loaner_application__c> lacList = new List<loaner_application__c>();
+
+        for (Attachment oldAtt : oldList) {
+            String parentId = oldAtt.parentId;
+            String name = oldAtt.Name;
+            //鍒ゆ柇鏄惁鍒犻櫎鏀惰揣纭闄勪欢鍜屽畨瑁呯‘璁ら檮浠�
+            if(parentId.startsWith('a0Q')){
+                if(name.startsWith('鏀惰揣纭-')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+//                    [select id,Receipt_Attachment__c from loaner_application__c where id = :parentId];
+                    lac.Receipt_Attachment__c = false;
+                    lacList.add(lac);
+                }
+                if(name.startsWith('瑁呮満纭')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+//                    [select id,Installation_Qualification_Attachment__c from loaner_application__c where id = :parentId];
+                    lac.Installation_Qualification_Attachment__c = false;
+                    lacList.add(lac);  
+                }
+                if(name.startsWith('鍊熺敤鍗忚') || name.startsWith('鍊熺敤鍗�') || name.startsWith('DeliveryConfirmPDF')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+                    lac.Loaner_AgreementPDF__c = false;
+                    lacList.add(lac);
+                }
+                if(name.startsWith('杞�熺‘璁�')){
+                    loaner_application__c lac = new loaner_application__c();
+                    lac.id = parentId;
+                    lac.Loaner_Confirm_Photo__c = false;
+                    lacList.add(lac);
+                }
+            }
+        }
+        if(lacList.size() > 0){
+            update lacList;
+        }        
+    }
+
+    //涓氬姟娲诲姩涓婁紶闄勪欢瀹屾垚涔嬪悗灏嗛檮浠跺厠闅嗚嚦鐩稿叧鑱旂殑鐢ㄦ埛淇℃伅涓婇潰
+    public static void AfterUploadToUserFaultInfo(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap) {
+        List<String> selectBAIdList = new List<String>();
+        String firstThreeDigitCode= System.label.FirstThreeDigitCode;
+        for (Attachment newAtt : newList) {
+            String parentId = newAtt.parentId;
+            if (parentId.startsWith(firstThreeDigitCode)) {
+                selectBAIdList.add(parentId);
+            }
+        }
+        
+        if (selectBAIdList.size() > 0) {
+            List<BusinessActivity__c> businessActivityList = TSRepairUtil.GetBusinessActivityList(null,null, selectbaIdList,null,null,'');
+
+            String userFaultInfoId = businessActivityList[0].User_FaultInfo__c;
+            System.debug('userFaultInfoId---->'+userFaultInfoId);
+            if (String.isNotBlank(userFaultInfoId)) {
+                    
+                    // 鑾峰彇鐢ㄦ埛/鏁呴殰淇℃伅鐨勯檮浠�
+                    List<String> selectUfIdList = new List<String>();
+                    selectUfIdList.add(userFaultInfoId);
+                    List<Attachment> ufAttachmentList = TSRepairUtil.GetAttachmentList(selectUfIdList);
+
+                    if (ufAttachmentList.size() >0){
+                        //鍒犻櫎鐢ㄦ埛/鏁呴殰淇℃伅鐨勯檮浠�
+                        delete ufAttachmentList;
+                        
+                    }
+
+                    //灏嗕笟鍔℃椿鍔ㄤ笅鐨勯檮浠跺厠闅嗚嚦 鐢ㄦ埛/鏁呴殰淇℃伅
+                    TSRepairUtil.insertattachmentCloneList(selectBAIdList,userFaultInfoId);
+                    
+                }
+
+        }
+    }
+    //鐜嬮箯浼� 璐告槗绠$悊瀹㈡埛鐢宠琛� 鍚堝悓宸叉彁浜� 涓嶅厑璁镐慨鏀硅锤鏄撶鐞嗗鎴风敵璇疯〃闄勪欢 
+    public static void updateTradeCustomerManagerFile(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
+        for(Attachment accach : newList){
+            String parentId = accach.parentId;
+            String tradeCustomerManagerStart = System.label.TradeCustomerManagerStart;
+            if(parentId.startsWith(tradeCustomerManagerStart)){
+                TradeCustomerManager__c trade = [select Id,order__c,isHaveLink__c from TradeCustomerManager__c where Id =: parentId];
+                if(trade!=null){
+                    Order order = [select Id,applicationForm__c,ApproveStatus__c from Order where id=:trade.order__c];
+                    if(order !=null){
+                        if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
+                            accach.addError('鍚堝悓宸叉彁浜わ紝鐢宠琛ㄩ檮浠朵笉鍙慨鏀癸紒');
+                            return;
+                        }
+                    }
+                }
+            }
+        }
+    }
+    //鐜嬮箯浼熷垽鏂槸鍚︽槸 璐告槗绠$悊瀹㈡埛鐢宠琛� 涓嬬殑鏂囦欢 濡傛灉鏄�
+    public static void DeleteTradeCustomerManagerFile(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
+        for(Attachment accach : oldList){
+            String parentId = accach.parentId;
+            String tradeCustomerManagerStart = System.label.TradeCustomerManagerStart;
+            if(parentId.startsWith(tradeCustomerManagerStart)){
+                TradeCustomerManager__c trade = [select Id,order__c,isHaveLink__c from TradeCustomerManager__c where Id =: parentId];
+                if(trade!=null){
+                    Order order = [select Id,applicationForm__c,ApproveStatus__c from Order where id=:trade.order__c];
+                    if(order!=null){
+                        if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
+                            accach.addError('鍚堝悓宸叉彁浜わ紝鐢宠琛ㄩ檮浠朵笉鍙垹闄わ紒');
+                            return;
+                        }
+                        if(order!=null &&(accach.Name.startsWith('鍐涗簨')||(accach.Name.startsWith('涓汉淇℃伅') && trade.isHaveLink__c == '鏄�'))){
+                            order.applicationForm__c = false;
+                            update order;
+                        }
+                    }
+                }
+            }
+        }
+    }
+    //鐜嬮箯浼熸柊鍔犲垽鏂�  璐告槗绠$悊瀹㈡埛鐢宠琛� 涓�涓敵璇疯〃涓嬪彧鑳芥湁涓�浠芥枃浠跺悕浠ュ啗浜嬫垨涓汉淇℃伅寮�澶寸殑鏂囦欢锛�
+    public static void UploadTradeCustomerManagerFile(List<Attachment> newList, Map<Id, Attachment> newMap, List<Attachment> oldList, Map<Id, Attachment> oldMap){
+         for(Attachment accach : newList){
+            String parentId = accach.parentId;
+            String tradeCustomerManagerStart = System.label.TradeCustomerManagerStart;
+            if(parentId.startsWith(tradeCustomerManagerStart)){
+                List<Attachment> fileList = [select Id,Name from Attachment where ParentId =:parentId];
+                if(fileList!=null && fileList.size()!=0){
+                    for(Attachment acc : fileList){
+                        if(acc.Name.substring(0,2).equals('鍐涗簨') && accach.Name.startsWith('鍐涗簨')){
+                            accach.addError('涓�涓锤鏄撶鐞嗗鎴风敵璇疯〃涓嬶紝鍙兘鏈変竴浠芥枃浠跺悕浠ュ啗浜嬪紑澶寸殑鏂囦欢锛�');
+                            return;
+                        }
+                        if(acc.Name.startsWith('涓汉淇℃伅') && accach.Name.startsWith('涓汉淇℃伅')){
+                            accach.addError('涓�涓锤鏄撶鐞嗗鎴风敵璇疯〃涓嬶紝鍙兘鏈変竴浠芥枃浠跺悕浠ヤ釜浜哄紑澶寸殑鏂囦欢锛�');
+                            return;
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AttachmentTriggerHandler.cls-meta.xml b/scr/classes/AttachmentTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/AttachmentTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/AttachmentTriggerTest.cls b/scr/classes/AttachmentTriggerTest.cls
new file mode 100644
index 0000000..21503a0
--- /dev/null
+++ b/scr/classes/AttachmentTriggerTest.cls
@@ -0,0 +1,394 @@
+@isTest
+private class AttachmentTriggerTest {
+    static void setupTestData() {
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+    }
+    static testMethod void myTest1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+        insert con;
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        Attachment att = new Attachment(
+            Name = 'ORDER-123456.pdf',
+            parentId = odr.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+
+        Attachment att2 = new Attachment(
+            Name = 'not-ORDER-123456.pdf',
+            parentId = odr.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+
+        delete att;
+    }
+
+     static testMethod void myTest2() {
+        setupTestData();
+        // Implement test code
+        List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        Attachment att = new Attachment(
+            Name = '鍊熺敤鍗忚-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+        Attachment att2 = new Attachment(
+            Name = '瑁呮満纭-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+
+        Attachment att3 = new Attachment(
+            Name = '鏀惰揣纭-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att3;
+        
+        try{
+        Attachment att4 = new Attachment(
+            Name = '鍊熺敤鍗忚-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att4;
+        }catch(Exception ex){
+            try{
+                Attachment att21 = new Attachment(
+                    Name = '瑁呮満纭-123456.pdf',
+                    parentId = loaner.Id,
+                    Body = EncodingUtil.base64Decode('test')
+                );
+                insert att21;
+            }catch(Exception ex1){
+                try{
+                    Attachment att31 = new Attachment(
+                        Name = '鏀惰揣纭-123456.pdf',
+                        parentId = loaner.Id,
+                        Body = EncodingUtil.base64Decode('test')
+                    );
+                    insert att31;
+                }catch(Exception ex2){
+                    return;
+                }
+            } 
+        } 
+     }
+
+
+      static testMethod void myTest3() {
+        setupTestData();
+        // Implement test code
+        List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        Attachment att = new Attachment(
+            Name = '鍊熺敤鍗忚-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+        Attachment att2 = new Attachment(
+            Name = '瑁呮満纭-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+
+        Attachment att3 = new Attachment(
+            Name = '鏀惰揣纭-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att3;
+
+        delete att;
+        delete att2;
+        delete att3;
+    }
+     static testMethod void myTest4() {
+        setupTestData();
+        // Implement test code
+        List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        loaner.HP_Received_Sign_Date__c  = Date.today();
+        loaner.Bollow_Date__c = Date.today();
+        insert loaner;
+        Attachment att = new Attachment(
+            Name = '鍊熺敤鍗忚-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+        Attachment att2 = new Attachment(
+            Name = '瑁呮満纭-123456.pdf',
+            parentId = loaner.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+        try{
+            delete att;
+        }catch(Exception ex){
+            try{
+                delete att2;
+            }catch(Exception ex1){
+                return;
+            } 
+        }
+    }
+    // 涓氬姟娲诲姩 闄勪欢涓婁紶
+    static testMethod void myTest5() {
+
+        TS_Repair__c tsr = new TS_Repair__c();
+        tsr.TSReportDate__c = Date.today();
+        insert tsr; 
+
+        User_FaultInfo__c uf1 = new User_FaultInfo__c();
+        insert uf1;
+        FailureAsset__c fa1 = new FailureAsset__c();
+        fa1.model__c = 'test1';
+        fa1.FAUserFaultInfo__c = uf1.Id;
+        insert fa1;
+        Attachment att3 = new Attachment(
+            Name = 'not-ORDER-123456.pdf',
+            parentId = uf1.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att3;
+        
+        BusinessActivity__c  ba1 = new BusinessActivity__c();
+        ba1.BusinessATS__c = tsr.Id;
+        ba1.User_FaultInfo__c = uf1.Id;
+        insert ba1;
+
+        Attachment att = new Attachment(
+            Name = 'ORDER-123456.pdf',
+            parentId = ba1.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+
+        Attachment att2 = new Attachment(
+            Name = 'not-ORDER-123456.pdf',
+            parentId = ba1.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+
+        
+
+    }
+    static testMethod void myTest6() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+        insert con;
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            customerType__c = 'B'
+        );
+        insert opp;
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            EndUser__c = con.Id
+        );
+        insert odr;
+        TradeCustomerManager__c tra = new TradeCustomerManager__c(
+            OrderIdSave__c = odr.Id,
+            order__c =  odr.Id
+        );
+        insert tra;
+        Attachment att1 = new Attachment(
+            Name = '鍐涗簨.pdf',
+            parentId = tra.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att1;
+        Attachment att2 = new Attachment(
+            Name = '涓汉淇℃伅.pdf',
+            parentId = tra.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+        att1.Name = 'test.pdf';
+        update att1;
+        delete att1;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/AttachmentTriggerTest.cls-meta.xml b/scr/classes/AttachmentTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..b12420e
--- /dev/null
+++ b/scr/classes/AttachmentTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>31.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/BreachRecordBatch.cls b/scr/classes/BreachRecordBatch.cls
new file mode 100644
index 0000000..0e193d5
--- /dev/null
+++ b/scr/classes/BreachRecordBatch.cls
@@ -0,0 +1,451 @@
+global class BreachRecordBatch implements Database.Batchable<sObject>,Database.Stateful {
+	
+	private List<String> idList = null;
+	
+	public List<String> outlaId = new List<String>();
+	public List<String> autolaId = new List<String>();
+	global BreachRecordBatch() {
+		
+	}
+
+	global BreachRecordBatch(List<String> temp) {
+		idList = temp;
+	}
+	
+	global Database.QueryLocator start(Database.BatchableContext BC) {
+		if(idList != null && idList.size() > 0){
+			return Database.getQueryLocator([select id,Receipt_Date__c,Loaner_Express__c,Equipment_Type__c,Automatic_Received_Date__c,loaner_application__c,loaner_application__r.Rental_End_Date__c,
+				                             loaner_application__r.OwnerId,loaner_application__r.Owner.ProfileId,loaner_application__r.Is_Automatic_Received__c,loaner_application__r.Is_time_out__c 
+				                             from loaner_application_detail__c  
+				                             where (loaner_application__r.Rental_End_Date__c <= :Date.today() or Automatic_Received_Date__c <= :Date.today()) 
+				                             //and loaner_application__r.CreatorUserType__c = 'PowerPartner' 
+				                             and RAESD_Status__c in ('宸插嚭搴�','鐢宠鑰呭凡鏀惰揣','鐢宠鑰呭凡瑁呮満纭') and id in :idList ]);
+		}else{
+			return Database.getQueryLocator([select id,Receipt_Date__c,Loaner_Express__c,Equipment_Type__c,Automatic_Received_Date__c,loaner_application__c,loaner_application__r.Rental_End_Date__c,
+				                             loaner_application__r.OwnerId,loaner_application__r.Owner.ProfileId,loaner_application__r.Is_Automatic_Received__c,loaner_application__r.Is_time_out__c 
+				                             from loaner_application_detail__c  
+				                             where ((loaner_application__r.Rental_End_Date__c <= :Date.today() and RAESD_Status__c in ('宸插嚭搴�','鐢宠鑰呭凡鏀惰揣','鐢宠鑰呭凡瑁呮満纭')) 
+				                                   or (Automatic_Received_Date__c <= :Date.today() and RAESD_Status__c = '宸插嚭搴�'))]);
+		}
+	}
+
+   	global void execute(Database.BatchableContext BC, List<sObject> scope) {
+
+   		List<String> passUserId = new List<String>{
+        	'00e0K000001z2Y8',
+        	'00e0K000001l1Dx',
+        	'00e0K000001l1E2',
+        	'00e0K000001l1E7',
+        	'00e28000000YMiL',
+        	'00e28000000YMif',
+        	'00e28000000eN61',
+        	'00e28000000eN64',
+        	'00e28000001wf2h'
+    	};
+
+   		Map<String,loaner_application__c> timeoutMap= new Map<String,loaner_application__c>();
+		Map<String,loaner_application__c> autoMap= new Map<String,loaner_application__c>();
+		
+		Set<loaner_application__c> timeoutSet= new Set<loaner_application__c>();
+		Set<loaner_application__c> autoSet= new Set<loaner_application__c>();
+
+		Set<String> timeoutID = new Set<String>();
+		Set<String> autoID = new Set<String>();
+
+		Set<String> userIdSet = new Set<String>();
+		List<User> userList = new List<User>();
+		Map<String,User> userMap = new Map<String,User>();
+		List<loaner_application_detail__c> ladList = new List<loaner_application_detail__c>();
+     	Set<String> leIdSet = new Set<String>();
+
+		Set<String> laIdSet = new Set<String>();   		
+		Map<String,String> usertypeMap = New Map<String,String>();
+
+		system.debug(scope.size());
+		//鑾峰彇绗﹀悎鏉′欢鐨勬槑缁嗙殑鍊熺敤鍗曞拰鍊熺敤鐗╂祦鍗�.
+		for(sObject temp : scope){
+			
+			loaner_application_detail__c lad = (loaner_application_detail__c) temp;
+			if(lad.loaner_application__r.Owner.ProfileId != null){
+				if(passUserId.contains(String.valueOf(lad.loaner_application__r.Owner.ProfileId).subString(0,15))){
+
+				}else{
+					userIdSet.add(lad.loaner_application__r.OwnerId);
+					usertypeMap.put(lad.loaner_application__r.OwnerId, lad.Equipment_Type__c);
+		         	leIdSet.add(lad.Loaner_Express__c);
+		        }
+		    }
+		}
+
+		//userList = [select id,Automatic_Received_Number__c,Return_Timeout_Number__c from User where id in : userIdSet];
+      	//鏄庣粏
+      	List<Loaner_Express__c> leList = new List<Loaner_Express__c>();
+		for(Loaner_Express__c le : [select id from Loaner_Express__c where id= :leIdSet]){
+        	le.NotReceivingNum__c = 0;
+        	leList.add(le);
+      	}
+		/*for(User temp : userList){
+			
+			userMap.put(temp.id, temp);
+			
+		}*/
+
+		Map<String,loaner_application__c> updatLa = new Map<String,loaner_application__c>();
+		Map<String,loaner_application__c> updatLa1 = new Map<String,loaner_application__c>();
+	
+		
+		//鍒ゆ柇鏄庣粏鏄惁瓒呮湡
+		for(sObject temp : scope){
+			loaner_application_detail__c lad = (loaner_application_detail__c) temp;
+			//濡傛灉鑷姩鏀惰揣鏃ユ湡鏄粖澶╂垨鑰呬粖澶╀箣鍓嶏紝骞朵笖鍊熺敤鍗曟槸鍚﹁嚜鍔ㄦ敹璐ф槸false骞朵笖娌℃湁鏀惰揣鏃ユ湡銆�
+			
+			if(lad.Automatic_Received_Date__c <= Date.today() 
+				&& lad.loaner_application__r.Is_Automatic_Received__c != true 
+				&& lad.Receipt_Date__c == null ){
+				//鍊熺敤鍗�
+				loaner_application__c la = new loaner_application__c();
+				la.id = lad.loaner_application__c;
+				la.OwnerId = lad.loaner_application__r.OwnerId;
+				la.Is_Automatic_Received__c = true;
+				if(lad.loaner_application__r.Owner.ProfileId != null){
+					if(passUserId.contains(String.valueOf(lad.loaner_application__r.Owner.ProfileId).subString(0,15))){
+
+					}else{
+						autoMap.put(la.id, la);
+					}	
+				}
+				lad.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+				lad.Receipt_Status__c= 'OK';
+				lad.Receipt_Date__c = Date.today();
+				ladList.add(lad);
+				laIdSet.add(lad.loaner_application__c);
+				if(!updatLa.keySet().contains(la.id)){
+					updatLa.put(la.Id, la);
+				}
+
+				//updatLa.add(la);
+			}
+			//濡傛灉鍊熷嚭缁撴潫鏃ユ槸浠婂ぉ鎴栬�呬粖澶╀箣鍓嶏紝骞朵笖鏄惁瓒呮湡鏄痜alse
+			if(lad.loaner_application__r.Rental_End_Date__c <= Date.today() 
+				&& lad.loaner_application__r.Is_time_out__c != true ){
+				loaner_application__c la = new loaner_application__c();
+				la.id = lad.loaner_application__c;
+				la.OwnerId = lad.loaner_application__r.OwnerId;
+				la.Is_time_out__c = true;
+				if(!updatLa1.keySet().contains(la.id)){
+					updatLa1.put(la.Id, la);
+				}
+
+				//updatLa1.add(la);
+				if(lad.loaner_application__r.Owner.ProfileId != null){
+					if(passUserId.contains(String.valueOf(lad.loaner_application__r.Owner.ProfileId).subString(0,15))){
+
+					}else{
+						timeoutMap.put(la.id, la);
+					}
+				}
+			}
+		}
+		system.debug(timeoutSet);
+		system.debug(autoSet);
+		autoSet.addAll(autoMap.values());
+		timeoutSet.addAll(timeoutMap.values());
+
+
+		//鑷姩鏀惰揣
+		/*for(sObject temp : scope){
+			loaner_application_detail__c lad = (loaner_application_detail__c) temp;
+
+			if(lad.Automatic_Received_Date__c <= Date.today() && lad.Receipt_Date__c == null){
+				lad.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+				lad.Receipt_Status__c= 'OK';
+				lad.Receipt_Date__c = Date.today();
+				ladList.add(lad);
+				laIdSet.add(lad.loaner_application__c);
+			}
+		}*/
+
+		//List<User> autoUser = new List<User>();
+		List<User> timeoutUser = new List<User>();
+		List<loaner_application__c> autoList = new List<loaner_application__c>();
+		List<loaner_application__c> timeoutList = new List<loaner_application__c>();
+
+		List<User_Violations__c> ulList = [select id,Violations_User__c,Violations_reason__c from User_Violations__c where Is_effective__c = true and Violations_User__c in : userIdSet];
+		Map<String,Integer> uvMap = new Map<String,Integer>();
+		Map<String,Integer> uvMap2 = new Map<String,Integer>();
+
+		//缁熻鐜板湪绯荤粺涓凡鏈夌殑杩濊娆℃暟
+		for(User_Violations__c uv : ulList){
+			/*if(uv.Violations_reason__c == '绯荤粺鑷姩鏀惰揣'){
+				if(uvMap.containsKey(uv.Violations_User__c)){
+					uvMap.put(uv.Violations_User__c, uvMap.get(uv.Violations_User__c)+1);	
+				}else{
+					uvMap.put(uv.Violations_User__c, 1);
+				}
+			}
+			if(uv.Violations_reason__c == '瓒呮湡鏈綊杩�'){
+				if(uvMap2.containsKey(uv.Violations_User__c)){
+					uvMap2.put(uv.Violations_User__c, uvMap2.get(uv.Violations_User__c)+1);	
+				}else{
+					uvMap2.put(uv.Violations_User__c, 1);
+				}
+			}*/
+
+			if(uvMap.containsKey(uv.Violations_User__c)){
+				uvMap.put(uv.Violations_User__c, uvMap.get(uv.Violations_User__c)+1);
+			}else{
+				uvMap.put(uv.Violations_User__c, 1);
+			}
+		}
+
+
+		Map<String,List<User_Violations__c>>  newMap = new Map<String,List<User_Violations__c>>();
+		List<loaner_application__c> laList = new List<loaner_application__c>();
+		system.debug(autoSet);
+		if(autoSet.size()>0){
+			laList =  [select id,Approver__c,loaner_Manager__c,ApproveManager__c from loaner_application__c where id in :autoMap.keySet()];
+			for(loaner_application__c la : autoSet){
+				//User user = userMap.get(la.OwnerId);
+				/*if(user == null){
+					break;
+				}*/
+				//userMap.get(la.OwnerId).Automatic_Received_Number__c = (userMap.get(la.OwnerId).Automatic_Received_Number__c == null? 0 : userMap.get(la.OwnerId).Automatic_Received_Number__c ) + 1;
+				
+				if(autolaId.contains(la.Id)){
+
+				}else{
+					loaner_application__c la1 = new loaner_application__c();
+					for(loaner_application__c la2 : laList){
+						if(la2.Id == la.Id){
+							la1 = la2;
+						}
+					}
+					User_Violations__c uv = new User_Violations__c();
+					uv.Violations_User__c = la.OwnerId;
+					uv.Violations_Loaner__c = la.id;
+					uv.Violations_reason__c = '绯荤粺鑷姩鏀惰揣';
+					uv.ApplyPerson__c = la1.Approver__c;
+					uv.loaner_Manager__c = la1.loaner_Manager__c;
+					uv.ApproveManager__c = la1.ApproveManager__c;
+					if(newMap.containsKey(uv.Violations_User__c)){
+						newMap.get(uv.Violations_User__c).add(uv);
+					}else{
+						List<User_Violations__c> uvlist = new List<User_Violations__c>();
+						uvlist.add(uv);
+						newMap.put(uv.Violations_User__c,uvlist);
+					}
+					autolaId.add(la.Id);
+					//autoUser.add(user);
+				}
+			}
+		}
+
+		Map<String,List<User_Violations__c>>  newMap2 = new Map<String,List<User_Violations__c>>();
+		system.debug(timeoutSet);
+		if(timeoutSet.size()>0){
+			laList =  [select id,Approver__c,loaner_Manager__c,ApproveManager__c from loaner_application__c where id in :timeoutMap.keySet()];
+			for(loaner_application__c la : timeoutSet){
+				//User user = userMap.get(la.OwnerId);
+/*   				if(user == null){
+					break;
+				}*/
+				// user.Return_Timeout_Number__c = (user.Return_Timeout_Number__c == null ? 0 :  user.Return_Timeout_Number__c ) +1;
+				//timeoutUser.add(user);
+				//userMap.put(la.OwnerId,user);
+
+				if(outlaId.contains(la.Id)){
+
+				}else{
+
+					loaner_application__c la1 = new loaner_application__c();
+					for(loaner_application__c la2 : laList){
+						if(la2.Id == la.Id){
+							la1 = la2;
+						}
+					}
+
+					User_Violations__c uv = new User_Violations__c();
+					uv.Violations_User__c = la.OwnerId;
+					uv.Violations_Loaner__c = la.id;
+					uv.Violations_reason__c = '瓒呮湡鏈綊杩�';
+					uv.ApplyPerson__c = la1.Approver__c;
+					uv.loaner_Manager__c = la1.loaner_Manager__c;
+					uv.ApproveManager__c = la1.ApproveManager__c;
+
+					/*if(newMap2.containsKey(uv.Violations_User__c)){
+						newMap2.get(uv.Violations_User__c).add(uv);
+					}else{
+						List<User_Violations__c> uvlist = new List<User_Violations__c>();
+						uvlist.add(uv);
+						newMap2.put(uv.Violations_User__c,uvlist);
+					}*/
+					if(newMap.containsKey(uv.Violations_User__c)){
+						newMap.get(uv.Violations_User__c).add(uv);
+					}else{
+						List<User_Violations__c> uvlist = new List<User_Violations__c>();
+						uvlist.add(uv);
+						newMap.put(uv.Violations_User__c,uvlist);
+					}
+					outlaId.add(la.Id);
+				}
+			}
+		}
+
+		system.debug(newMap.values());
+		system.debug(newMap2.values());
+
+		List<User_Violations__c> updateList = new List<User_Violations__c>();
+		for(String str : newMap.keySet()){
+			if(usertypeMap.get(str) == 'NDT' ||usertypeMap.get(str) == 'ANI'){
+				if(uvMap.containsKey(str)){
+					if(newMap.containsKey(str)){
+						if((uvMap.get(str) + newMap.get(str).size()) >= 1 && uvMap.get(str) < 1){
+							newMap.get(str)[0].Is_locking__c = true;
+							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
+						}
+					}
+				}else{
+					if(newMap.containsKey(str)){
+						if(newMap.get(str).size() >= 1 ){
+							newMap.get(str)[0].Is_locking__c = true;	
+							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
+						}
+					}
+				}
+			}else{
+				if(uvMap.containsKey(str)){
+					if(newMap.containsKey(str)){
+						if((uvMap.get(str) + newMap.get(str).size()) >= 2 && uvMap.get(str) < 2){
+							newMap.get(str)[0].Is_locking__c = true;
+							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
+						}
+					}
+				}else{
+					if(newMap.containsKey(str)){
+						if(newMap.get(str).size() >= 2 ){
+							newMap.get(str)[0].Is_locking__c = true;	
+							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
+						}
+					}
+				}
+			}
+			updateList.addAll(newMap.get(str));
+		}
+
+		/*for(String str : newMap2.keySet()){
+			if(uvMap2.containsKey(str)){
+				if(newMap2.containsKey(str)){
+					if((uvMap2.get(str) + newMap2.get(str).size()) == 2 && uvMap2.get(str) != 2){
+						newMap2.get(str)[0].Is_locking__c = true;
+						newMap2.get(str)[0].Locking_Start_Date__c = Date.today();
+					}
+				}
+			}else{
+				if(newMap2.containsKey(str)){
+					if(newMap2.get(str).size() >= 2 ){
+						newMap2.get(str)[0].Is_locking__c = true;	
+						newMap2.get(str)[0].Locking_Start_Date__c = Date.today();
+					}
+				}
+			}
+			updateList.addAll(newMap2.get(str));
+		}*/
+
+		system.debug('updateList:' + updateList);
+		insert updateList;
+   		
+		//update userMap.values();
+
+		if(ladList.size()>0){
+			update ladList;
+		}
+      	if(leList.size()>0){
+         	update leList;
+      	}
+      	if(updatLa.size()>0){
+      		update updatLa.values();
+      	}
+      	if(updatLa1.size()>0){
+      		update updatLa1.values();
+      	}
+
+		if(laIdSet.size()>0){
+			laList = [select id,Count_SendOut__c,Count_ApplicantReceived__c from loaner_application__c where id = :laIdSet and Status__c = '鍏ㄩ儴鍙戣揣'];
+			for(loaner_application__c la : laList){
+				if(la.Count_SendOut__c == la.Count_ApplicantReceived__c){
+					la.Status__c = '鐢宠鑰呭凡鏀惰揣';
+				}
+			}
+			update laList;
+		}
+
+
+
+
+	
+	}
+	
+	global void finish(Database.BatchableContext BC) {
+		List<User_Violations__c> uvList = [select id,Violations_User__c,Is_locking__c,Violations_reason__c from User_Violations__c where Is_effective__c = true order by Violations_User__c];
+		Map<String,Integer> userMap = new Map<String,Integer>();
+		Map<String,Integer> userMap2 = new Map<String,Integer>();
+		
+		Map<String,String> user_vMap = new Map<String,String>();
+		
+		for(User_Violations__c uv : uvList){
+			if(uv.Violations_reason__c == '瓒呮湡鏈綊杩�'){
+				if(userMap.containsKey(uv.Violations_User__c)){
+					userMap.put(uv.Violations_User__c, userMap.get(uv.Violations_User__c)+1);
+				}else{
+					userMap.put(uv.Violations_User__c, 1);
+				}
+			}else if(uv.Violations_reason__c == '绯荤粺鑷姩鏀惰揣'){
+				if(userMap2.containsKey(uv.Violations_User__c)){
+					userMap2.put(uv.Violations_User__c, userMap2.get(uv.Violations_User__c)+1);
+				}else{
+					userMap2.put(uv.Violations_User__c, 1);
+				}
+			}
+			if(uv.Is_locking__c == true){
+				user_vMap.put(uv.Violations_User__c,uv.Id);
+			}
+		}
+		system.debug(user_vMap);
+		Map<String,User> userList = new Map<String,User>();
+		
+		for(String userId : userMap.keySet()){
+			User user = new User();
+			user.Id = userId;
+			user.Return_Timeout_Number__c = userMap.get(userId);
+			if(user_vMap.containsKey(userId)){
+				user.ViolationsID__c = user_vMap.get(userId);
+			}
+			userList.put(user.Id, user);
+		}
+
+		for(String userId : userMap2.keySet()){
+			User user = new User();
+			if(userList.containsKey(userId)){
+				user = userList.get(userId);
+				user.Automatic_Received_Number__c = userMap2.get(userId);
+			}else{
+				user.Id = userId;
+				user.Automatic_Received_Number__c = userMap2.get(userId);
+			}
+
+			if(user_vMap.containsKey(userId)){
+				user.ViolationsID__c = user_vMap.get(userId);
+			}
+			userList.put(user.Id, user);
+		}
+
+
+		system.debug(userList);
+		List<User> updateList = userList.values();
+		update updateList;
+
+	}
+
+
+	
+}
\ No newline at end of file
diff --git a/scr/classes/BreachRecordBatch.cls-meta.xml b/scr/classes/BreachRecordBatch.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/BreachRecordBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/BreachRecordBatchTest.cls b/scr/classes/BreachRecordBatchTest.cls
new file mode 100644
index 0000000..d0203a0
--- /dev/null
+++ b/scr/classes/BreachRecordBatchTest.cls
@@ -0,0 +1,177 @@
+@isTest
+private class BreachRecordBatchTest {
+	
+	@isTest static void test_method_one() {
+		OlympusCalendar__c ocq  = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c ocw  = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oce  = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4r = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5q = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6q = new OlympusCalendar__c(Date__c = Date.today().addDays(-6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c ocww = new OlympusCalendar__c(Date__c = Date.today().addDays(-7), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c ocwww= new OlympusCalendar__c(Date__c = Date.today().addDays(-8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c ocew = new OlympusCalendar__c(Date__c = Date.today().addDays(-9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4rw = new OlympusCalendar__c(Date__c = Date.today().addDays(-10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5qw = new OlympusCalendar__c(Date__c = Date.today().addDays(-11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6qw = new OlympusCalendar__c(Date__c = Date.today().addDays(-12), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,ocq,ocw,oce,oc4r,oc5q,oc6q, ocww,ocwww,ocew,oc4rw,oc5qw,oc6qw};
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+       	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        //List<RecordType> rectus = [select Id from RecordType where IsActive = true and SobjectType = 'User' and Name = 'Customer IE'];
+       
+       User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'test@test.com';
+        user.Username = 'test111@test222.com';
+        user.CommunityNickname = 'test';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+
+
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner.Request_return_Date__c = Date.today().addDays(10);
+        loaner.Status__c = '閮ㄥ垎鍙戣揣';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        loaner.Rental_End_Date__c = Date.today().addDays(-2);
+        loaner.OwnerId = user.Id;
+
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+
+        loaner_application__c loaner1 = new loaner_application__c();
+        loaner1.Name = 'TEST';
+        loaner1.RecordTypeId = rectLo[0].id;
+        loaner1.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner1.DEMO_PURPOSE__C = '婕旂ず';
+        loaner1.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner1.Request_return_Date__c = Date.today().addDays(10);
+        loaner1.Status__c = '閮ㄥ垎鍙戣揣';
+        loaner1.Return_Track_Company__c = '鐗╂祦鍏徃';
+        loaner1.Rental_End_Date__c = Date.today().addDays(+3);
+        loaner1.OwnerId = user.Id;
+
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner1;
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+		//detail.Shipment_Request_Date__c = Date.today();
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner1.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.Automatic_Received_Date__c =  Date.today().addDays(-1);
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        Loaner_Express__c le = new Loaner_Express__c(
+        	Name = 'test01',
+        	loaner_application__c = loaner.Id
+        	);
+
+        insert le;
+        In_detail[2].Loaner_Express__c = le.Id;
+       	le.Consignor_LogisticsNumber__c ='test123123';
+        le.Consignor_LogisticsCompany__c = 'testCompany';
+        le.Shipment_Request_Date__c = Date.today();       
+        le.NotReceivingNum__c = 1;
+        update le;
+        update In_detail;
+
+        le.Consignor_LogisticsNumber__c = '3232323';
+        update le;
+
+         Loaner_Express__c le1 = new Loaner_Express__c(
+        	Name = 'test01',
+        	loaner_application__c = loaner.Id
+        	);
+
+        insert le1;
+        //BreachRecordBatch.come();
+        List<String> idList = new List<String>();
+        for(loaner_application_detail__c lad : In_detail){
+            idList.add(lad.id);
+        }
+
+        System.debug(idList.size()+'1111111111111111111111111');
+        Database.executeBatch(new BreachRecordBatch(idList), 20);	
+
+	}
+	
+	
+}
\ No newline at end of file
diff --git a/scr/classes/BreachRecordBatchTest.cls-meta.xml b/scr/classes/BreachRecordBatchTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/BreachRecordBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/BreachRecordSchedulable.cls b/scr/classes/BreachRecordSchedulable.cls
new file mode 100644
index 0000000..cd144d9
--- /dev/null
+++ b/scr/classes/BreachRecordSchedulable.cls
@@ -0,0 +1,7 @@
+global class BreachRecordSchedulable implements Schedulable {
+	global void execute(SchedulableContext sc) {
+		//MyBatchClass b = new MyBatchClass();
+		//database.executebatch(b);
+		 Id execBTId = Database.executeBatch(new BreachRecordBatch(), 200);
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/BreachRecordSchedulable.cls-meta.xml b/scr/classes/BreachRecordSchedulable.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/BreachRecordSchedulable.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/BreachRecordSchedulableTest.cls b/scr/classes/BreachRecordSchedulableTest.cls
new file mode 100644
index 0000000..2f62832
--- /dev/null
+++ b/scr/classes/BreachRecordSchedulableTest.cls
@@ -0,0 +1,23 @@
+@isTest
+private class BreachRecordSchedulableTest {
+	
+	 static  testMethod void testExecute() {
+		 // This test runs a scheduled job at midnight Sept. 3rd. 2022
+        String CRON_EXP = '0 0 0 3 9 ? 2032';
+
+        System.Test.startTest();
+        // Schedule the test job
+        String jobId = system.schedule('BreachRecordSchedulableTest', CRON_EXP, new BreachRecordSchedulable());
+        // Get the information from the CronTrigger API object
+        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
+        // Verify the expressions are the same
+        System.assertEquals(CRON_EXP, ct.CronExpression);
+        // Verify the job has not run
+        System.assertEquals(0, ct.TimesTriggered);
+        // Verify the next time the job will run
+        System.assertEquals('2032-09-03 00:00:00', String.valueOf(ct.NextFireTime));
+	}
+	
+
+	
+}
\ No newline at end of file
diff --git a/scr/classes/BreachRecordSchedulableTest.cls-meta.xml b/scr/classes/BreachRecordSchedulableTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/BreachRecordSchedulableTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/BusinessActivityHandler.cls b/scr/classes/BusinessActivityHandler.cls
new file mode 100644
index 0000000..7bc6c7e
--- /dev/null
+++ b/scr/classes/BusinessActivityHandler.cls
@@ -0,0 +1,302 @@
+public without sharing class BusinessActivityHandler {
+
+    public static void ValidDaysBetweenTwoWorkingDays(List<BusinessActivity__c> newList, Map<Id, BusinessActivity__c> newMap, List<BusinessActivity__c> oldList, Map<Id, BusinessActivity__c> oldMap) {
+
+        Map<String, Date> dateRangeMap = new Map<String, Date>();
+        // 鏄惁闇�瑕佸垵濮嬪寲涓�涓棩鏈熷 1970-01-01
+        Date bigDate = Date.today();//Date.newInstance(1970,1, 1);
+        Date smaDate = Date.today();//Date.newInstance(4000, 12, 31);
+        dateRangeMap.put('BigDate', bigDate);
+        dateRangeMap.put('SmaDate', smaDate);
+        Map<String, User_FaultInfo__c> updateUserFaultInfoMap = new Map<String, User_FaultInfo__c>();
+        for (BusinessActivity__c ba : newList) {
+
+            // 鎶ュ憡鏃ユ湡(鍚庡彴鐢�)
+            if (ba.AgreeReportDate__c != null) {
+
+                if (ba.AgreeReportDate__c > dateRangeMap.get('BigDate')) {
+                    dateRangeMap.put('BigDate', ba.AgreeReportDate__c);
+                }
+
+                if (ba.AgreeReportDate__c  < dateRangeMap.get('SmaDate')) {
+                    dateRangeMap.put('SmaDate', ba.AgreeReportDate__c );
+                }
+            }
+
+
+            //  瑕佹眰鏈嶅姟鏃ユ湡
+            if (ba.BusinessADateRequest__c != null) {
+
+                if (ba.BusinessADateRequest__c > dateRangeMap.get('BigDate')) {
+                    dateRangeMap.put('BigDate', ba.BusinessADateRequest__c);
+                }
+
+                if (ba.BusinessADateRequest__c  < dateRangeMap.get('SmaDate')) {
+                    dateRangeMap.put('SmaDate', ba.BusinessADateRequest__c );
+                }
+
+            }
+            //  妗堜欢瀹屾垚鏃�
+            if (ba.BusinessACompletionDate__c != null) {
+                if (ba.BusinessACompletionDate__c > dateRangeMap.get('BigDate')) {
+                    dateRangeMap.put('BigDate', ba.BusinessACompletionDate__c);
+                }
+
+                if (ba.BusinessACompletionDate__c  < dateRangeMap.get('SmaDate')) {
+                    dateRangeMap.put('SmaDate', ba.BusinessACompletionDate__c );
+                }
+            }
+            // 鍚屾剰鎶ヤ环鏃ユ湡
+            if (ba.BusinessADateApproval__c != null) {
+                if (ba.BusinessADateApproval__c > dateRangeMap.get('BigDate')) {
+                    dateRangeMap.put('BigDate', ba.BusinessADateApproval__c);
+                }
+
+                if (ba.BusinessADateApproval__c  < dateRangeMap.get('SmaDate')) {
+                    dateRangeMap.put('SmaDate', ba.BusinessADateApproval__c );
+                }
+            }
+            // 鎶ヤ环鏃ユ湡
+            if (ba.BusinessADateQuotation__c != null) {
+                if (ba.BusinessADateQuotation__c > dateRangeMap.get('BigDate')) {
+                    dateRangeMap.put('BigDate', ba.BusinessADateQuotation__c);
+                }
+
+                if (ba.BusinessADateQuotation__c  < dateRangeMap.get('SmaDate')) {
+                    dateRangeMap.put('SmaDate', ba.BusinessADateQuotation__c );
+                }
+            }
+            // 鎶ヤ慨鏃ユ湡
+            if (ba.BusinessARepairDate__c != null) {
+                if (ba.BusinessARepairDate__c > dateRangeMap.get('BigDate')) {
+                    dateRangeMap.put('BigDate', ba.BusinessARepairDate__c);
+                }
+
+                if (ba.BusinessARepairDate__c  < dateRangeMap.get('SmaDate')) {
+                    dateRangeMap.put('SmaDate', ba.BusinessARepairDate__c );
+                }
+            }
+
+        }
+        if (dateRangeMap.size() > 0) {
+            if (dateRangeMap.size() > 0) {
+                System.debug('SmaDate--->' + dateRangeMap.get('SmaDate'));
+                System.debug('BigDate--->' + dateRangeMap.get('BigDate'));
+                Map<String, OlympusCalendar__c> olyCalendarMap = calendarUtil.getCalendarMap(dateRangeMap.get('SmaDate').addDays(-40), dateRangeMap.get('BigDate').addDays(15));
+                System.debug(olyCalendarMap);
+                for (BusinessActivity__c ba : newList) {
+                    // 娲鹃仯鍛ㄦ湡
+                    if ( ba.BusinessASegment__c == 'IE' || ba.BusinessASegment__c == 'LS') {
+
+                        if (ba.BusinessADateRequest__c == null || //[瑕佹眰鏈嶅姟鏃ユ湡]=绌�
+                                ba.BusinessAServicePlace__c == '绔欏唴' || //[鏈嶅姟鍦烘墍]=鈥濈珯鍐呪��
+                                ba.BusinessAServiceCategory__c == 'Sevice' || //[鏈嶅姟鑼冪暣]="service"
+                                ba.BusinessAServiceCategory__c == 'Association' ) {// [鏈嶅姟鑼冪暣]="Association"
+                            // 娲鹃仯鍛ㄦ湡 缃┖
+                            ba.BusinessADispatchTime__c = null;
+                        } else {
+                            if (ba.BusinessAServiceCategory__c == 'Repair' && //[鏈嶅姟鑼冪暣]="Repair"
+                                    ba.BusinessAServicePlace__c == '鐜板満') {//[鏈嶅姟鍦烘墍]=鈥滅幇鍦衡��
+                                Date beginDate = null;
+                                Date endDate = null ;
+                                if (ba.AgreeReportDate__c >= ba.BusinessADateRequest__c) {
+                                    beginDate = ba.BusinessADateRequest__c;
+                                    endDate = ba.AgreeReportDate__c;
+                                } else {
+                                    beginDate = ba.AgreeReportDate__c;
+                                    endDate = ba.BusinessADateRequest__c;
+                                }
+                                Integer count = calendarUtil.getNumfromCalendarMap(olyCalendarMap, beginDate, endDate);
+                                if (count < 1) {
+                                    count = 0 ;
+                                } else if (count > 1) {
+                                    count = count - 1;
+                                }
+                                ba.BusinessADispatchTime__c = count;
+                                // [鎶ュ憡鏃ユ湡]- [瑕佹眰鏈嶅姟鏃ユ湡] 鍒ゆ柇鍝釜鏃ユ湡灏�
+                            }
+
+                        }
+                    } else {
+                        // RVI/NDT涓嶉渶瑕佽绠楁淳閬e懆鏈� 鍥犳鐩存帴缃┖
+                        ba.BusinessADispatchTime__c = null;
+                    }
+
+                    // 缁翠慨鍛ㄦ湡
+                    if (ba.BusinessACompletionDate__c == null || // [妗堜欢瀹屾垚鏃=绌�
+                            ba.BusinessAServiceCategory__c == 'Sevice' || //[鏈嶅姟鑼冪暣]="service"
+                            ba.BusinessAServiceCategory__c == 'Association') {//[鏈嶅姟鑼冪暣]="Association"
+                        // 缁翠慨鍛ㄦ湡 = null
+                        ba.BusinessAMaintainTime__c = null;
+                    } else {
+                        if (ba.BusinessAServiceCategory__c == 'Repair') {//[鏈嶅姟鑼冪暣]="Repair"
+                            if (ba.BusinessANatureService__c == '鏈夊伩' ) {//[鏈嶅姟鎬ц川]="鏈夊伩"
+                                if (ba.BusinessADateApproval__c == null) {//[鍚屾剰鎶ヤ环鏃=绌�
+                                    // 缁翠慨鍛ㄦ湡 = null
+                                    ba.BusinessAMaintainTime__c = null;
+                                    continue;
+                                } else  {
+                                    Date beginDate = ba.BusinessADateApproval__c; //鍚屾剰鎶ヤ环鏃ユ湡
+                                    Date endDate = ba.BusinessACompletionDate__c ;//妗堜欢瀹屾垚鏃�
+                                    Integer count = calendarUtil.getNumfromCalendarMap(olyCalendarMap, beginDate, endDate);
+                                    if (count < 1) {
+                                        count = 0 ;
+                                    } else if (count > 1) {
+                                        count = count - 1;
+                                    }
+                                    ba.BusinessAMaintainTime__c = count;
+                                    // networkday [妗堜欢瀹屾垚鏃(澶�)- [鍚屾剰鎶ヤ环鏃ユ湡](灏�)
+                                }
+
+                            } else if (ba.BusinessANatureService__c == '鏃犲伩' ) {
+                                Date beginDate = ba.AgreeReportDate__c;//鎶ュ憡鏃ユ湡
+                                Date endDate = ba.BusinessACompletionDate__c ;//妗堜欢瀹屾垚鏃�
+                                Integer count = calendarUtil.getNumfromCalendarMap(olyCalendarMap, beginDate, endDate);
+                                if (count < 1) {
+                                    count = 0 ;
+                                } else if (count > 1) {
+                                    count = count - 1;
+                                }
+                                ba.BusinessAMaintainTime__c = count;
+                                // networkday [妗堜欢瀹屾垚鏃- [鎶ュ憡鏃ユ湡]
+                            }
+                        }
+                    }
+                    // 鍋滄満鏃堕棿
+                    if ( ba.BusinessACompletionDate__c == null || //[妗堜欢瀹屾垚鏃=绌�
+                            ba.BusinessARepairDate__c == null || //[鎶ヤ慨鏃ユ湡]=绌�
+                            ba.BusinessAServiceCategory__c == 'Sevice'  || //[鏈嶅姟鑼冪暣]="Sevice"
+                            ba.BusinessAServiceCategory__c == 'Association' ) {//[鏈嶅姟鑼冪暣]="Association"
+                        // 鍋滄満鏃堕棿 = null
+                        ba.BusinessADowntime__c = null ;
+                    } else {
+                        Date beginDate1 = ba.BusinessARepairDate__c;//鎶ヤ慨鏃ユ湡
+                        Date endDate1 = ba.BusinessACompletionDate__c ;//妗堜欢瀹屾垚鏃�
+                        Integer count1 = calendarUtil.getNumfromCalendarMap(olyCalendarMap, beginDate1, endDate1);
+                        if (ba.BusinessAServiceCategory__c == 'Repair') {
+                            if (ba.BusinessANatureService__c == '鏈夊伩' ) {
+                                if (ba.BusinessADateQuotation__c == null || //鎶ヤ环鏃ユ湡
+                                        ba.BusinessADateApproval__c == null) { //鍚屾剰鎶ヤ环鏃ユ湡
+
+                                    ba.BusinessADowntime__c = null;
+                                    continue;
+                                }
+                                Date beginDate2 = ba.BusinessADateQuotation__c;//鎶ヤ环鏃ユ湡
+                                Date endDate2 = ba.BusinessADateApproval__c ;//鍚屾剰鎶ヤ环鏃ユ湡
+                                Integer count2 = calendarUtil.getNumfromCalendarMap(olyCalendarMap, beginDate2, endDate2);
+                                // networkday [妗堜欢瀹屾垚鏃- [鎶ヤ慨鏃ユ湡]-networkday [鍚屾剰鎶ヤ环鏃ユ湡]- [鎶ヤ环鏃ユ湡]
+                                if (count1 - count2 < 1) {
+                                    ba.BusinessADowntime__c = 0;
+                                } else {
+                                    ba.BusinessADowntime__c = count1 - count2 - 1;
+                                }
+
+                            } else if (ba.BusinessANatureService__c == '鏃犲伩' ) {
+                                // networkday [妗堜欢瀹屾垚鏃- [鎶ヤ慨鏃ユ湡]
+
+                                if (count1 < 1) {
+                                    count1 = 0 ;
+                                } else {
+                                    count1 = count1 - 1;
+                                }
+                                ba.BusinessADowntime__c = count1;
+                            }
+                        }
+                    }
+                    if (String.isNotBlank(ba.User_FaultInfo__c) && ba.BusinessAFirstSubmission__c != null) {
+                        User_FaultInfo__c updateUserFaultInfo = new User_FaultInfo__c();
+                        updateUserFaultInfo.Id = ba.User_FaultInfo__c;
+                        updateUserFaultInfo.UserFaultInfoDispatchTime__c = ba.BusinessADispatchTime__c ; //娲鹃仯鍛ㄦ湡
+                        updateUserFaultInfo.UserFaultInfoMaintainTime__c = ba.BusinessAMaintainTime__c;//缁翠慨鍛ㄦ湡
+                        updateUserFaultInfo.UserFaultInfoDowntime__c = ba.BusinessADowntime__c;//鍋滄満鏃堕棿
+                        updateUserFaultInfoMap.put(ba.User_FaultInfo__c, updateUserFaultInfo);
+                    }
+                }
+
+                if (updateUserFaultInfoMap != null && updateUserFaultInfoMap.size() > 0) {
+                    update updateUserFaultInfoMap.values();
+                }
+            }
+        }
+
+
+    }
+    // 姹囨�籘S鏃ユ姤鍏宠仈鐨勪笟鍔℃椿鍔ㄧ殑绠$悊缂栫爜
+    public static void TSRepairManagementCode(List<BusinessActivity__c> newList, Map<Id, BusinessActivity__c> newMap, List<BusinessActivity__c> oldList, Map<Id, BusinessActivity__c> oldMap) {
+        Map<String, String> tSRepairIdMap = new Map<String, String>();
+        
+        if (Trigger.isDelete) {
+            // 寰呭垹闄ょ殑涓氬姟娲诲姩
+            Map<String, String> pendingDeleteMap = new  Map<String, String>();
+
+            for (BusinessActivity__c ba : oldList) {
+                // 鑾峰彇涓氬姟娲诲姩鐨凾S鏃ユ姤
+                if (String.isNotBlank(ba.BusinessATS__c)) {
+                    tSRepairIdMap.put(ba.BusinessATS__c, ba.BusinessATS__c);
+                    pendingDeleteMap.put(ba.Id, ba.FindManagementCode__c);
+                }
+            }
+
+            if (tSRepairIdMap != null && tSRepairIdMap.size() > 0) {
+                updateTSRepair(tSRepairIdMap,pendingDeleteMap);
+            }
+        } else if (Trigger.isInsert || Trigger.isUpdate) {
+            // Trigger.isInsert 涓氬姟娲诲姩 閫夋嫨 宸叉湁鐨勭敤鎴�/鏁呴殰淇℃伅锛屽皢绠$悊缂栫爜姹囨��
+            for (BusinessActivity__c ba : newList) {
+                // 鑾峰彇涓氬姟娲诲姩鐨凾S鏃ユ姤
+                if (String.isNotBlank(ba.BusinessATS__c) && String.isNotBlank(ba.FindManagementCode__c)) {
+                    tSRepairIdMap.put(ba.BusinessATS__c, ba.BusinessATS__c);
+                }
+            }
+
+            if (tSRepairIdMap != null && tSRepairIdMap.size() > 0) {
+                Map<String, String> pendingDeleteMap = new  Map<String, String>();
+                updateTSRepair(tSRepairIdMap,pendingDeleteMap);
+            }
+        }
+    }
+
+    public static void updateTSRepair(Map<String, String> tSRepairIdMap,Map<String, String> pendingDeleteMap) {
+        List<BusinessActivity__c> getBusinessActivity = new List<BusinessActivity__c>();
+        // 鏌ユ壘涓氬姟娲诲姩
+        getBusinessActivity = [select Id, Name, ManagementCode__c, FindManagementCode__c, BusinessATS__c,TSRepairManagementCode__c from BusinessActivity__c where BusinessATS__c In:tSRepairIdMap.keySet() order by Id];
+        Map<String, String> updateTSRepairMap = new Map<String, String>();
+        for (BusinessActivity__c ba : getBusinessActivity) {
+            // 鍒ゆ柇鏄惁鍦ㄥ緟鍒犻櫎鐨凪ap涓紝涓嶅湪 灏� 绠$悊缂栫爜姹囨��
+            if (!pendingDeleteMap.containsKey(ba.Id)) {
+                if (String.isNotBlank(ba.FindManagementCode__c)) {
+                    String managementCode = ba.FindManagementCode__c;
+                    if (updateTSRepairMap.containsKey(ba.BusinessATS__c)) {
+                        managementCode = updateTSRepairMap.get(ba.BusinessATS__c);
+                        managementCode += ';' + ba.FindManagementCode__c;
+
+                    }
+                    updateTSRepairMap.put(ba.BusinessATS__c, managementCode);
+                }
+                
+            } else {
+                // 寰呭垹闄ょ殑涓氬姟娲诲姩鐨勭鐞嗙紪鐮佷笌 TS鏃ユ姤 姹囨�荤殑绠$悊缂栫爜 鐩稿悓 锛屾竻绌� TS鏃ユ姤鐨� 绠$悊缂栫爜
+                if (ba.FindManagementCode__c == ba.TSRepairManagementCode__c) {
+                    updateTSRepairMap.put(ba.BusinessATS__c, '');
+                }
+            }
+        }
+
+        if (updateTSRepairMap != null && updateTSRepairMap.size() > 0) {
+
+            List<TS_Repair__c> updateTSRepairList = new List<TS_Repair__c>();
+            for (String tSRepairId : updateTSRepairMap.keySet() ) {
+                TS_Repair__c tSRepair = new TS_Repair__c();
+                tSRepair.Id = tSRepairId;
+                tSRepair.TSRepairManagementCode__c = updateTSRepairMap.get(tSRepairId);
+                updateTSRepairList.add(tSRepair);
+            }
+
+            if (updateTSRepairList.size() > 0) {
+
+                update updateTSRepairList;
+            }
+
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/BusinessActivityHandler.cls-meta.xml b/scr/classes/BusinessActivityHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/BusinessActivityHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/BusinessActivityHandlerTest.cls b/scr/classes/BusinessActivityHandlerTest.cls
new file mode 100644
index 0000000..3930c61
--- /dev/null
+++ b/scr/classes/BusinessActivityHandlerTest.cls
@@ -0,0 +1,140 @@
+@isTest
+private class BusinessActivityHandlerTest {
+    public static TS_Repair__c tsr;
+    public static TS_Repair__c tsr2;
+    public static BusinessActivity__c ba1;
+    public static BusinessActivity__c ba2;
+    public static BusinessActivity__c ba3;
+    public static BusinessActivity__c ba4;
+
+    public static User_FaultInfo__c uf1;
+    public static User_FaultInfo__c uf2;
+    public static User_FaultInfo__c uf3;
+
+    public static FailureAsset__c fa1;
+    public static FailureAsset__c fa2;
+    public static FailureAsset__c fa3;
+    static void basicData() {
+
+        tsr = new TS_Repair__c();
+        tsr.TSReportDate__c = Date.today();
+        tsr.TSRepairManagementCode__c = 'TestName';
+        insert tsr;    
+        tsr2 = new TS_Repair__c();
+        tsr2.TSReportDate__c = Date.today();
+        insert tsr2;
+
+        uf1 = new User_FaultInfo__c();
+        insert uf1;
+        fa1 = new FailureAsset__c();
+        fa1.model__c = 'test1';
+        fa1.FAUserFaultInfo__c = uf1.Id;
+        insert fa1;
+        ba1 = new BusinessActivity__c();
+        ba1.BusinessATS__c = tsr.Id;
+        ba1.workingHours__c = 2;
+        ba1.BusinessAApprovalOpinion__c = '鍚屾剰';
+        ba1.User_FaultInfo__c = uf1.Id;
+        ba1.AgreeReportDate__c = Date.today().addDays(-2);//鎶ュ憡鏃ユ湡(鍚庡彴鐢�)
+        ba1.BusinessADateRequest__c = Date.today().addDays(-3);//瑕佹眰鏈嶅姟鏃ユ湡
+        ba1.BusinessACompletionDate__c = Date.today().addDays(-2);//妗堜欢瀹屾垚鏃�
+        ba1.BusinessADateApproval__c= Date.today().addDays(-2);//鍚屾剰鎶ヤ环鏃ユ湡
+        ba1.BusinessADateQuotation__c= Date.today().addDays(-2);// 鎶ヤ环鏃ユ湡
+        ba1.BusinessARepairDate__c= Date.today().addDays(-2);//鎶ヤ慨鏃ユ湡
+        ba1.BusinessASegment__c = 'LS';
+        ba1.BusinessAServicePlace__c = '鐜板満';
+        ba1.serviceType__c = '纭欢淇悊';
+        ba1.BusinessAServiceCategory__c = 'Repair';
+        
+        ba1.BusinessANatureService__c = '鏈夊伩';
+        ba1.BusinessAFirstSubmission__c = Datetime.now();
+        insert ba1;
+
+        ba4 = new BusinessActivity__c();
+        ba4.BusinessATS__c = tsr.Id;
+        ba4.workingHours__c = 7;
+        ba4.BusinessAApprovalOpinion__c = '';
+        ba4.User_FaultInfo__c = uf1.Id;
+
+        ba4.AgreeReportDate__c = Date.today().addDays(1);//鎶ュ憡鏃ユ湡(鍚庡彴鐢�)
+        ba4.BusinessADateRequest__c = Date.today().addDays(2);//瑕佹眰鏈嶅姟鏃ユ湡
+        ba4.BusinessACompletionDate__c = Date.today().addDays(1);//妗堜欢瀹屾垚鏃�
+        ba4.BusinessADateApproval__c= Date.today().addDays(4);//鍚屾剰鎶ヤ环鏃ユ湡
+        ba4.BusinessADateQuotation__c= Date.today().addDays(1);// 鎶ヤ环鏃ユ湡
+        ba4.BusinessARepairDate__c= Date.today().addDays(-3);//鎶ヤ慨鏃ユ湡
+        ba4.BusinessASegment__c = 'LS';
+        ba4.BusinessAServicePlace__c = '鐜板満';
+        ba4.serviceType__c = '纭欢淇悊';
+        ba4.BusinessAServiceCategory__c = 'Repair';
+        
+        ba4.BusinessANatureService__c = '鏃犲伩';
+        ba4.BusinessAFirstSubmission__c = Datetime.now();
+        insert ba4;
+
+
+        BusinessActivity__c ba5 = new BusinessActivity__c();
+        ba5.FindManagementCode__c = 'TestName';
+        ba5.BusinessATS__c = tsr.Id;
+        ba5.workingHours__c = 7;
+        ba5.BusinessAApprovalOpinion__c = '';
+        ba5.User_FaultInfo__c = uf1.Id;
+        ba5.BusinessASegment__c = 'RVI';
+        ba5.serviceType__c = '浜у搧瀹夎';
+        ba5.BusinessAServiceCategory__c = 'Sevice';
+
+        insert ba5;
+        update ba5;
+        BusinessActivity__c ba6 =  ba5.clone();
+        ba6.BusinessASegment__c = 'LS';
+        ba6.BusinessAServicePlace__c = '鐜板満';
+        ba6.serviceType__c = '纭欢淇悊';
+        ba6.BusinessAServiceCategory__c = 'Repair';
+        
+        ba6.BusinessANatureService__c = '鏈夊伩';
+        insert ba6;
+
+        delete ba6;
+        // uf2 = new User_FaultInfo__c();
+        // insert uf2;
+        // fa2 = new FailureAsset__c();
+        // fa2.model__c = 'test2';
+        // fa2.FAUserFaultInfo__c = uf2.Id;
+        // insert fa2;
+        // ba2 = new BusinessActivity__c();
+        // ba2.BusinessATS__c = tsr2.Id;
+        // ba2.workingHours__c = 2;
+        // ba2.User_FaultInfo__c = uf2.Id;
+        // insert ba2;
+
+        // uf3 = new User_FaultInfo__c();
+        // insert uf3;
+        // fa3 = new FailureAsset__c();
+        // fa3.model__c = 'test3';
+        // fa3.FAUserFaultInfo__c = uf3.Id;
+        // insert fa3;
+        // ba3 = new BusinessActivity__c();
+        // ba3.BusinessATS__c = tsr2.Id;
+        // ba3.workingHours__c = 2;
+        // ba3.User_FaultInfo__c = uf3.Id;
+        // insert ba3;
+
+        // Attachment att = new Attachment(
+        //     Name = 'ORDER-123456.pdf',
+        //     parentId = ba1.Id,
+        //     Body = EncodingUtil.base64Decode('test')
+        // );
+        // insert att;
+
+        // Attachment att2 = new Attachment(
+        //     Name = 'not-ORDER-123456.pdf',
+        //     parentId = ba2.Id,
+        //     Body = EncodingUtil.base64Decode('test')
+        // );
+        // insert att2;
+
+    }
+    static testMethod void testMethod1() {
+        basicData();
+        update uf1;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/BusinessActivityHandlerTest.cls-meta.xml b/scr/classes/BusinessActivityHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/BusinessActivityHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CampaignRelationshipController.cls b/scr/classes/CampaignRelationshipController.cls
new file mode 100644
index 0000000..092ff55
--- /dev/null
+++ b/scr/classes/CampaignRelationshipController.cls
@@ -0,0 +1,82 @@
+public with sharing class CampaignRelationshipController {
+
+	public string campaignId {get; set;}
+	public List<CampaignRelationship__c> CRList {get; set;}
+	public List<CampaignRelationship__c> RVICRList {get; set;}
+	public List<CampaignRelationship__c> NDTCRList {get; set;}
+	public List<CampaignRelationship__c> ANICRList {get; set;}
+	public List<CampaignRelationship__c> IECRList {get; set;}
+
+	public String baseUrl { get; set; }
+
+	public  CampaignRelationshipController(){
+
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+        campaignId = System.currentPageReference().getParameters().get('campaignId');
+
+
+	} 
+
+	public CampaignRelationshipController(ApexPages.StandardController controller) {
+		campaignId = controller.getRecord().Id;
+		system.debug('campaignId---->'+campaignId);
+
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+
+	}
+
+	public PageReference init() {
+		
+		CRList  = new List<CampaignRelationship__c>();
+		CRList = [SELECT Id,Name,RelationshipAccount__c,RelationshipAccount__r.Name,
+							RelationshipAccountStatus__c,RelationshipProductSegment__c,
+							RelationshipCampaign__c,ManagementCode__c 
+				FROM CampaignRelationship__c 
+				WHERE RelationshipCampaign__c = :campaignId Order by Id];
+		
+		
+		RVICRList  = new List<CampaignRelationship__c>();
+		NDTCRList  = new List<CampaignRelationship__c>();
+
+		ANICRList  = new List<CampaignRelationship__c>();
+
+		IECRList  = new List<CampaignRelationship__c>();
+		if (CRList.size() > 0) {
+			for (CampaignRelationship__c cr:CRList) {
+				if (cr.RelationshipProductSegment__c == 'RVI') {
+					RVICRList.add(cr);
+				} else if (cr.RelationshipProductSegment__c == 'NDT') {
+					NDTCRList.add(cr);
+				} else if (cr.RelationshipProductSegment__c == 'ANI') {
+					ANICRList.add(cr);
+				} else if (cr.RelationshipProductSegment__c == 'IE') {
+					IECRList.add(cr);
+				}
+			}
+		}
+		return null;
+	}
+
+
+	public PageReference DataLoadAccount(){
+
+		PageReference ref = new Pagereference(baseUrl +'/apex/DataLoadAccount?campaignId=' + campaignId);
+        ref.setRedirect(true);
+        return ref;
+		//return null ;
+	}
+
+	//public PageReference UnabletoEdit() {
+ //       PageReference ref = new Pagereference('/apex/TSRepair?Id=' + repairId);
+ //       ref.setRedirect(true);
+ //       return ref;
+ //   }
+}
\ No newline at end of file
diff --git a/scr/classes/CampaignRelationshipController.cls-meta.xml b/scr/classes/CampaignRelationshipController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CampaignRelationshipController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CampaignRelationshipControllerTest.cls b/scr/classes/CampaignRelationshipControllerTest.cls
new file mode 100644
index 0000000..72b2e1a
--- /dev/null
+++ b/scr/classes/CampaignRelationshipControllerTest.cls
@@ -0,0 +1,90 @@
+@isTest
+private class CampaignRelationshipControllerTest {
+    static testMethod void testMethod1() {
+    	List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+    	List<RecordType> rectRVI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer RVI'];
+    	List<RecordType> rectNDT = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+    	List<RecordType> rectANI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        Campaign campain = new Campaign();
+        campain.Name = '娴嬭瘯甯傚満娲诲姩';
+
+        insert campain;
+        List<Account> insertAccountList = new List<Account>();
+        Account accIE = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        //insert accIE;
+        insertAccountList.add(accIE);
+
+        Account accRVI = new Account(
+            name = '*',
+            RecordTypeId = rectRVI[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer RVI',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        //insert accRVI;
+         insertAccountList.add(accRVI);
+        Account accNDT = new Account(
+            name = '*',
+            RecordTypeId = rectNDT[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer NDT',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        //insert accNDT;
+        insertAccountList.add(accNDT);
+        Account accANI = new Account(
+            name = '*',
+            RecordTypeId = rectANI[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer ANI',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        //insert accANI;
+        insertAccountList.add(accANI);
+        insert insertAccountList;
+
+        List<CampaignRelationship__c> relationshipList = new List<CampaignRelationship__c>();
+        CampaignRelationship__c r1 = new CampaignRelationship__c();
+        r1.RelationshipAccount__c = accIE.id;
+        r1.RelationshipCampaign__c = campain.Id;
+        relationshipList.add(r1);
+
+        CampaignRelationship__c r2 = new CampaignRelationship__c();
+        r2.RelationshipAccount__c = accRVI.id;
+        r2.RelationshipCampaign__c = campain.Id;
+        relationshipList.add(r2);
+
+        CampaignRelationship__c r3 = new CampaignRelationship__c();
+        r3.RelationshipAccount__c = accNDT.id;
+        r3.RelationshipCampaign__c = campain.Id;
+        relationshipList.add(r3);
+
+        CampaignRelationship__c r4 = new CampaignRelationship__c();
+        r4.RelationshipAccount__c = accANI.id;
+        r4.RelationshipCampaign__c = campain.Id;
+        relationshipList.add(r4);
+
+
+        insert relationshipList;
+        PageReference page = new PageReference('/apex/CampaignRelationship?campaignId='+campain.Id);
+        System.Test.setCurrentPage(page);
+        CampaignRelationshipController controller = new CampaignRelationshipController();
+        controller.init(); 
+
+        controller = new CampaignRelationshipController(new ApexPages.StandardController(campain));
+        controller.init();
+        controller.DataLoadAccount(); 
+
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CampaignRelationshipControllerTest.cls-meta.xml b/scr/classes/CampaignRelationshipControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CampaignRelationshipControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CampaignUpsertContactToSapBatch.cls b/scr/classes/CampaignUpsertContactToSapBatch.cls
new file mode 100644
index 0000000..f2b20e8
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapBatch.cls
@@ -0,0 +1,42 @@
+global class CampaignUpsertContactToSapBatch implements Database.Batchable<sObject>, Database.AllowsCallouts {
+    public String query;
+    // 甯傚満娲诲姩鎵归噺瀵煎叆鑱旂郴浜猴紝姣忔櫄鍙戦�佺粰SAP
+    public List<String> contactIdList;
+    global CampaignUpsertContactToSapBatch() {
+        this.query = query;
+    }
+
+    global CampaignUpsertContactToSapBatch(List<String> contactIdList) {
+        this.contactIdList = contactIdList;
+    }
+    
+
+    global Database.QueryLocator start(Database.BatchableContext bc) {
+
+        if (contactIdList != null && contactIdList.size() > 0) {
+            return Database.getQueryLocator([SELECT Id,Name,isBatch__c,CampaignUpsertContact__c FROM Contact WHERE Id IN : contactIdList]);
+        } else {
+            return Database.getQueryLocator([SELECT Id,Name,isBatch__c,CampaignUpsertContact__c FROM Contact WHERE CampaignUpsertContact__c = true ]);
+        }
+
+        
+    }
+
+    global void execute(Database.BatchableContext BC, List<Contact> contactList) {
+        
+        if (contactList != null && contactList.size() > 0){
+            List<String> contactIdListToSAP = new List<String>();
+            for (Contact con:contactList) {
+                con.CampaignUpsertContact__c = false;
+                contactIdListToSAP.add(con.Id);
+            }
+            SBG001TriggerHandler.calloutContactNotFuture(null,contactIdListToSAP);
+            update contactList;
+
+        }
+    }
+
+    global void finish(Database.BatchableContext BC) {
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CampaignUpsertContactToSapBatch.cls-meta.xml b/scr/classes/CampaignUpsertContactToSapBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CampaignUpsertContactToSapBatchSchedule.cls b/scr/classes/CampaignUpsertContactToSapBatchSchedule.cls
new file mode 100644
index 0000000..4f2f9dc
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapBatchSchedule.cls
@@ -0,0 +1,5 @@
+global class CampaignUpsertContactToSapBatchSchedule implements Schedulable {
+    global void execute(SchedulableContext sc) {
+        Id execBTId = Database.executeBatch(new CampaignUpsertContactToSapBatch(), 100);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CampaignUpsertContactToSapBatchSchedule.cls-meta.xml b/scr/classes/CampaignUpsertContactToSapBatchSchedule.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapBatchSchedule.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CampaignUpsertContactToSapBatchTest.cls b/scr/classes/CampaignUpsertContactToSapBatchTest.cls
new file mode 100644
index 0000000..3e09983
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapBatchTest.cls
@@ -0,0 +1,97 @@
+@isTest
+private class CampaignUpsertContactToSapBatchTest {
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account acc = new Account();
+        acc.Name = 'test001';
+        acc.RecordTypeId = '01228000000TdF1';
+        acc.ProductSegment__c = 'BS';
+        acc.ManagementCode_Ext__c = '1234567';
+        acc.AccountStatus__c = 'Active';
+        acc.DepartmentName__c = 'DepartmentNametest';
+        acc.DivisionName__c = 'DivisionNametest';
+        acc.City__c = '鍖椾含';
+        acc.Phone = '18711111111';
+        acc.MobilePhoneNumber__c ='18711111112';
+        acc.Fax = '18711111113';
+        acc.PostCode__c = '100111';
+        acc.Address1__c = 'Address1';
+        acc.Sub_Use__c = 'LED';
+        insert acc;
+
+        Contact con = new Contact();
+        con.StatusD__c = 'Pass';
+        con.FirstName = 'con';
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.ManagementCode_Ext__c = '1234568';
+        con.ContactStatus__c = 'Active';
+        con.Phone = '01012345678';
+        con.MobilePhone = '01012345679';
+        acc.Fax = '18711111113';
+        con.Email = 'EmailD__c@test.com';
+        con.Postcode__c = '100111';
+        con.Address1__c = 'Address1D';
+        con.Department = 'Department';
+        con.CampaignUpsertContact__c = true;
+        insert con;
+
+        Test.startTest();
+        Id execBTId = null;
+        // System.Test.StartTest();
+        List<Contact> contactList = [SELECT Id,Name,isBatch__c,CampaignUpsertContact__c FROM Contact WHERE CampaignUpsertContact__c = true];
+        System.assertEquals(1, contactList.size());
+        execBTId = Database.executeBatch(new CampaignUpsertContactToSapBatch());
+        Test.stopTest();
+        contactList = [SELECT Id,Name,isBatch__c,CampaignUpsertContact__c FROM Contact WHERE CampaignUpsertContact__c = true];
+        System.assertEquals(0, contactList.size());
+    }
+
+    static testMethod void testMethod2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account acc = new Account();
+        acc.Name = 'test001';
+        acc.RecordTypeId = '01228000000TdF1';
+        acc.ProductSegment__c = 'BS';
+        acc.ManagementCode_Ext__c = '1234567';
+        acc.AccountStatus__c = 'Active';
+        acc.DepartmentName__c = 'DepartmentNametest';
+        acc.DivisionName__c = 'DivisionNametest';
+        acc.City__c = '鍖椾含';
+        acc.Phone = '18711111111';
+        acc.MobilePhoneNumber__c ='18711111112';
+        acc.Fax = '18711111113';
+        acc.PostCode__c = '100111';
+        acc.Address1__c = 'Address1';
+        acc.Sub_Use__c = 'LED';
+        insert acc;
+
+        Contact con = new Contact();
+        con.StatusD__c = 'Pass';
+        con.FirstName = 'con';
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.ManagementCode_Ext__c = '1234568';
+        con.ContactStatus__c = 'Active';
+        con.Phone = '01012345678';
+        con.MobilePhone = '01012345679';
+        acc.Fax = '18711111113';
+        con.Email = 'EmailD__c@test.com';
+        con.Postcode__c = '100111';
+        con.Address1__c = 'Address1D';
+        con.Department = 'Department';
+        con.CampaignUpsertContact__c = true;
+        insert con;
+
+        Test.startTest();
+        Id execBTId = null;
+        List<String> contactIdList = new List<String>();
+        contactIdList.add(con.Id);
+        execBTId = Database.executeBatch(new CampaignUpsertContactToSapBatch(contactIdList));
+        Test.stopTest();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CampaignUpsertContactToSapBatchTest.cls-meta.xml b/scr/classes/CampaignUpsertContactToSapBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CampaignUpsertContactToSapTest.cls b/scr/classes/CampaignUpsertContactToSapTest.cls
new file mode 100644
index 0000000..bc3eb94
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapTest.cls
@@ -0,0 +1,20 @@
+@isTest
+private class CampaignUpsertContactToSapTest {
+    static testMethod void test_method_one() {
+        // This test runs a scheduled job at midnight Sept. 3rd. 2022
+        String CRON_EXP = '0 0 0 3 9 ? 2022';
+
+        System.Test.startTest();
+        // Schedule the test job
+        String jobId = system.schedule('CampaignUpsertContactToSapTest', CRON_EXP, new CampaignUpsertContactToSapBatchSchedule());
+        // Get the information from the CronTrigger API object
+        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
+        // Verify the expressions are the same
+        System.assertEquals(CRON_EXP, ct.CronExpression);
+        // Verify the job has not run
+        System.assertEquals(0, ct.TimesTriggered);
+        // Verify the next time the job will run
+        System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
+        System.Test.StopTest();
+    }   
+}
\ No newline at end of file
diff --git a/scr/classes/CampaignUpsertContactToSapTest.cls-meta.xml b/scr/classes/CampaignUpsertContactToSapTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CampaignUpsertContactToSapTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CaseEmailComeBackListen.cls b/scr/classes/CaseEmailComeBackListen.cls
new file mode 100644
index 0000000..3b4fa58
--- /dev/null
+++ b/scr/classes/CaseEmailComeBackListen.cls
@@ -0,0 +1,89 @@
+global class CaseEmailComeBackListen implements Messaging.InboundEmailHandler {
+   global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
+    	System.debug('杩涘叆Case鍥炲閭欢鐩戝惉');
+    	String id = '';
+		if(String.isNotBlank(email.subject)){
+			List<String> str = email.subject.split('~');
+			if(str!=null && str.size()!=0){
+				//鎴彇閭欢鍏宠仈淇℃伅锛屾煡璇㈤偖浠跺叧鑱斿璞★紝鍒ゆ柇鏄惁璺宠繃閭欢鏈嶅姟
+				String name = str[1];
+				if(String.isNotBlank(name)){
+					List<User_FaultInfo__c> caseList = [select Id,notSaveEmail__c,Name from User_FaultInfo__c where Name=:name];
+					if(caseList!=null && caseList.size()!=0){
+						id = caseList[0].Id;
+						System.debug('Case閭欢鍥炲鐩戝惉:'+caseList[0].notSaveEmail__c);
+						if(caseList[0].notSaveEmail__c){
+							System.debug('璺宠繃閭欢鏈嶅姟鐩戝惉');
+							caseList[0].notSaveEmail__c = false;
+							update caseList[0];
+							return null;
+						}
+					}
+				}
+			}
+		}
+		Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
+		createEmail(email,id);
+		//SendEmail();
+		result.success = true;
+		return result;
+	} 
+	public void createEmail(Messaging.InboundEmail email,String id){
+		Mail_Merge__c mailMerge = new Mail_Merge__c();
+		//閭欢鏍囬
+		if(String.isNotBlank(email.subject)){
+			mailMerge.SUBJECTCOPY__c = email.subject;
+			List<String> str = email.subject.split('~');
+			if(str!=null && str.size()!=0){
+				mailMerge.SUBJECT__c = str[0];
+				mailMerge.Name = str[0];
+			}
+		}else{
+			mailMerge.SUBJECTCOPY__c = '';
+			mailMerge.SUBJECT__c = '';
+			mailMerge.Name = '';
+		}
+		mailMerge.CaseF__c = id;
+		mailMerge.RECORD_TYPE__c = 'Case';
+		//鍙戜欢浜哄湴鍧�
+		mailMerge.FROM__c = email.fromAddress;
+		//鏀朵欢浜哄湴鍧�
+		mailMerge.RECIPIENT__c = getAddresses(email.toAddresses);
+		//鎶勯�佷汉
+		mailMerge.CC__c = getAddresses(email.ccAddresses);
+		//閭欢淇℃伅
+		mailMerge.MESSAGE__c = email.plainTextBody;
+		//鏀跺彇鍥炲閭欢鏃堕棿
+		mailMerge.DATE__c = Date.today();
+
+		mailMerge.TYPE__c = 'reply';
+		
+		insert mailMerge;
+		//淇濆瓨閭欢闄勪欢
+		saveFile(email.binaryAttachments,mailMerge.Id);
+	}
+
+	public String getAddresses(List<String> addresses){
+		String returnStr = '';
+		if(addresses!=null && addresses.size()!=0){
+			for(String str:addresses){
+				returnStr += str+';';
+			}
+		}
+		return returnStr;
+	}
+
+	public void saveFile(List<Messaging.InboundEmail.BinaryAttachment> binaryAttachments,String Id){
+		if (binaryAttachments != null && binaryAttachments.size()!=0) {
+			List<Attachment> attachmentList = new List<Attachment>();
+			for(Messaging.InboundEmail.BinaryAttachment emailFile : binaryAttachments){
+				Attachment attachment = new Attachment();
+				attachment.Name = emailFile.fileName;
+				attachment.Body = emailFile.body;
+				attachment.ParentId = Id;
+				attachmentList.add(attachment);
+			}
+			insert attachmentList;
+		}
+	} 
+}
\ No newline at end of file
diff --git a/scr/classes/CaseEmailComeBackListen.cls-meta.xml b/scr/classes/CaseEmailComeBackListen.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CaseEmailComeBackListen.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CaseWebService.cls b/scr/classes/CaseWebService.cls
new file mode 100644
index 0000000..31c9218
--- /dev/null
+++ b/scr/classes/CaseWebService.cls
@@ -0,0 +1,16 @@
+global class CaseWebService {
+    // 鍏抽棴涓
+    WebService static String CloseCase(String caseId) {
+        String result = '1';
+        Case  closeCase = new Case();
+        closeCase.Id = caseId;
+        closeCase.Status = 'Closed';
+
+        try{
+            update closeCase;
+        } catch (Exception ex) {
+            result = ex.getMessage();
+        }
+        return result;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CaseWebService.cls-meta.xml b/scr/classes/CaseWebService.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CaseWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CertificationDetailTriggerHandler.cls b/scr/classes/CertificationDetailTriggerHandler.cls
new file mode 100644
index 0000000..221bfbd
--- /dev/null
+++ b/scr/classes/CertificationDetailTriggerHandler.cls
@@ -0,0 +1,56 @@
+public without sharing class CertificationDetailTriggerHandler {
+    
+    public static void updateDealerPurchaseDetail(List<CertificationDetails__c> newList, Map<Id, CertificationDetails__c> newMap, 
+    											  List<CertificationDetails__c> oldList, Map<Id, CertificationDetails__c> oldMap) {
+        // SBG203璇佺収鍙樻洿鍚庯紝鏂板璇佺収鏄庣粏锛岀粰浠g悊鍟嗚喘涔版槑缁嗕腑鐨勮瘉鐓ф槑缁嗗瓧娈佃祴鍊�-ANI杈愬皠璇佺収宸叉洿鏂�-鏂版簮蹇楀嫟-XHL
+    	Map<String,List<CertificationDetails__c>> certificationDetailMap = new Map<String,List<CertificationDetails__c>>();
+    	List<CertificationDetails__c> detailList = new List<CertificationDetails__c>();
+    	String dealerId = '';
+    	for (CertificationDetails__c detail : newList) {
+
+    		if (detail.ActivitieTypes__c == '閿�鍞�' && detail.IsActive__c == true) {
+    			dealerId = detail.CertificationDetailAccountId__c;
+				if (certificationDetailMap.containsKey(dealerId)) {
+					detailList =  certificationDetailMap.get(dealerId);
+					detailList.add(detail);
+					certificationDetailMap.put(dealerId, detailList);
+				} else {
+					detailList.add(detail);
+					certificationDetailMap.put(dealerId, detailList);
+				}
+    		}
+    		
+    		
+    	}
+
+    	if (String.isNotBlank(dealerId) && certificationDetailMap != null && certificationDetailMap.size() > 0) {
+    		Map<String, PurchaseDetails__c> dealerModelQuantityMap = RadiationUtil.GetPurchaseDetailsMap(dealerId);
+			if (dealerModelQuantityMap != null && dealerModelQuantityMap.size() > 0) {
+				for (CertificationDetails__c detail : certificationDetailMap.get(dealerId)) {
+
+					if ('Delta鍜孷anta'.equals(detail.ProdustionType__c)) {
+
+						List<String> childModels = new List<String> {'Delta', 'Vanta'};
+						for (String childModel : childModels) {
+
+							if (dealerModelQuantityMap.containsKey(childModel)) {
+								dealerModelQuantityMap.get(childModel).PurchaseDetail__c = detail.Id;
+							}
+							
+						}
+
+					} else {
+						if (dealerModelQuantityMap.containsKey(detail.ProdustionType__c)) {
+							dealerModelQuantityMap.get(detail.ProdustionType__c).PurchaseDetail__c = detail.Id;
+						}
+					}
+
+				} 
+
+				update dealerModelQuantityMap.values();
+
+			}   	
+    	}
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CertificationDetailTriggerHandler.cls-meta.xml b/scr/classes/CertificationDetailTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CertificationDetailTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CertificationDetailTriggerTest.cls b/scr/classes/CertificationDetailTriggerTest.cls
new file mode 100644
index 0000000..a3a059f
--- /dev/null
+++ b/scr/classes/CertificationDetailTriggerTest.cls
@@ -0,0 +1,81 @@
+@isTest
+private class CertificationDetailTriggerTest {
+    public static Account acc0;
+    public static License_Information__c licenseInfo;
+    public static String effectiveYear;
+    static void inittransfersData() {
+        NFMUtil.EscapeSBG001TriggerHandler = true;
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        // ANI浠g悊鍟�
+        acc0 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer ANI',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer ANI',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            NationalEnterpriseUser__c = true
+        );
+        insert acc0;
+        // 杈愬皠璇佺収
+        licenseInfo = new License_Information__c();
+        licenseInfo.LicenseAndAccount__c = acc0.Id;
+        licenseInfo.ValidFrom__c = Date.today().addDays(-22);
+        licenseInfo.ValidTo__c = Date.today().addDays(22);
+        licenseInfo.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert licenseInfo;
+        // 鍒涘缓璐拱鏄庣粏
+        effectiveYear = String.valueOf(Date.today().year());
+        PurchaseDetails__c pdetail = new PurchaseDetails__c();
+        pdetail.PurchaseAccount__c = acc0.Id;
+        pdetail.TakeEffectInYear__c = effectiveYear;
+        pdetail.PurProductModel__c = 'Delta';
+        pdetail.SoldNumber__c = 22;
+        // insert pdetail;
+
+        PurchaseDetails__c pdetai2 = new PurchaseDetails__c();
+        pdetai2.PurchaseAccount__c = acc0.Id;
+        pdetai2.TakeEffectInYear__c = effectiveYear;
+        pdetai2.PurProductModel__c = 'Vanta';
+        pdetai2.SoldNumber__c = 22;
+        // insert pdetai2;
+
+        PurchaseDetails__c pdetai3 = new PurchaseDetails__c();
+        pdetai3.PurchaseAccount__c = acc0.Id;
+        pdetai3.TakeEffectInYear__c = effectiveYear;
+        pdetai3.PurProductModel__c = 'FOX-IQ';
+        pdetai3.SoldNumber__c = 22;
+        // insert pdetai3;
+
+        insert new List<PurchaseDetails__c> {pdetail,pdetai2,pdetai3};
+    }
+    static testMethod void testMethod1() {
+        inittransfersData();
+        String accountId = acc0.Id;
+        // 鏂板缓璇佺収鏄庣粏
+        CertificationDetails__c cDetail = new CertificationDetails__c();
+        cDetail.LicenseInformation__c = licenseInfo.Id;
+        cDetail.DeviceName__c = '鎵嬫寔寮廥鑽у厜鍒嗘瀽浠�';
+        cDetail.ActivitieTypes__c = '閿�鍞�';
+        cDetail.ProdustionType__c = 'Delta鍜孷anta';
+        cDetail.ProductModelNumber__c = 122;
+
+        CertificationDetails__c cDetai2 = new CertificationDetails__c();
+        cDetai2.LicenseInformation__c = licenseInfo.Id;
+        cDetai2.DeviceName__c = '娴嬭瘯';
+        cDetai2.ActivitieTypes__c = '閿�鍞�';
+        cDetai2.ProdustionType__c = 'FOX-IQ';
+        cDetai2.ProductModelNumber__c = 122;
+
+        insert new List<CertificationDetails__c> {cDetail,cDetai2};
+
+        // List<PurchaseDetails__c> purchaseDetailsList = [select Id, Name, RemainingNumber__c, SoldNumber__c,
+        //                          PurProductModel__c, PurchaseAccount__c,PurchaseDetail__c
+        //                          from PurchaseDetails__c
+        //                          where TakeEffectInYear__c = :effectiveYear and PurchaseAccount__c = :accountId];
+
+        // System.assertEquals(depart1.Id, purchaseDetailsList);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CertificationDetailTriggerTest.cls-meta.xml b/scr/classes/CertificationDetailTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CertificationDetailTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ChangePasswordController.cls b/scr/classes/ChangePasswordController.cls
new file mode 100644
index 0000000..31dde01
--- /dev/null
+++ b/scr/classes/ChangePasswordController.cls
@@ -0,0 +1,14 @@
+/**
+ * An apex page controller that exposes the change password functionality
+ */
+public with sharing class ChangePasswordController {
+    public String oldPassword {get; set;}
+    public String newPassword {get; set;}
+    public String verifyNewPassword {get; set;}        
+    
+    public PageReference changePassword() {
+        return Site.changePassword(newPassword, verifyNewPassword, oldpassword);    
+    }     
+    
+   	public ChangePasswordController() {}
+}
\ No newline at end of file
diff --git a/scr/classes/ChangePasswordController.cls-meta.xml b/scr/classes/ChangePasswordController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/ChangePasswordController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ChangePasswordControllerTest.cls b/scr/classes/ChangePasswordControllerTest.cls
new file mode 100644
index 0000000..2814e42
--- /dev/null
+++ b/scr/classes/ChangePasswordControllerTest.cls
@@ -0,0 +1,14 @@
+/**
+ * An apex page controller that exposes the change password functionality
+ */
+@IsTest public with sharing class ChangePasswordControllerTest {
+   	@IsTest(SeeAllData=true) public static void testChangePasswordController() {
+        // Instantiate a new controller with all parameters in the page
+        ChangePasswordController controller = new ChangePasswordController();
+        controller.oldPassword = '123456';
+        controller.newPassword = 'qwerty1'; 
+        controller.verifyNewPassword = 'qwerty1';                
+        
+        System.assertEquals(controller.changePassword(),null);                           
+    }    
+}
\ No newline at end of file
diff --git a/scr/classes/ChangePasswordControllerTest.cls-meta.xml b/scr/classes/ChangePasswordControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/ChangePasswordControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ChatterAnswers.cls b/scr/classes/ChatterAnswers.cls
new file mode 100644
index 0000000..bc84f6b
--- /dev/null
+++ b/scr/classes/ChatterAnswers.cls
@@ -0,0 +1,7 @@
+public class ChatterAnswers {
+    public String createAccount(String firstname, String lastname, Id siteAdminId) {
+         Account a = new Account(name = firstname + ' ' + lastname, ownerId = siteAdminId);
+         insert a;
+         return a.Id;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ChatterAnswers.cls-meta.xml b/scr/classes/ChatterAnswers.cls-meta.xml
new file mode 100644
index 0000000..6dc8b22
--- /dev/null
+++ b/scr/classes/ChatterAnswers.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ChatterAnswersEscalationTriggerTest.cls b/scr/classes/ChatterAnswersEscalationTriggerTest.cls
new file mode 100644
index 0000000..6bfdc36
--- /dev/null
+++ b/scr/classes/ChatterAnswersEscalationTriggerTest.cls
@@ -0,0 +1,24 @@
+@isTest
+private class ChatterAnswersEscalationTriggerTest {
+	static testMethod void validateQuestionEscalation() {
+		String questionTitle = 'questionTitle';
+		String questionBody = 'questionBody';
+		Community[] c = [SELECT Id from Community];
+		// We cannot create a question without a community
+		if (c.size() == 0) { return; }
+		String communityId = c[0].Id;
+		Question q = new Question();
+		q.Title = questionTitle;
+		q.Body = questionBody;
+		q.CommunityId = communityId;
+		insert(q);
+		q.Priority = 'high';
+		update(q);
+		Case ca = [SELECT Origin, CommunityId, Subject, Description from Case where QuestionId =: q.Id];
+		// Test that escaltion trigger correctly escalate the question to a case
+		System.assertEquals(questionTitle, ca.Subject);
+		System.assertEquals(questionBody, ca.Description);
+		System.assertEquals('Chatter Answers', ca.Origin);
+		System.assertEquals(communityId, ca.CommunityId);
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/ChatterAnswersEscalationTriggerTest.cls-meta.xml b/scr/classes/ChatterAnswersEscalationTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..6dc8b22
--- /dev/null
+++ b/scr/classes/ChatterAnswersEscalationTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CodeGenerator.cls b/scr/classes/CodeGenerator.cls
new file mode 100644
index 0000000..f8682a5
--- /dev/null
+++ b/scr/classes/CodeGenerator.cls
@@ -0,0 +1,30 @@
+global class CodeGenerator implements Process.Plugin
+{    
+    global Process.PluginResult invoke(Process.PluginRequest request)
+    {   
+        Map<String, Object> result = new Map<String, Object>();  
+        
+        Integer rand = Math.round(Math.random()*100000);
+        String code  = string.valueOf(rand);
+         
+        result.put('Code', code);
+        
+        return new Process.PluginResult(result);
+    }
+
+    global Process.PluginDescribeResult describe()
+    {
+        Process.PluginDescribeResult result = new Process.PluginDescribeResult();
+        result.description='This plug-in generates a radnom 5-digits code';
+        result.tag='Identity';
+        
+        result.inputParameters = new List<Process.PluginDescribeResult.InputParameter> {};
+        
+        result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter> {
+            new Process.PluginDescribeResult.OutputParameter('Code',
+                Process.PluginDescribeResult.ParameterType.STRING)
+        };
+           
+        return result;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CodeGenerator.cls-meta.xml b/scr/classes/CodeGenerator.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/CodeGenerator.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CodeGeneratorTest.cls b/scr/classes/CodeGeneratorTest.cls
new file mode 100644
index 0000000..13b7db8
--- /dev/null
+++ b/scr/classes/CodeGeneratorTest.cls
@@ -0,0 +1,24 @@
+@isTest
+private class CodeGeneratorTest
+{
+    static testMethod void getCode() {
+     
+        CodeGenerator generator = new CodeGenerator();
+        Map<String,Object> inputParams = new Map<String,Object>();
+        Map<String,Object> outputParams = new Map<String,Object>();
+         
+        Process.PluginRequest request = new Process.PluginRequest(inputParams);
+        Process.PluginResult result;
+        result = generator.invoke(request);
+        
+        System.AssertEquals(1,1);
+    }
+
+    static testMethod void describeTest() {
+
+        CodeGenerator generator = new CodeGenerator();
+        Process.PluginDescribeResult result = generator.describe();
+       
+        System.AssertEquals(result.OutputParameters.size(), 1);
+     }
+}
\ No newline at end of file
diff --git a/scr/classes/CodeGeneratorTest.cls-meta.xml b/scr/classes/CodeGeneratorTest.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/CodeGeneratorTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesLandingController.cls b/scr/classes/CommunitiesLandingController.cls
new file mode 100644
index 0000000..9633c5a
--- /dev/null
+++ b/scr/classes/CommunitiesLandingController.cls
@@ -0,0 +1,12 @@
+/**
+ * An apex page controller that takes the user to the right start page based on credentials or lack thereof
+ */
+public with sharing class CommunitiesLandingController {
+    
+    // Code we will invoke on page load.
+    public PageReference forwardToStartPage() {
+        return Network.communitiesLanding();
+    }
+    
+    public CommunitiesLandingController() {}
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesLandingController.cls-meta.xml b/scr/classes/CommunitiesLandingController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesLandingController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesLandingControllerTest.cls b/scr/classes/CommunitiesLandingControllerTest.cls
new file mode 100644
index 0000000..7479790
--- /dev/null
+++ b/scr/classes/CommunitiesLandingControllerTest.cls
@@ -0,0 +1,9 @@
+/**
+ * An apex page controller that takes the user to the right start page based on credentials or lack thereof
+ */
+@IsTest public with sharing class CommunitiesLandingControllerTest {
+    @IsTest(SeeAllData=true) public static void testCommunitiesLandingController() {
+        // Instantiate a new controller with all parameters in the page
+        CommunitiesLandingController controller = new CommunitiesLandingController();
+      }
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesLandingControllerTest.cls-meta.xml b/scr/classes/CommunitiesLandingControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesLandingControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesLoginController.cls b/scr/classes/CommunitiesLoginController.cls
new file mode 100644
index 0000000..35ab098
--- /dev/null
+++ b/scr/classes/CommunitiesLoginController.cls
@@ -0,0 +1,14 @@
+/**
+ * An apex page controller that exposes the site login functionality
+ */
+global with sharing class CommunitiesLoginController {
+
+    global CommunitiesLoginController () {}
+    
+    // Code we will invoke on page load.
+    global PageReference forwardToAuthPage() {
+    	String startUrl = System.currentPageReference().getParameters().get('startURL');
+    	String displayType = System.currentPageReference().getParameters().get('display');
+        return Network.forwardToAuthPage(startUrl, displayType);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesLoginController.cls-meta.xml b/scr/classes/CommunitiesLoginController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesLoginController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesLoginControllerTest.cls b/scr/classes/CommunitiesLoginControllerTest.cls
new file mode 100644
index 0000000..b892fdc
--- /dev/null
+++ b/scr/classes/CommunitiesLoginControllerTest.cls
@@ -0,0 +1,10 @@
+/**
+ * An apex page controller that exposes the site login functionality
+ */
+@IsTest global with sharing class CommunitiesLoginControllerTest {
+    @IsTest(SeeAllData=true) 
+    global static void testCommunitiesLoginController () {
+     	CommunitiesLoginController controller = new CommunitiesLoginController();
+     	System.assertEquals(null, controller.forwardToAuthPage());       
+    }    
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesLoginControllerTest.cls-meta.xml b/scr/classes/CommunitiesLoginControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesLoginControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesSelfRegConfirmController.cls b/scr/classes/CommunitiesSelfRegConfirmController.cls
new file mode 100644
index 0000000..d98d1fe
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegConfirmController.cls
@@ -0,0 +1,7 @@
+/**
+ * An apex page controller that takes the user to the right start page based on credentials or lack thereof
+ */
+public with sharing class CommunitiesSelfRegConfirmController {
+    
+    public CommunitiesSelfRegConfirmController() {}
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesSelfRegConfirmController.cls-meta.xml b/scr/classes/CommunitiesSelfRegConfirmController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegConfirmController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesSelfRegConfirmControllerTest.cls b/scr/classes/CommunitiesSelfRegConfirmControllerTest.cls
new file mode 100644
index 0000000..18a60bb
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegConfirmControllerTest.cls
@@ -0,0 +1,9 @@
+/**
+ * An apex page controller that takes the user to the right start page based on credentials or lack thereof
+ */
+@IsTest public with sharing class CommunitiesSelfRegConfirmControllerTest {
+    @IsTest(SeeAllData=true) public static void testCommunitiesSelfRegConfirmController() {
+        // Instantiate a new controller with all parameters in the page
+        CommunitiesSelfRegConfirmController controller = new CommunitiesSelfRegConfirmController();
+      }    
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesSelfRegConfirmControllerTest.cls-meta.xml b/scr/classes/CommunitiesSelfRegConfirmControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegConfirmControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesSelfRegController.cls b/scr/classes/CommunitiesSelfRegController.cls
new file mode 100644
index 0000000..e0c8ba7
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegController.cls
@@ -0,0 +1,69 @@
+/**
+ * An apex page controller that supports self registration of users in communities that allow self registration
+ */
+public class CommunitiesSelfRegController {
+
+    public String firstName {get; set;}
+    public String lastName {get; set;}
+    public String email {get; set;}
+    public String password {get; set {password = value == null ? value : value.trim(); } }
+    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
+    public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
+    
+    public CommunitiesSelfRegController() {}
+    
+    private boolean isValidPassword() {
+        return password == confirmPassword;
+    }
+
+    public PageReference registerUser() {
+    
+           // it's okay if password is null - we'll send the user a random password in that case
+        if (!isValidPassword()) {
+            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
+            ApexPages.addMessage(msg);
+            return null;
+        }    
+
+        String profileId = null; // To be filled in by customer.
+        String roleEnum = null; // To be filled in by customer.
+        String accountId = ''; // To be filled in by customer.
+        
+        String userName = email;
+
+        User u = new User();
+        u.Username = userName;
+        u.Email = email;
+        u.FirstName = firstName;
+        u.LastName = lastName;
+        u.CommunityNickname = communityNickname;
+		u.ProfileId = profileId;
+		
+        String userId;
+
+        try {
+            userId = Site.createExternalUser(u, accountId, password);
+        } catch(Site.ExternalUserCreateException ex) {
+            List<String> errors = ex.getDisplayMessages();
+            for (String error : errors)  {
+                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, error));
+            }
+            
+            // This message is used for debugging. Do not display this in the UI to the end user.
+            // It has the information around why the user creation failed.
+            System.debug(ex.getMessage());
+        }
+        
+        if (userId != null) { 
+            if (password != null && password.length() > 1) {
+                return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
+            }
+            else {
+                PageReference page = System.Page.CommunitiesSelfRegConfirm;
+                page.setRedirect(true);
+                return page;
+            }
+        }
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesSelfRegController.cls-meta.xml b/scr/classes/CommunitiesSelfRegController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CommunitiesSelfRegControllerTest.cls b/scr/classes/CommunitiesSelfRegControllerTest.cls
new file mode 100644
index 0000000..bda9c05
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegControllerTest.cls
@@ -0,0 +1,20 @@
+/**
+ * An apex page controller that supports self registration of users in communities that allow self registration
+ */
+@IsTest public with sharing class CommunitiesSelfRegControllerTest {
+    @IsTest(SeeAllData=true) 
+    public static void testCommunitiesSelfRegController() {
+        CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
+        controller.firstName = 'FirstName';
+        controller.lastName = 'LastName';
+        controller.email = 'test@force.com';
+        controller.communityNickname = 'test';
+        
+        // registerUser will always return null when the page isn't accessed as a guest user
+        System.assert(controller.registerUser() == null);    
+        
+        controller.password = 'abcd1234';
+        controller.confirmPassword = 'abcd123';
+        System.assert(controller.registerUser() == null);  
+    }    
+}
\ No newline at end of file
diff --git a/scr/classes/CommunitiesSelfRegControllerTest.cls-meta.xml b/scr/classes/CommunitiesSelfRegControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/CommunitiesSelfRegControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ContactTriggerHandler.cls b/scr/classes/ContactTriggerHandler.cls
new file mode 100644
index 0000000..e17979a
--- /dev/null
+++ b/scr/classes/ContactTriggerHandler.cls
@@ -0,0 +1,205 @@
+public without sharing class ContactTriggerHandler {
+    
+    public static void setIsNew(List<Contact> newList, Map<Id, Contact> newMap, List<Contact> oldList, Map<Id, Contact> oldMap) {
+        for (Contact newCon : newList) {
+            // String new_profileId = UserInfo.getProfileId().subString(0,15);
+            //calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+            String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+            
+            if (new_profileId.subString(0,15) == System.label.Market_Department || new_profileId.subString(0,15) == System.label.Market_Department1 || new_profileId.subString(0,15) == System.label.Service_Owner ||
+                UserInfo.getUserType() == 'PowerPartner') {
+                newCon.IsNew__c = true;
+            } else {
+                newCon.MobilePhoneD__c = newCon.MobilePhone;
+                newCon.OtherPhoneD__c = newCon.OtherPhone;
+                newCon.FaxD__c = newCon.Fax;
+                newCon.EmailD__c = newCon.Email;
+                newCon.PhoneD__c = newCon.Phone;
+                newCon.TitleD__c = newCon.Title;
+                newCon.Address1D__c = newCon.Address1__c;
+                newCon.Address2D__c = newCon.Address2__c;
+                newCon.Address3D__c = newCon.Address3__c;
+                newCon.PostcodeD__c = newCon.Postcode__c;
+                newCon.ContactStatusD__c = newCon.ContactStatus__c;
+                newCon.CancelReasonD__c = newCon.CancelReason__c;
+                if(new_profileId.subString(0,15) == '00e28000000YKLo'){
+                    newCon.IsNew__c = true;
+                }
+            }
+        }
+    }
+    
+    public static void updateForDealer(List<Contact> newList, Map<Id, Contact> newMap, List<Contact> oldList, Map<Id, Contact> oldMap) {
+        //鐜嬮箯浼� 娣诲姞userId 鏈嶅姟閮ㄤ慨鏀硅仈绯讳汉閲嶆柊瀹℃壒 鍒ゆ柇褰撳墠淇敼鐨勭櫥闄嗕汉鏄惁鏄瓩瀛︽磱  鍚存檽涓�
+        String userId = UserInfo.getUserId(); 
+        for (Contact newCon : newList) {
+            Contact oldCon = oldMap.get(newCon.Id);
+            
+            if(newCon.AccountStaut__c != 'Pass' && newCon.StatusD__c != oldCon.StatusD__c && newCon.StatusD__c == 'Pass' ){
+                newCon.addError('璇峰厛瀹℃壒瀵瑰簲鐨勫鎴�');
+            }
+
+            if (newCon.MobilePhoneD__c != oldCon.MobilePhoneD__c ||
+                newCon.OtherPhoneD__c != oldCon.OtherPhoneD__c ||
+                newCon.FaxD__c != oldCon.FaxD__c ||
+                newCon.EmailD__c != oldCon.EmailD__c ||
+                newCon.PhoneD__c != oldCon.PhoneD__c ||
+                newCon.TitleD__c != oldCon.TitleD__c ||
+                newCon.Address1D__c != oldCon.Address1D__c ||
+                newCon.Address2D__c != oldCon.Address2D__c ||
+                newCon.Address3D__c != oldCon.Address3D__c ||
+                newCon.PostcodeD__c != oldCon.PostcodeD__c ||
+                newCon.ContactStatusD__c != oldCon.ContactStatusD__c ||
+                newCon.CancelReasonD__c != oldCon.CancelReasonD__c) {
+                // String new_profileId = UserInfo.getProfileId().subString(0,15);
+                //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+                String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+                //鐜嬮箯浼� 娣诲姞 && !((oldCon.ProductSegment__c == 'BS' || oldCon.ProductSegment__c == 'NDT' || oldCon.ProductSegment__c = 'ANI') && oldCon.isServiceCreate__c == true)
+                //鏈嶅姟閮ㄤ慨鏀硅仈绯讳汉淇℃伅 LS銆丯DT銆丄NI鏃犻渶瀹℃壒,璺宠繃瀹℃壒鐘舵�佸彉鑽夋
+                if (( new_profileId.subString(0,15) == System.label.Service_Owner
+                    || UserInfo.getUserType() == 'PowerPartner' || userId =='00528000000YWC6' || userId =='00528000000YWE7')
+                    && !((oldCon.ProductSegment__c == 'BS' || oldCon.ProductSegment__c == 'NDT' || oldCon.ProductSegment__c == 'ANI') && oldCon.isServiceCreate__c == true)) {
+                    newCon.StatusD__c = 'Draft';
+                }
+            }
+            
+            if (newCon.MobilePhone != oldCon.MobilePhone) {
+                newCon.MobilePhoneD__c = newCon.MobilePhone;
+            }
+            if (newCon.OtherPhone != oldCon.OtherPhone) {
+                newCon.OtherPhoneD__c = newCon.OtherPhone;
+            }
+            if (newCon.Fax != oldCon.Fax) {
+                newCon.FaxD__c = newCon.Fax;
+            }
+            if (newCon.Email != oldCon.Email) {
+                newCon.EmailD__c = newCon.Email;
+            }
+            if (newCon.Phone != oldCon.Phone) {
+                newCon.PhoneD__c = newCon.Phone;
+            }
+            if (newCon.Title != oldCon.Title) {
+                newCon.TitleD__c = newCon.Title;
+            }
+            if (newCon.Address1__c != oldCon.Address1__c) {
+                newCon.Address1D__c = newCon.Address1__c;
+            }
+            if (newCon.Address2__c != oldCon.Address2__c) {
+                newCon.Address2D__c = newCon.Address2__c;
+            }
+            if (newCon.Address3__c != oldCon.Address3__c) {
+                newCon.Address3D__c = newCon.Address3__c;
+            }
+            if (newCon.Postcode__c != oldCon.Postcode__c) {
+                newCon.PostcodeD__c = newCon.Postcode__c;
+            }
+                
+            if (newCon.ContactStatus__c != oldCon.ContactStatus__c) {
+                newCon.ContactStatusD__c = newCon.ContactStatus__c;
+            }
+            if (newCon.CancelReason__c != oldCon.CancelReason__c) {
+                newCon.CancelReasonD__c = newCon.CancelReason__c;
+            }
+        }
+    }
+    
+    public static void dealerContactApproval(List<Contact> newList, Map<Id, Contact> newMap, List<Contact> oldList, Map<Id, Contact> oldMap) {
+        List<String> accIdList = new List<String>();
+        for (Contact newCon : newList) {
+            accIdList.add(newCon.AccountId);
+        }
+        // 鐜版湁瀹㈡埛灏忕粍
+        Map<String, String> accsMap = new Map<String, String>();
+        //List<AccountTeamMember> atmList = [select Id, AccountId, UserId from AccountTeamMember where AccountId in :accIdList];
+        List<AccountShare> accsList = [select id, accountId, UserOrGroupId, AccountAccessLevel, RowCause from AccountShare where AccountId in :accIdList and RowCause = 'Team'];
+        for (AccountShare accs : accsList) {
+            accsMap.put(accs.AccountId + '' + accs.UserOrGroupId, accs.Id);
+        }
+        // 闇�瑕佹洿鏂板鎴峰皬缁�
+//      List<AccountShare> updList = new List<AccountShare>();
+
+        //鏂扮殑鑾峰彇绠�妗D calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑  
+        // String new_profileId = UserInfo.getProfileId().subString(0,15);
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+        for (Contact newCon : newList) {
+            Contact oldCon = oldMap.get(newCon.Id);
+
+            if (new_profileId.subString(0,15) == System.label.Market_Department || new_profileId.subString(0,15) == System.label.Market_Department1){
+                newCon.MobilePhone = newCon.MobilePhoneD__c;
+                newCon.OtherPhone = newCon.OtherPhoneD__c;
+                newCon.Fax = newCon.FaxD__c;
+                newCon.Email = newCon.EmailD__c;
+                newCon.Phone = newCon.PhoneD__c;
+                newCon.Title = newCon.TitleD__c;
+                newCon.Address1__c = newCon.Address1D__c;
+                newCon.Address2__c = newCon.Address2D__c;
+                newCon.Address3__c = newCon.Address3D__c;
+                newCon.Postcode__c = newCon.PostcodeD__c;
+                
+                newCon.ContactStatus__c = newCon.ContactStatusD__c;
+                newCon.CancelReason__c = newCon.CancelReasonD__c;
+            } else if (newCon.StatusD__c != oldCon.StatusD__c) {
+                if (newCon.StatusD__c == 'Submit') {
+                    //newCon.DealerSelectOwner__c = newCon.Account.DealerSelectOwner__c;
+                }
+                if (newCon.StatusD__c == 'Pass') {
+                    // 鎵瑰噯杩囩▼鑲畾鏄竴鏉′竴鏉℃壒鍑嗙殑锛屾墍浠ヨ繖閲屽啀寰幆涓啓浜唖elect鏂�
+                    
+                    List<Account> accList = [select Id, IsNew__c, AccountStatus__c from Account where Id = :newCon.AccountId];
+                    if (accList.size() > 0 ) {
+                        Account acc = accList[0];
+                        if (acc.IsNew__c == true || (acc.AccountStatus__c == 'Cancel' && newCon.ContactStatusD__c != 'Cancel')) {
+                            newCon.addError('瀹㈡埛鏃犳晥鎴栨湭閫氳繃瀹℃壒锛屼笉鑳芥壒鍑嗗綋鍓嶈仈绯讳汉銆�');
+                        }
+                    }
+                    
+                    newCon.MobilePhone = newCon.MobilePhoneD__c;
+                    newCon.OtherPhone = newCon.OtherPhoneD__c;
+                    newCon.Fax = newCon.FaxD__c;
+                    newCon.Email = newCon.EmailD__c;
+                    newCon.Phone = newCon.PhoneD__c;
+                    newCon.Title = newCon.TitleD__c;
+                    newCon.Address1__c = newCon.Address1D__c;
+                    newCon.Address2__c = newCon.Address2D__c;
+                    newCon.Address3__c = newCon.Address3D__c;
+                    newCon.Postcode__c = newCon.PostcodeD__c;
+                    
+                    newCon.ContactStatus__c = newCon.ContactStatusD__c;
+                    newCon.CancelReason__c = newCon.CancelReasonD__c;
+                    
+//                  if (accsMap.containsKey(newCon.AccountId + '' + newCon.OwnerId) == true && newCon.IsNew__c == true) {
+//                      AccountShare upd = new AccountShare(
+//                          Id = accsMap.get(newCon.AccountId + '' + newCon.OwnerId),
+//                          AccountAccessLevel = 'Edit'
+//                      );
+//                      updList.add(upd);
+//                  }
+                    
+                    if (newCon.IsNew__c = true) {
+                        newCon.IsNew__c = false;
+                    }
+                }
+                if (newCon.StatusD__c == 'Reject' && newCon.IsNew__c == false) {
+                    newCon.MobilePhoneD__c = newCon.MobilePhone;
+                    newCon.OtherPhoneD__c = newCon.OtherPhone;
+                    newCon.FaxD__c = newCon.Fax;
+                    newCon.EmailD__c = newCon.Email;
+                    newCon.PhoneD__c = newCon.Phone;
+                    newCon.TitleD__c = newCon.Title;
+                    newCon.Address1D__c = newCon.Address1__c;
+                    newCon.Address2D__c = newCon.Address2__c;
+                    newCon.Address3D__c = newCon.Address3__c;
+                    newCon.PostcodeD__c = newCon.Postcode__c;
+                    
+                    newCon.ContactStatusD__c = newCon.ContactStatus__c;
+                    newCon.CancelReasonD__c = newCon.CancelReason__c;
+                }
+            }
+        }
+        // 鏇存柊瀹㈡埛灏忕粍
+//      if (updList!= null && updList.size() > 0) {
+//          update updList;
+//      }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ContactTriggerHandler.cls-meta.xml b/scr/classes/ContactTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/ContactTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ContactTriggerHandlerTest.cls b/scr/classes/ContactTriggerHandlerTest.cls
new file mode 100644
index 0000000..37dfd9f
--- /dev/null
+++ b/scr/classes/ContactTriggerHandlerTest.cls
@@ -0,0 +1,90 @@
+@isTest
+private class ContactTriggerHandlerTest {
+
+    static testMethod void myUnitTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        User user = new User();
+        user.LastName = 'test02';
+        user.FirstName = 'test';
+        user.Alias = 'test02';
+        user.Email = 'test@test02.com';
+        user.Username = 'test111@test3222.com';
+        user.CommunityNickname = 'test1111';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+        
+        Account acc = new Account();
+        acc.Name = '*';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        acc.stautesD__c= 'Pass';
+        insert acc;
+        
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+        
+        insert con;
+        
+        con.MobilePhone = 'MobilePhone';
+        con.OtherPhone = 'OtherPhone';
+        con.Fax = 'Fax';
+        con.Email = 'Email@test.com';
+        con.Phone = 'Phone';
+        con.Title = 'Title';
+        con.Address1__c = 'Address1__c';
+        con.Address2__c = 'Address2__c';
+        con.Address3__c = 'Address3__c';
+        con.Postcode__c = '100222';
+        con.ContactStatus__c = 'ContactStatus__c';
+        con.CancelReason__c = 'CancelReason__c';
+        
+        update con;
+        
+        con.MobilePhoneD__c = 'MobilePhoneD__c';
+        con.OtherPhoneD__c = 'OtherPhoneD__c';
+        con.FaxD__c = 'FaxD__c';
+        con.EmailD__c = 'EmailD__c@test.com';
+        con.PhoneD__c = 'PhoneD__c';
+        con.TitleD__c = 'TitleD__c';
+        con.Address1D__c = 'Address1D__c';
+        con.Address2D__c = 'Address2D__c';
+        con.Address3D__c = 'Address3D__c';
+        con.PostcodeD__c = '100111';
+        con.ContactStatusD__c = 'ContactStatusD__c';
+        con.CancelReasonD__c = 'CancelReasonD__c';
+        
+        update con;
+        
+        con.StatusD__c = 'Completed';
+        update con;
+        con.StatusD__c = 'Submit';
+        update con;
+        con.StatusD__c = 'Pass';
+        update con;
+        
+        con.StatusD__c = 'Reject';
+        update con;
+        
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ContactTriggerHandlerTest.cls-meta.xml b/scr/classes/ContactTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/ContactTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ControllerUtil.cls b/scr/classes/ControllerUtil.cls
new file mode 100644
index 0000000..7736d00
--- /dev/null
+++ b/scr/classes/ControllerUtil.cls
@@ -0,0 +1,105 @@
+global without sharing class ControllerUtil {
+    public ControllerUtil() {
+        Integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+
+    }
+
+    public static Pricebook2 getStandardPricebook() {
+        if (Test.isRunningTest()) {
+            return new Pricebook2(Id = Test.getStandardPricebookId(), Name = 'Standard Pricebook');
+        } else {
+            List<Pricebook2> pbs = [Select Id, Name From Pricebook2 where IsStandard = true];
+            if (pbs.size() > 0) {
+                return pbs[0];
+            } else {
+                return null;
+            }
+        }
+    }
+
+    public static void updateExpress(List<Loaner_Express__c> upLeList){
+        update upLeList;
+    }
+
+    public class myException extends Exception {}
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/ControllerUtil.cls-meta.xml b/scr/classes/ControllerUtil.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/ControllerUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ControllerUtilTest.cls b/scr/classes/ControllerUtilTest.cls
new file mode 100644
index 0000000..24e12c5
--- /dev/null
+++ b/scr/classes/ControllerUtilTest.cls
@@ -0,0 +1,8 @@
+@isTest
+private class ControllerUtilTest {
+	
+	@isTest static void test_ControllerUtil() {
+		ControllerUtil con = new ControllerUtil();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/ControllerUtilTest.cls-meta.xml b/scr/classes/ControllerUtilTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/ControllerUtilTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/CustContController.cls b/scr/classes/CustContController.cls
new file mode 100644
index 0000000..8c4c0bf
--- /dev/null
+++ b/scr/classes/CustContController.cls
@@ -0,0 +1,59 @@
+public with sharing class CustContController {
+	//鍚堟垚url
+	public String ccUrl { get; private set; }
+	//涓や釜鐢ㄦ潵鎷兼帴url
+	public String accid { get; private set; }
+	public String conid { get; private set; }
+	//鍒濆鍖�
+	public loaner_user__c lou { get; private set; }
+	public loaner_user__c lu { get; private set; }
+	//鍒ゆ柇
+	public String isOk {get; private set; }
+
+    public CustContController() {
+        accid = System.currentPageReference().getParameters().get('accid');
+        conid = System.currentPageReference().getParameters().get('conid');
+    }
+
+    public void init(){
+       
+    	lou = new loaner_user__c();
+        List<Account> accList = new List<Account>();
+        List<Contact> conList = new List<Contact>();
+        if (String.isNotBlank(accid)) {
+            accList = [select id from Account where id =: accid];    
+        }
+    	if (String.isNotBlank(conid)) {
+            conList = [select id from Contact where id =: conid];
+        }
+    	
+    	if(accList.size() >0){
+            lou.Customer__c = accid;
+        }
+
+        if(conList.size() > 0 ){
+            lou.Contact__c = conid;
+        }
+    }
+
+    public void getisOk(){
+        isOk = '';
+        //鍓嶅彴閫夌殑瀹㈡埛涓庤仈绯讳汉閮藉彲浠ュ彇鍒颁粬淇╃殑id锛岄�夋病閫夋病鍏崇郴锛屽彧闇�瑕佹煡璇㈡瘮杈冧粬淇╅兘琚�変腑鐨勬儏鍐典笅
+        Contact cont = new Contact();
+        if (String.isNotBlank(lou.Contact__c)) {
+           cont = [select AccountId from Contact where id =:lou.Contact__c]; 
+        }
+        System.debug(cont.AccountId);
+        if (cont.AccountId != null) {
+           if (String.isNotBlank(lou.Customer__c) && String.isNotBlank(lou.Contact__c)) {
+                isOk = cont.AccountId == lou.Customer__c ? '1' : '0';
+           }
+           if (String.isBlank(lou.Customer__c)) {
+            isOk = '2';
+           }
+        }else if (String.isNotBlank(lou.Customer__c)){
+            isOk = '1';
+        }
+        System.debug(isOk);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/CustContController.cls-meta.xml b/scr/classes/CustContController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/CustContController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DataLoadAccountController.cls b/scr/classes/DataLoadAccountController.cls
new file mode 100644
index 0000000..6c133a1
--- /dev/null
+++ b/scr/classes/DataLoadAccountController.cls
@@ -0,0 +1,1019 @@
+public with sharing class DataLoadAccountController {
+
+	public List<String> StringList {get; set;}
+
+	public String  campaignId {get; set;}
+
+	public List<CampaignRelationship__c> CRList {get; set;}
+
+	public List<AccountContactInfo> ACInfoList {get; set;}
+	public Blob contentFile { get; set; }
+	public String nameFile { get; set; }
+
+	public Boolean errorFlag { get; set; }
+	public String errorMessage {get; set;}
+
+    public Map<String, List<Contact>> upsertContactMap;
+    public Map<String, Account> upsertAccountMap;
+    public Map<String,Account> accountMap;
+    public Map<String,String> accountIsUpdateMap;
+    public Map<String,String> accountInDealerMap;
+
+
+    private Integer line_Account_ProductSegment = 0;//鍒嗛噹
+    private Integer line_Account_accountName = 1;//瀹㈡埛鍚�
+    private Integer line_Account_DivisionName_D = 2;//閮ㄩ棬
+    private Integer line_Account_approver = 3;//瀹℃壒浜�
+    private Integer line_Account_Province = 4;//鐪�
+    private Integer line_Account_CityD = 5;//甯�
+    private Integer line_Account_Address1D = 6;//瀹㈡埛鍦板潃
+    private Integer line_Account_PostCodeD = 7;//瀹㈡埛閭紪
+    private Integer line_Account_Sub_UseD = 8;//瀹㈡埛Sub_Use;
+    private Integer line_Account_EnglishNameD = 9;//瀹㈡埛鑻辨枃鍚嶇О(IE)
+    private Integer line_Account_CustomerSource = 10;//瀹㈡埛鏉ユ簮
+    private Integer line_Account_UserType = 11;//鐢ㄦ埛灞炴��
+    private Integer line_Account_TargetCustomer = 12;//瀹㈡埛绫诲瀷
+    private Integer line_Account_Remark = 13;//瀹㈡埛澶囨敞
+    private Integer line_Contact_LastName = 14;//鑱旂郴浜哄鍚�
+    private Integer line_Contact_Address1D = 15;//鑱旂郴浜哄湴鍧�
+    private Integer line_Contact_MobilePhoneD = 16;//鑱旂郴浜烘墜鏈�
+    private Integer line_Contact_PostcodeD = 17;//鑱旂郴浜洪偖缂�
+    private Integer line_Contact_Remark = 18;//鑱旂郴浜哄娉�
+    private Integer line_nineteen;
+
+    public String baseUrl { get; set; }
+
+	public DataLoadAccountController() {
+
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+		campaignId = System.currentPageReference().getParameters().get('campaignId');
+		ACInfoList = new List<AccountContactInfo>();
+	}
+
+	public PageReference init() {
+		ACInfoList = new List<AccountContactInfo>();
+		return null;
+	}
+
+	public PageReference csvRead() {
+
+		String strFile = '';
+		List<String> listFile = new List<String>();
+		errorFlag = false;
+		errormessage = null;
+
+        List<String> errormessageList = new List<String>();
+        Map<String, List<String>> errormessageMap = new Map<String, List<String>>();
+		try {
+			if (contentFile != null) {
+				strFile = contentFile.toString();
+				listFile = strFile.split('\n');
+			} else {
+				errorFlag = true;
+				errormessage = '璇诲彇鍐呭涓虹┖銆�';
+                errormessageList.add(errormessage);
+                errormessageMap.put('瀵煎叆鏂囦欢寮傚父', errormessageList);
+                Pageerrormessage(errormessageMap);
+				return null;
+			}
+		} catch (Exception ex) {
+			errorFlag = true;
+            errormessage = '璇诲彇鐨勬枃浠朵笉鏄疌SV鏂囦欢鎴朇SV鏂囦欢鐨勭紪鐮佷笉鏄疷TF-8';
+            errormessageList.add(errormessage);
+            errormessageMap.put('瀵煎叆鏂囦欢寮傚父', errormessageList);
+            Pageerrormessage(errormessageMap);
+			return null;
+		}
+
+		List<String[]> arrayFile = new List<String[]>();
+		String firstline = listFile[0];
+		if (firstline.indexOf('瀹㈡埛鍒嗛噹') < 0) {
+			errorFlag = true;
+			errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭��';
+            errormessageList.add(errormessage);
+            errormessageMap.put('瀵煎叆鏂囦欢寮傚父', errormessageList);
+            Pageerrormessage(errormessageMap);
+			return null;
+		} else {
+			String strReplace = '';
+			List<String> temp = strFile.split('"');
+			for (Integer i = 0; i < temp.size(); i++) {
+				if (math.mod(i, 2) == 1) {
+					temp[i] = temp[i].replace(',', '#%&');
+				}
+				strReplace += temp[i];
+			}
+			// system.debug('=====strReplace:' + strReplace);
+			List<String> listReplace = strReplace.split('\n');
+			for (String replace : listReplace) {
+				system.debug('=====replace:' + replace);
+				if (replace != '\r' && replace.length() > 0) {
+					replace = replace.replace('\r', '');
+					String[] a = replace.split(',', -1);
+					for (Integer i = 0; i < a.size(); i++) {
+						if (a[i].indexOf('#%&') > 0) {
+							a[i] = a[i].replace('#%&', ',');
+						}
+					}
+					// 楠岃瘉瀵煎叆鐨勬ā鏉挎湁澶氬皯鍒�
+					if (a.size() != 19) {
+						errorFlag = true;
+						errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭�侺ine锛�' + arrayFile.size();
+                        errormessageList.add(errormessage);
+                        errormessageMap.put('瀵煎叆鏂囦欢寮傚父', errormessageList);
+                        Pageerrormessage(errormessageMap);
+						return null;
+					}
+					
+					arrayFile.add(a);
+				}
+			}
+		}
+
+		if (arrayFile.size() > 1) {
+
+			checkFields(arrayFile);
+		}
+        
+		return null;
+	}
+
+    public PageReference save() {
+        system.debug('upsertAccountMap-----><----' + upsertAccountMap);
+
+        Savepoint sp = Database.setSavepoint();
+        // try {
+            List<CampaignRelationship__c> insertCampaignRelationshipList = new List<CampaignRelationship__c>();
+            if (upsertAccountMap != null && upsertAccountMap.size() > 0) {
+
+                // 淇濆瓨瀹㈡埛
+                upsert upsertAccountMap.values();
+                List<Contact> upsertContactList = new List<Contact>();
+                Map<String,Contact> insertContactMap = new Map<String,Contact>();
+                for (String accountkey : upsertAccountMap.keySet()) {
+                    String productSegment = upsertAccountMap.get(accountkey).ProductSegment__c;
+                    String accountId = upsertAccountMap.get(accountkey).Id;
+                    if (upsertContactMap != null && upsertContactMap.size() > 0) {
+                        if (upsertContactMap.containsKey(accountkey)) {
+                            // 缁欒仈绯讳汉璧嬪�煎鎴稩d
+                            for (Contact contact : upsertContactMap.get(accountkey)) {
+                                if (String.isNotBlank(contact.LastName)) {
+                                    contact.CampaignUpsertContact__c = true;
+                                    if (String.isBlank(contact.Id)) {
+                                        contact.AccountId = accountId;
+                                        upsertContactList.add(contact);
+                                    } else {
+                                        insertContactMap.put(contact.Id, contact);
+                                    }
+                                    
+                                    // upsertContactList.add(contact); 
+                                }
+                                
+                            }
+                        }
+                    }
+
+                    String accountName = upsertAccountMap.get(accountkey).FacilityNameD__c;
+                    String divisionName = upsertAccountMap.get(accountkey).DivisionName_D__c;
+                    String accountAssemblyName = accountName + divisionName;
+                    // 鑻ュ鎴峰凡瀛樺湪锛屽垱寤哄鎴�-甯傚満娲诲姩鍏崇郴锛岃嫢瀹㈡埛涓嶅瓨鍦紝閭d箞瀹㈡埛鍒涘缓瀹屾垚涔嬪悗锛屼細鍦╰rigger閲屽垱寤哄鎴�-甯傚満娲诲姩鍏崇郴
+                    if ( accountMap != null && accountMap.containsKey(accountAssemblyName)) {
+                        
+                        CampaignRelationship__c campaignRelationship = campaignRelationshipAssembly(accountId,productSegment);
+                        
+                        insertCampaignRelationshipList.add(campaignRelationship);
+                    }
+                    
+                }
+                
+
+                // 淇濆瓨鑱旂郴浜�
+                // if (upsertContactMap != null && upsertContactMap.size() > 0) {
+                //     // upsert upsertContactMap.values();
+                //     Integer Error01 = Integer.valueOf('TEST--->'+upsertContactMap);
+                // }
+                if (upsertContactList.size() > 0) {
+                    upsert upsertContactList;
+                }
+
+                if (insertContactMap != null && insertContactMap.size() >0) {
+                    update insertContactMap.values();
+                }
+            
+            } 
+            // 鑻ュ鎴峰凡鍦ㄤ唬鐞嗗晢涓嬶紝閭d箞鍒涘缓瀹㈡埛-甯傚満娲诲姩鍏崇郴
+            if (accountInDealerMap != null && accountInDealerMap.size() > 0) {
+
+                for (String accountId : accountInDealerMap.keySet()) {
+                    CampaignRelationship__c campaignRelationship = campaignRelationshipAssembly(accountId,accountInDealerMap.get(accountId));
+                    insertCampaignRelationshipList.add(campaignRelationship);
+                }
+            }
+
+            // 淇濆瓨瀹㈡埛-甯傚満娲诲姩鍏崇郴
+            if (insertCampaignRelationshipList.size() > 0) {
+                insert insertCampaignRelationshipList;
+            }
+        // } catch (Exception e) {
+        //     errorFlag = true;
+        //     ApexPages.addMessages(e);
+        //     Database.rollback(sp);
+        //     return  null;
+        // }
+        return null;
+    }
+    // 瀹㈡埛-甯傚満娲诲姩鍏崇郴 璧嬪��
+    public CampaignRelationship__c campaignRelationshipAssembly(String accountId,String productSegment){
+        CampaignRelationship__c result = new CampaignRelationship__c();
+        result.RelationshipAccount__c = accountId;
+        result.RelationshipCampaign__c = campaignId;
+        result.RelationshipProductSegment__c = productSegment;
+        return result;
+    }
+    // 鏁版嵁楠岃瘉鍙婃暟鎹嫾瑁�
+	public void checkFields(List<String[]> arrayFile) {
+		Integer no = 1;
+		AccountContactInfo ifno = new AccountContactInfo(no);
+        // 鏌ユ壘瀹℃壒浜�
+		Map<String,User> userMap = getUser(arrayFile);
+
+        accountMap = new Map<String,Account>();
+        // 鏍规嵁瀵煎叆鏂囦欢鐨勫鎴峰悕绉颁笌閮ㄩ棬鍚嶇О浠ュ強鍒嗛噹锛屽幓绯荤粺涓煡鎵惧競鍦洪儴鍒涘缓鐨勫鎴�
+        accountMap = getAccountMap(arrayFile);
+        accountIsUpdateMap = new Map<String,String>();
+        // 鏌ユ壘瀹㈡埛涓嬬殑瀹㈡埛鍥㈤槦鏄惁鏈変唬鐞嗗晢鐢ㄦ埛锛屽�熸鍒ゆ柇瀹㈡埛鏄惁鍦ㄤ唬鐞嗗晢涓�
+        accountIsUpdateMap = getAccountTeamMemberList(accountMap);
+        // 鏌ユ壘鑱旂郴浜�
+        Map<String,Contact> contactMap = getContactMap(accountMap);
+        // 瀹㈡埛鍦ㄤ唬鐞嗗晢涓�
+        accountInDealerMap = new Map<String,String>();
+
+
+		
+		String tem = '';
+
+        upsertContactMap = new Map<String, List<Contact>>();
+        upsertAccountMap = new Map<String, Account>();
+		Map<String, List<String>> errormessageMap = new Map<String, List<String>>();
+		for (Integer line = 1; line < arrayFile.size(); line++) {
+			List<Contact> countList = new List<Contact>();
+			Account account = new Account();
+			Contact contact = new Contact();
+			// 瀹㈡埛鍒嗛噹涓嶄负绌�
+            if (String.isNotBlank(arrayFile[line][line_Account_ProductSegment])) {
+
+				tem = arrayFile[line][line_Account_ProductSegment];
+                String accountName= arrayFile[line][line_Account_accountName];
+                String divisionName= arrayFile[line][line_Account_DivisionName_D];
+				if (String.isNotBlank(accountName) && String.isNotBlank(divisionName)) {
+					tem += ':' + accountName + divisionName;
+				} else {
+                    Integer fileNo = line+1;
+					List<String> errormessageList = new List<String>();
+					errormessageList.add( '瀵煎叆鏂囦欢绗� [ ' + fileNo + ' ] 琛� 瀹㈡埛鍚嶇О鎴栭儴闂ㄥ悕绉颁负绌猴紝璇风‘璁わ紝姝ゆ潯瀹㈡埛涓庤仈绯讳汉璺宠繃');
+                    tem += '-' + fileNo;
+					errormessageMap.put(tem,errormessageList);
+					continue;
+				}
+                // 楠岃瘉瀹㈡埛鏄惁绗﹀悎瑙勫垯
+				if (accountFieldCheck(arrayFile[line], errormessageMap, tem,userMap)) {
+
+					account = accountAssembly(arrayFile[line],userMap);
+                    String managementCode  = '';
+                    
+                    if (accountMap != null && accountMap.size() > 0 ) {
+                        String accountId = getAccountId(accountMap,arrayFile[line], errormessageMap, tem);
+                        if (String.isNotBlank(accountId)) {
+                            account.Id = accountId;
+                            
+                            String key = accountName + divisionName;
+                            managementCode = accountMap.get(key).ManagementCode_F__c;
+                        }
+                    }
+
+                    // 姝ゅ闇�瑕佸鐞嗛噸鍚嶅鎴�
+					if (!upsertAccountMap.containsKey(tem)) {
+                        // 鍒ゆ柇瀹㈡埛鏄惁宸插湪浠g悊鍟嗕笅锛屽湪浠g悊鍟嗕笅涓嶆洿鏂板鎴�
+                        if (accountIsUpdateMap != null && accountIsUpdateMap.size() > 0) {
+                            // 瀹㈡埛鏇存柊
+                            if (String.isNotBlank(account.Id)) {
+                                // 鍒ゆ柇瀹㈡埛鏄惁宸插湪浠g悊鍟嗕笅锛岃嫢涓嶅湪浠g悊鍟嗕笅鏇存柊瀹㈡埛鍩烘湰淇℃伅
+                                if (!accountIsUpdateMap.containsKey(account.Id)) {
+                                    upsertAccountMap.put(tem, account);
+                                } else {
+                                    
+                                    accountInDealerMap.put(account.Id, tem.split(':')[0]);
+                                    List<String> errormessageList = new List<String>();
+                                    errormessage = '瀹㈡埛鍚嶏細' + tem.split(':')[1] +divisionName+ ' 瀹㈡埛缂栫爜 [ '+managementCode+' ] 宸插湪浠g悊鍟嗕笅锛涙鏉″鎴蜂笌鑱旂郴浜轰笉浼氳鏇存柊锛屼粎鍒涘缓 瀹㈡埛-甯傚満娲诲姩鍏崇郴';
+                                    errormessageList.add(errormessage);
+                                    errormessageMap.put(tem, errormessageList);
+                                    // 鑻ュ鎴峰湪浠g悊鍟嗕笅 锛屽鎴峰鍏ラ〉闈細鏄剧ず璇ュ鎴风殑淇℃伅锛屼絾鏄笉浼氭洿鏂板鎴�
+                                    // continue;
+                                }
+                            } else {
+                                // 瀹㈡埛鏂板
+                                upsertAccountMap.put(tem, account);
+                            }
+                            
+                        } else {
+                            // 瀹㈡埛鏂板
+                            upsertAccountMap.put(tem, account);
+                        }
+                        
+                    } else {
+                        List<String> errormessageList = new List<String>();
+                        errormessage = '鍒嗛噹锛�'+ tem.split(':')[0] + '锛屽鎴峰悕锛�' + tem.split(':')[1] + ' 閲嶅悕锛屾鏉″鎴蜂笌鑱旂郴浜鸿烦杩�';
+                        errormessageList.add(errormessage);
+                        tem += 'Error';
+                        errormessageMap.put(tem, errormessageList);
+                        system.debug('tem------>' + tem);
+                        continue;
+                        
+                    }
+                    // 鍒ゆ柇涓庡鎴峰悓涓�琛岀殑鑱旂郴浜哄瓧娈垫槸鍚﹂兘涓虹┖鍊�
+					if (FirstContactIsNull(arrayFile[line])) {
+	                    ifno = new AccountContactInfo(no, account);
+	                    ACInfoList.add(ifno);
+	                    no++;
+					} else {
+                        // 妫�鏌ヨ仈绯讳汉瀛楁鏄惁鏈夊紓甯�
+	                    if (contactFieldCheck(arrayFile[line], errormessageMap, tem)) {
+	                        contact = contactAssembly(arrayFile[line], tem);
+                            // 鑻ュ鎴峰湪浠g悊鍟嗕笅 瀹㈡埛瀵煎叆椤甸潰浼氭樉绀鸿仈绯讳汉淇℃伅锛屼絾鏄笉浼氭洿鏂拌仈绯讳汉淇℃伅
+                            if (accountInDealerMap != null && accountInDealerMap.size() > 0 && accountInDealerMap.containsKey(account.Id)) {
+                                ifno = new AccountContactInfo(no, account, contact);
+                                ACInfoList.add(ifno);
+                                no++;
+                                continue;
+                            }
+                            if (contactMap != null && contactMap.size() >0) {
+                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
+                                if (String.isNotBlank(contactId)) {
+                                    contact.Id = contactId;
+                                }
+                            }
+	                        countList.add(contact);
+	                        upsertContactMap.put(tem, countList);
+	                        ifno = new AccountContactInfo(no, account, contact);
+	                        ACInfoList.add(ifno);
+	                        no++;
+	                    } else {
+							errormessageMap.putAll(errormessageMap);
+						}
+					}
+				} else {
+					errormessageMap.putAll(errormessageMap);
+				}
+
+				system.debug('tem---->' + tem);
+			} else {
+                if (upsertAccountMap.containsKey(tem)) {
+                    if (contactFieldCheck(arrayFile[line], errormessageMap, tem)) {
+                        // 灏嗗悓涓�瀹㈡埛涓嬬殑鑱旂郴浜烘斁鍒板悓涓�涓仈绯讳汉闆嗗悎涓�
+                        if (upsertContactMap.containsKey(tem)) {
+                            contact = contactAssembly(arrayFile[line], tem);
+                            account = upsertAccountMap.get(tem);
+                            if (contactMap != null && contactMap.size() >0) {
+                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
+                                if (String.isNotBlank(contactId)) {
+                                    contact.Id = contactId;
+                                }
+                            }
+                            List<Contact> contacts = upsertContactMap.get(tem);
+                            contacts.add(contact);
+                            upsertContactMap.put(tem, contacts);
+                            
+                            ifno = new AccountContactInfo(no, account, contact);
+                            ACInfoList.add(ifno);
+                            no++;
+                        } else {
+                            // 鍚屼竴瀹㈡埛涓嬬殑鍓嶉潰鐨勮仈绯讳汉閮戒负绌烘垨楠岃瘉涓嶉�氳繃銆傚皢鍓╀綑绗﹀悎瑙勫垯鐨勬斁鍏ヨ仈绯讳汉闆嗗悎涓��
+                            contact = contactAssembly(arrayFile[line], tem);
+                            if (contactMap != null && contactMap.size() >0) {
+                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
+                                if (String.isNotBlank(contactId)) {
+                                    contact.Id = contactId;
+                                }
+                            }
+                            countList.add(contact);
+                            upsertContactMap.put(tem, countList);
+                            account = upsertAccountMap.get(tem);
+                            ifno = new AccountContactInfo(no, account, contact);
+                            ACInfoList.add(ifno);
+                            no++;
+                        }
+
+                    } else {
+                        errormessageMap.putAll(errormessageMap);
+                    }
+                }
+				
+
+			}
+		}
+        // 寮傚父淇℃伅椤甸潰灞曠ず
+		if (errormessageMap != null && errormessageMap.size() > 0) {
+            Pageerrormessage(errormessageMap);
+		
+		}
+	}
+    // 寮傚父淇℃伅
+    public void Pageerrormessage(Map<String, List<String>> errormessageMap) {
+
+        errorFlag = true;
+        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '浠ヤ笅鏁版嵁鍚湁寮傚父淇℃伅锛岃纭锛侊紒锛�'));
+        for (String key :errormessageMap.keySet()) {
+            if (key.indexOf(':') > 0) {
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '瀹㈡埛 '+ key.split(':')[1] + '锛�'));
+            } else {
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '瀹㈡埛 '+ key + '锛�'));
+            }
+            for (String errorm :errormessageMap.get(key)){
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '--->'  + errorm)); 
+            }
+            
+        }
+
+    }
+    // 楠岃瘉涓庡鎴峰悓涓�琛岀殑鑱旂郴浜哄瓧娈垫槸鍚﹂兘涓虹┖
+    public Boolean FirstContactIsNull(String[] strList){
+        Boolean contactNameflag = String.isBlank(strList[line_Contact_LastName]);
+        Boolean contactAddrflag = String.isBlank(strList[line_Contact_Address1D]);
+        Boolean contactPhoneflag = String.isBlank(strList[line_Contact_MobilePhoneD]);
+        Boolean contactPostflag = String.isBlank(strList[line_Contact_PostcodeD]);
+
+        if (contactNameflag && contactAddrflag && contactPhoneflag && contactPostflag) {
+            return true;
+        }
+        return false;
+    }
+
+
+    // 涓鸿仈绯讳汉瀛楁璧嬪��
+	public Contact contactAssembly(String[] strList,String tem) {
+
+		Contact result = new Contact();
+		result.LastName = strList[line_Contact_LastName];
+		result.FirstName = null;
+		result.Address1D__c = strList[line_Contact_Address1D];
+		result.MobilePhoneD__c = strList[line_Contact_MobilePhoneD];
+		result.PostcodeD__c = strList[line_Contact_PostcodeD];
+        result.Remark__c = strList[line_Contact_Remark];
+		result.ContactStatusD__c = 'Active';
+        //result.StatusD__c = 'Pass';
+		if (tem.split(':')[0] == 'IE') {
+			result.ProductSegmentIE__c = true;
+		} else if (tem.split(':')[0] == 'RVI') {	
+			result.ProductSegmentRVI__c = true;
+		} else if (tem.split(':')[0] == 'NDT') {
+			result.ProductSegmentNDT__c = true;
+		} else if (tem.split(':')[0] == 'ANI') {
+			result.ProductSegmentANI__c = true;
+		}  
+		
+		return result;
+	}
+    // 涓哄鎴峰瓧娈佃祴鍊�
+	public Account accountAssembly(String[] strList,Map<String,User> userMap) {
+
+		Account result = new Account();
+        String productSegment = strList[line_Account_ProductSegment];
+		result.ProductSegment__c = productSegment;
+		result.FacilityNameD__c = strList[line_Account_accountName];
+        result.FacilityName__c = strList[line_Account_accountName];
+		result.Name = '*';
+		result.DivisionName_D__c = strList[line_Account_DivisionName_D];
+		String approver = strList[line_Account_approver].replaceAll(' ', '');
+		result.DealerSelectOwner__c = userMap.get(approver).Id;
+		result.Province__c = strList[line_Account_Province];
+		result.CityD__c = strList[line_Account_CityD];
+		result.Address1D__c = strList[line_Account_Address1D];
+		result.PostCodeD__c = strList[line_Account_PostCodeD];
+		String subUse = '';
+        if ((productSegment != 'IE') && '姹借溅'.equals(strList[line_Account_Sub_UseD])) {
+            subUse = 'Automotive';
+        } else if ('鍏朵粬'.equals(strList[line_Account_Sub_UseD])){
+            subUse = 'Others';
+        } else {
+            subUse = strList[line_Account_Sub_UseD];
+        }
+		result.Sub_UseD__c = subUse;
+
+		result.AccountCampaign__c = campaignId;
+		if ('IE'.equals(productSegment)) {
+			result.EnglishNameD__c = strList[line_Account_EnglishNameD];
+			result.CustomerSource__c = strList[line_Account_CustomerSource];
+			result.UserType__c = strList[line_Account_UserType];
+			result.TargetCustomer__c = strList[line_Account_TargetCustomer];
+            result.Sub_UseA__c = subUse;
+            if(subUse.startsWith('Compo')){
+                result.compo_Acc__c = 'COMPO瀹㈡埛';
+            }else{
+                result.compo_Acc__c = '闈濩OMPO瀹㈡埛';
+            }
+		}
+		
+        result.Remark__c = strList[line_Account_Remark];
+
+        result.AccountStatusD__c = 'Active';
+
+        if (productSegment == 'IE') {
+            result.recordTypeId = '01228000000TdF6';
+        } else if (productSegment == 'RVI') {
+            result.recordTypeId = '01228000000TdFB';
+        } else if (productSegment == 'NDT') {
+            result.recordTypeId = '01228000000TdFG';
+        } else if (productSegment == 'ANI') {
+            result.recordTypeId = '01228000000TdFL';
+        }
+		return result;
+	}
+    // 鑾峰彇瀹℃壒浜�
+	public Map<String,User> getUser(List<String[]> arrayFile){
+		Map<String,User> result = new Map<String,User>();
+		List<String> approverList = new List<String>();
+		//鏌ユ壘瀹℃壒浜烘槸鍚﹀瓨鍦�
+		for (Integer line = 1; line < arrayFile.size(); line++) {
+		    //瀹㈡埛鍒嗛噹
+		    Boolean productSegment = String.isBlank(arrayFile[line][line_Account_ProductSegment]);
+		    //瀹℃壒浜�
+		    Boolean approver = String.isBlank(arrayFile[line][line_Account_approver]);
+		    if (!productSegment && !approver) {
+		        approverList.add(arrayFile[line][line_Account_approver]);
+		    }
+		}
+
+		if (approverList.size() > 0) {
+
+			List<User> userList = [SELECT id,Name,LastName,FirstName 
+								   FROM User ];
+
+			if (userList.size() > 0) {
+				for (User user :userList) {
+					String firstName = String.isBlank(user.FirstName) ? '' :user.FirstName;
+					String name = user.LastName + firstName;
+					result.put(name,user);
+				}
+			}
+		}
+
+		return result;
+	}
+    // 瀵煎叆鏂囦欢瀹㈡埛瀛楁楠岃瘉
+	public Boolean accountFieldCheck(String[] strList, Map<String, List<String>> errormessageMap, String tem,Map<String,User> userMap) {
+		//瀹㈡埛鍚嶇О
+		Boolean dealerNameflag = String.isBlank(strList[line_Account_accountName]);
+
+		//閮ㄩ棬鍚嶇О
+		Boolean deptNameflag = String.isBlank(strList[line_Account_DivisionName_D]);
+		//瀹℃壒浜�
+		Boolean approverflag = String.isBlank(strList[line_Account_approver]);
+		//鐪�
+		Boolean provinceflag = String.isBlank(strList[line_Account_Province]);
+		//鍩庡競
+		Boolean cityflag = String.isBlank(strList[line_Account_CityD]);
+		//瀹㈡埛鍦板潃
+		Boolean addressflag = String.isBlank(strList[line_Account_Address1D]);
+		//閭紪
+		Boolean postflag = String.isBlank(strList[line_Account_PostCodeD]);
+		//Sub Use
+		Boolean sub_Useflag = String.isBlank(strList[line_Account_Sub_UseD]);
+		//瀹㈡埛鑻辨枃鍚嶇О(IE楠岃瘉)
+		Boolean accountEnglishNameflag = String.isBlank(strList[line_Account_EnglishNameD]);
+		//瀹㈡埛鏉ユ簮(IE楠岃瘉)
+		Boolean customerSourceflag = String.isBlank(strList[line_Account_CustomerSource]);
+		//鐢ㄦ埛灞炴��(IE楠岃瘉)
+		Boolean useRattributeflag = String.isBlank(strList[line_Account_UserType]);
+        //瀹㈡埛绫诲瀷(IE楠岃瘉)
+		Boolean targetCustomerflag = String.isBlank(strList[line_Account_TargetCustomer]);
+
+		Boolean temflag = true;
+		String errormessage = '';
+		if (tem.indexOf(':') > 0) {
+			errormessage = tem.split(':')[1] + '锛�';
+		} else {
+			errormessage = tem;
+		}
+
+		List<String> errormessageList = new List<String>();
+
+		if (approverflag) {
+			errormessage += ' 瀹㈡埛瀹℃壒浜轰笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+			temflag = false;
+		} else {
+			//楠岃瘉瀹℃壒浜烘槸鍚﹀瓨鍦�
+			String approver = strList[line_Account_approver].replaceAll(' ', '');
+
+			if (!userMap.containsKey(approver)){
+				errormessage += ' 瀹㈡埛瀹℃壒浜� ['+strList[line_Account_approver]+'] 涓嶅瓨鍦紝璇风‘璁わ紱\n';
+				temflag = false;
+			} 
+		}
+		if (provinceflag) {
+			errormessage += ' 瀹㈡埛鐪佷笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+			temflag = false;
+		} else {
+			
+			Schema.DescribeFieldResult fieldResult = Account.Province__c.getDescribe();
+
+			Map<String,String> accountProvinceMap =  getPickListValuesMap(fieldResult);
+			String accountProvince = strList[line_Account_Province];
+			if (!accountProvinceMap.containsKey(accountProvince)) {
+				errormessage += ' 瀹㈡埛鐪佺殑鍊煎紓甯革紝[ '+accountProvince+' ]璇风‘璁わ紱\n';
+				temflag = false;
+			}
+		}
+		if (cityflag) {
+			errormessage += ' 瀹㈡埛鍩庡競涓嶈兘涓虹┖锛岃纭锛沑n';
+			temflag = false;
+		}
+		if (addressflag) {
+			errormessage += ' 瀹㈡埛鍦板潃涓嶈兘涓虹┖锛岃纭锛沑n';
+			temflag = false;
+		}
+		if (postflag) {
+			errormessage += ' 瀹㈡埛閭斂缂栫爜涓嶈兘涓虹┖锛岃纭锛沑n';
+			temflag = false;
+		} else {
+            Pattern pt = Pattern.compile('[0-9]\\d{5}(?!\\d)');
+            Matcher mc = pt.matcher(strList[line_Account_PostCodeD]);
+            if(!mc.matches()) {
+                errormessage += ' 瀹㈡埛閭斂缂栫爜涓嶆槸6浣嶆暟瀛楋紝[ '+strList[line_Account_PostCodeD]+' ]璇风‘璁わ紱\n';
+                temflag = false;
+            }
+		}
+		if (sub_Useflag) {
+			errormessage += ' Sub Use涓嶈兘涓虹┖锛岃纭锛沑n';
+			temflag = false;
+		} else {
+            
+            // 鍒ゆ柇Sub Use鏄惁绗﹀悎鍒嗛噹鎵�閫夊��
+            String segment = strList[line_Account_ProductSegment];
+            String subUse = strList[line_Account_Sub_UseD];
+            String key = segment + ':' + subUse;
+            if (!SegmentSubUseMap.containsKey(key)) {
+                String accountName = strList[line_Account_accountName];
+                errormessage += accountName +'- Sub Use [ '+subUse + ' ] 鐨勫�兼棤鏁堬紝璇风‘璁わ紱\n';
+                temflag = false;
+            }
+        }
+		if (strList[line_Account_ProductSegment] == 'IE') {
+			if (accountEnglishNameflag) {
+				errormessage += ' 瀹㈡埛鐨勮嫳鏂囧悕绉颁笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+				temflag = false;
+			}
+			if (customerSourceflag) {
+				errormessage += ' 瀹㈡埛鐨勫鎴锋潵婧愪笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+				temflag = false;
+			} else {
+				Schema.DescribeFieldResult fieldResult = Account.CustomerSource__c.getDescribe();
+
+				Map<String,String> sourceMap =  getPickListValuesMap(fieldResult);
+				String customerSource = strList[line_Account_CustomerSource];
+				if (!sourceMap.containsKey(customerSource)) {
+					errormessage += ' 瀹㈡埛鐨勫鎴锋潵婧愬�煎紓甯革紝[ '+customerSource+' ]璇风‘璁わ紱\n';
+					temflag = false;
+				}
+			}
+			if (useRattributeflag) {
+				errormessage += ' 瀹㈡埛鐨勭敤鎴峰睘鎬т笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+				temflag = false;
+			} else {
+				Schema.DescribeFieldResult fieldResult = Account.UserType__c.getDescribe();
+
+				Map<String,String> userTypeMap =  getPickListValuesMap(fieldResult);
+				String userType = strList[line_Account_UserType];
+				if (!userTypeMap.containsKey(userType)) {
+					errormessage += ' 瀹㈡埛鐨勭敤鎴峰睘鎬у�煎紓甯革紝[ '+userType+' ]璇风‘璁わ紱\n';
+					temflag = false;
+				}
+			}
+
+			if (targetCustomerflag) {
+				errormessage += ' 瀹㈡埛鐨勫鎴风被鍨嬩笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+				temflag = false;
+			} else {
+				Schema.DescribeFieldResult fieldResult = Account.TargetCustomer__c.getDescribe();
+
+				Map<String,String> targetCustomerMap =  getPickListValuesMap(fieldResult);
+				String targetCustomer = strList[line_Account_TargetCustomer];
+				if (!targetCustomerMap.containsKey(targetCustomer)) {
+					errormessage += ' 瀹㈡埛鐨勫鎴风被鍨嬪�煎紓甯革紝[ '+targetCustomer+' ]璇风‘璁わ紱\n';
+					temflag = false;
+				}
+			}
+
+		}
+		if (temflag) {
+			return true;
+
+		} else {
+			errormessageList.add(errormessage);
+			errormessageMap.put(tem, errormessageList);
+			return temflag;
+		}
+
+
+	}
+    // 鑾峰彇瀹㈡埛Id
+    public String getAccountId(Map<String,Account> accountMap,String[] strList,Map<String, List<String>> errormessageMap, String tem) {
+        List<String> errormessageList = new List<String>();
+        if (errormessageMap != null && errormessageMap.size() >0 && errormessageMap.containsKey(tem)) {
+            errormessageList = errormessageMap.get(tem);
+        }
+
+        String result = '';
+        String accountName = strList[line_Account_accountName];
+        String divisionName = strList[line_Account_DivisionName_D];
+        String name = accountName + divisionName;
+
+        if (accountMap.containsKey(name)) {
+            result = accountMap.get(name).Id;
+            String managementCode  = accountMap.get(name).ManagementCode_F__c;
+            String errormessage = '瀹㈡埛锛�'+name+' 绯荤粺涓凡瀛樺湪锛屽鎴风紪鐮� [ '+managementCode+' ]锛屽皢鏇存柊姝ゅ鎴凤紝璇锋敞鎰忥紱\n';
+            errormessageList.add(errormessage);
+            errormessageMap.put(tem,errormessageList);
+        }
+
+
+        
+        return result;
+
+    }
+    // 鑾峰彇鑱旂郴浜篒d
+    public String getContactId(Account account, Map<String,Contact> contactMap,String[] strList,Map<String, List<String>> errormessageMap, String tem) {
+        List<String> errormessageList = new List<String>();
+        if (errormessageMap != null && errormessageMap.size() >0 &&  errormessageMap.containsKey(tem)) {
+            errormessageList = errormessageMap.get(tem);
+        }
+        String result = '';
+        String accountName = account.FacilityNameD__c;
+        String divisionName = account.DivisionName_D__c;
+        String accountAssemblyName = accountName + divisionName;
+
+        String contactlastName = strList[line_Contact_LastName].replaceAll(' ', '');
+
+        String key = accountAssemblyName + contactlastName;
+        if (contactMap.containsKey(key)) {
+            result = contactMap.get(key).Id;
+            String managementCode  = contactMap.get(key).ManagementCode_F__c;
+            String errormessage = '鑱旂郴浜猴細'+contactlastName+' 绯荤粺涓凡瀛樺湪锛岃仈绯讳汉缂栫爜 [ '+managementCode+' ]锛屽皢鏇存柊姝よ仈绯讳汉锛岃娉ㄦ剰锛沑n';
+            errormessageList.add(errormessage);
+            errormessageMap.put(tem,errormessageList);
+        }
+        return result;
+    }
+    // 鑾峰彇甯傚満鎴樼暐閮ㄥ垱寤虹殑瀹㈡埛
+    public Map<String,Account> getAccountMap( List<String[]> arrayFile) {
+
+        Map<String,Account> result = new Map<String,Account>();
+        List<String> accountNameList = new List<String>();
+        String productSegment = '';
+        for (Integer line = 1; line < arrayFile.size(); line++) {
+            if (String.isNotBlank(arrayFile[line][line_Account_ProductSegment])) {
+                productSegment = arrayFile[line][line_Account_ProductSegment];
+                String accountName = arrayFile[line][line_Account_accountName];
+                String divisionName = arrayFile[line][line_Account_DivisionName_D];
+                if (String.isNotBlank(accountName) && String.isNotBlank(divisionName)) {
+                    String name = accountName + divisionName;
+                    accountNameList.add(name);
+                }
+            }
+        }
+
+        if (accountNameList != null && accountNameList.size() > 0) {
+            
+             List<Account> accountList =    [SELECT id,Name,DivisionName_D__c,ProductSegment__c,createddate,OwnerId ,ManagementCode_F__c from Account where MarketingStrategyCreated__c = true AND Name = :accountNameList AND ProductSegment__c = :productSegment];
+
+            if ( accountList.size() > 0) {
+                for (Account account :accountList) {
+                    result.put(account.Name, account);
+                }
+            }
+        }
+
+        return result;
+    }
+    // 鏌ユ壘甯傚満鎴樼暐閮ㄥ垱寤虹殑瀹㈡埛涓嬬殑鑱旂郴浜�
+    public Map<String,Contact> getContactMap(Map<String,Account> accountMap) {
+
+        if (accountMap != null && accountMap.size() > 0) {
+
+            Map<String,Contact> result = new Map<String,Contact>();
+            List<String> accountIdList = new List<String>(); 
+            for (String name : accountMap.keySet()) {
+
+                String accountId = accountMap.get(name).Id;
+                accountId = accountId.subString(0,15);
+                accountIdList.add(accountId);
+            }
+
+            List<Contact> contactList = [ SELECT Id,ManagementCode_F__c,Name__c,AccountId__c,Account.Name from Contact where AccountId__c In :accountIdList Order by AccountId__c,Id];
+
+            if (contactList.size() > 0) {
+
+                for (Contact contact :contactList) {
+                    String accountNameAndContactName = contact.Account.Name + contact.Name__c;
+                    result.put(accountNameAndContactName,contact);
+                }
+            }
+            return result;
+        }
+
+        return null;
+        
+    }
+
+    // 鏌ユ壘瀹㈡埛涓嬬殑瀹㈡埛鍥㈤槦涓紝鏄惁鏈変唬鐞嗗晢鐢ㄦ埛
+    public Map<String,String> getAccountTeamMemberList(Map<String,Account> accountMap) {
+        
+        if (accountMap != null && accountMap.size() > 0) {
+            Map<String,String> result = new Map<String,String>();
+            List<String> accountIdList = new List<String>(); 
+            for (String name : accountMap.keySet()) {
+
+                String accountId = accountMap.get(name).Id;
+                accountIdList.add(accountId);
+            }
+
+            List<AccountTeamMember> accountTeamMemberList = [ SELECT Id, AccountId,Account.Name, UserId,User.User_Type__c FROM AccountTeamMember where User.User_Type__c = 'PowerPartner' AND AccountId in :accountIdList];
+            if (accountTeamMemberList.size() > 0) {
+                for (AccountTeamMember accountTeamMember :accountTeamMemberList) {
+                    result.put(accountTeamMember.AccountId,accountTeamMember.UserId);
+                }
+                
+            }
+            return result;
+        }
+
+        return null;
+    }
+
+    // 楠岃瘉瀵煎叆鏂囦欢鐨勮仈绯讳汉鏁版嵁
+	public Boolean contactFieldCheck(String[] strList, Map<String, List<String>> errormessageMap, String tem) {
+
+		Boolean contactNameflag = String.isBlank(strList[line_Contact_LastName]);
+		Boolean contactAddrflag = String.isBlank(strList[line_Contact_Address1D]);
+		Boolean contactPhoneflag = String.isBlank(strList[line_Contact_MobilePhoneD]);
+		Boolean contactPostflag = String.isBlank(strList[line_Contact_PostcodeD]);
+		
+		List<String> errormessageList = new List<String>();
+		if (errormessageMap != null && errormessageMap.size() > 0 && errormessageMap.containsKey(tem)) {
+            errormessageList = errormessageMap.get(tem);
+        }
+		if (contactNameflag && ( !contactAddrflag || !contactPhoneflag || !contactPostflag)) {
+			String errormessage = '鑱旂郴浜虹殑濮撴皬涓嶈兘涓虹┖锛岃纭锛沑n';
+			errormessageList.add(errormessage);
+			errormessageMap.put(tem, errormessageList);
+			return false;
+		} else if (!contactNameflag) {
+			Boolean temflag = true;
+			String contactName = strList[line_Contact_LastName];
+			String errormessage = contactName + '锛�';
+			if (contactAddrflag) {
+				errormessage += ' 鑱旂郴浜哄湴鍧�涓嶈兘涓虹┖锛岃纭锛沑n';
+				temflag = false;
+			}
+			if (contactPhoneflag) {
+				errormessage += ' 鑱旂郴浜烘墜鏈轰笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+				temflag = false;
+			}
+			if (contactPostflag) {
+				errormessage += ' 鑱旂郴浜洪偖鏀跨紪鐮佷笉鑳戒负绌猴紝璇风‘璁わ紱\n';
+				temflag = false;
+			} else {
+                Pattern pt = Pattern.compile('[0-9]\\d{5}(?!\\d)');
+                Matcher mc = pt.matcher(strList[line_Contact_PostcodeD]);
+                if(!mc.matches()) {
+                    errormessage += ' 鑱旂郴浜洪偖鏀跨紪鐮佷笉鏄�6浣嶆暟瀛楋紝[ '+strList[line_Contact_PostcodeD]+' ]璇风‘璁わ紱\n';
+                    temflag = false;
+                }
+            }
+
+			if (temflag) {
+				return true;
+			} else {
+				errormessageList.add(errormessage);
+				errormessageMap.put(tem, errormessageList);
+				return temflag;
+			}
+
+		} else {
+			return false;
+		}
+
+	}
+
+	class AccountContactInfo {
+		public Integer lineNo { get; set; }
+		public Account accountpage {get; set;}
+
+		public Contact contactpage {get; set;}
+
+		public AccountContactInfo(Integer line) {
+
+		}
+        // 瀹㈡埛鏁版嵁姝e父浣嗕笌瀹㈡埛鍚屼竴琛岀殑鑱旂郴浜烘暟鎹紓甯�
+        public AccountContactInfo(Integer line, Account account) {
+            lineNo = line;
+            accountpage = account;
+        }
+        // 瀹㈡埛鏁版嵁涓庡鎴峰悓涓�琛岀殑鑱旂郴浜烘暟鎹兘姝e父
+		public AccountContactInfo(Integer line, Account account, Contact contact) {
+			lineNo = line;
+			accountpage = account;
+			contactpage = contact;
+		}
+	}
+	/**
+     * 鑾峰彇涓�涓璞℃煇涓�夐」鍒楄〃鐨勫叏閮ㄥ��
+     * @Author   XHL
+     * @DateTime 2019-09-18
+     * @param    fieldResult Schema.DescribeFieldResult fieldResult = Account.Use__c.getDescribe();
+     *                       渚嬶細鑾峰彇瀹㈡埛Use瀛楁閫夐」鍒楄〃鐨勫��
+     * @return               [description]
+     */
+    public  Map<String,String> getPickListValuesMap(Schema.DescribeFieldResult fieldResult){
+        Map<String,String> pickListValuesMap= new Map<String,String>();
+        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
+        for( Schema.PicklistEntry pickListVal : ple)
+        {
+            pickListValuesMap.put(pickListVal.getValue(),pickListVal.getLabel());
+        }
+        return pickListValuesMap;
+    }
+
+    // 楠岃瘉鍚勪釜鍒嗛噹鐨剆ub Use鏄惁绗﹀悎瑕佹眰
+    private  Map<String, String> SegmentSubUseMap = new Map<String, String> {
+        // IE
+        'IE:LED' => 'LED',
+        'IE:FPD' => 'FPD',
+        'IE:鍗婂浣�' => '鍗婂浣�',
+        'IE:鐢靛瓙閮ㄥ搧' => '鐢靛瓙閮ㄥ搧',
+        'IE:澶槼鑳�' => '澶槼鑳�',
+        'IE:鐢靛瓙绫籣鍏朵粬' => '鐢靛瓙绫籣鍏朵粬',
+        'IE:閲戝睘' => '閲戝睘',
+        'IE:姹借溅' => '姹借溅',
+        'IE:鐭虫补鍦拌川' => '鐭虫补鍦拌川',
+        'IE:浜旈噾妯″叿' => '浜旈噾妯″叿',
+        'IE:閲嶅伐璁惧' => '閲嶅伐璁惧',
+        'IE:鏉愭枡绫籣鍏朵粬' => '鏉愭枡绫籣鍏朵粬',
+        // ANI
+        'ANI:鍏朵粬' => '鍏朵粬',
+        'ANI:搴熸棫閲戝睘' => '搴熸棫閲戝睘',
+        'ANI:鐐奸挗鍘�' => '鐐奸挗鍘�',
+        'ANI:PMI-鐭冲寲琛屼笟' => 'PMI-鐭冲寲琛屼笟',
+        'ANI:PMI-绠¢亾鍒堕��' => 'PMI-绠¢亾鍒堕��',
+        'ANI:PMI-閲戝睘鍒堕��' => 'PMI-閲戝睘鍒堕��',
+        'ANI:PMI-鐢靛姏' => 'PMI-鐢靛姏',
+        'ANI:RoHS' => 'RoHS',
+        'ANI:ELV' => 'ELV',
+        'ANI:鐜╁叿&鐨潻' => '鐜╁叿&鐨潻',
+        'ANI:璐甸噾灞�-鍒堕��' => '璐甸噾灞�-鍒堕��',
+        'ANI:璐甸噾灞�-鍥炴敹' => '璐甸噾灞�-鍥炴敹',
+        'ANI:鍕樻帰-鏀垮簻' => '鍕樻帰-鏀垮簻',
+        'ANI:鍕樻帰-鐭夸笟鍏徃' => '鍕樻帰-鐭夸笟鍏徃',
+        'ANI:Mining-鍐剁偧' => 'Mining-鍐剁偧',
+        'ANI:Mining-寮�閲�' => 'Mining-寮�閲�',
+        'ANI:EPA' => 'EPA',
+        'ANI:鍦熷¥淇' => '鍦熷¥淇',
+        'ANI:鍦熷¥鐮旂┒' => '鍦熷¥鐮旂┒',
+        'ANI:鑰冨彜&鏂囩墿' => '鑰冨彜&鏂囩墿',
+        'ANI:褰曚簳' => '褰曚簳',
+        'ANI:鍒惰嵂' => '鍒惰嵂',
+        'ANI:涓夊厓鍌寲鍓�' => '涓夊厓鍌寲鍓�',
+        'ANI:Thermal Power' => 'Thermal Power',
+        'ANI:Nuclear Power' => 'Nuclear Power',
+        'ANI:Wind Power' => 'Wind Power',
+        'ANI:Power(other)' => 'Power(other)',
+        // NDT
+        'NDT:姹借溅' => '姹借溅',
+        'NDT:Civil Aviation' => 'Civil Aviation',
+        'NDT:Security/Defense' => 'Security/Defense',
+        'NDT:Oil,Gas&Chemical' => 'Oil,Gas&Chemical',
+        'NDT:General Manufacturing' => 'General Manufacturing',
+        'NDT:Inspection/Service/Rental' => 'Inspection/Service/Rental',
+        'NDT:鍏朵粬' => '鍏朵粬',
+        'NDT:Thermal Power' => 'Thermal Power',
+        'NDT:Nuclear Power' => 'Nuclear Power',
+        'NDT:Wind Power' => 'Wind Power',
+        'NDT:Power(other)' => 'Power(other)',
+        // RVI
+        'RVI:姹借溅' => '姹借溅',
+        'RVI:Civil Aviation' => 'Civil Aviation',
+        'RVI:Security/Defense' => 'Security/Defense',
+        'RVI:Oil,Gas&Chemical' => 'Oil,Gas&Chemical',
+        'RVI:General Manufacturing' => 'General Manufacturing',
+        'RVI:Inspection/Service/Rental' => 'Inspection/Service/Rental',
+        'RVI:鍏朵粬' => '鍏朵粬',
+        'RVI:Thermal Power' => 'Thermal Power',
+        'RVI:Nuclear Power' => 'Nuclear Power',
+        'RVI:Wind Power' => 'Wind Power',
+        'RVI:Power(other)' => 'Power(other)'
+    };
+
+}
\ No newline at end of file
diff --git a/scr/classes/DataLoadAccountController.cls-meta.xml b/scr/classes/DataLoadAccountController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/DataLoadAccountController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DataLoadAccountControllerTest.cls b/scr/classes/DataLoadAccountControllerTest.cls
new file mode 100644
index 0000000..bb27635
--- /dev/null
+++ b/scr/classes/DataLoadAccountControllerTest.cls
@@ -0,0 +1,241 @@
+@isTest
+private class DataLoadAccountControllerTest {
+	public static List<RecordType> rectIE;
+	public static List<RecordType> rectRVI;
+	public static List<RecordType> rectNDT;
+	public static List<RecordType> rectANI;
+	public static Campaign campain;
+	public static DataLoadAccountController controller;
+    public static Account accountIE;
+    public static Account accountNDT;
+    public static Account dealer;
+    public static Contact core;
+    public static Contact core2;
+    public static Contact core3;
+	public static void Basicdata(){
+		rectIE  = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+    	rectRVI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer RVI'];
+    	rectNDT = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+    	rectANI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+
+        //浠g悊鍟�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.FacilityNameD__c = '娴嬭瘯娴嬭瘯1111';
+        dealer.FacilityName__c = '娴嬭瘯娴嬭瘯1111';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        // 浠g悊鍟嗕笅鑱旂郴浜�
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+
+        String timenow = Datetime.now().format('yyyyMMddHHmmss');
+        // 甯傚満閮ㄧ敤鎴�(MarketingStrategy__c =true)
+        User hpOwner = new User( LastName = 'hp', FirstName = 'owner', Alias = 'hp', CommunityNickname = 'hpOwner', Email = 'olympus_hpowner@sunbridge.com', Username = 'olympus_hpowner@sunbridge.com', IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja', ProfileId = System.Label.SystemAdmin,MarketingStrategy__c =true);
+        insert hpOwner;
+        // 鍒涘缓浠g悊鍟嗙敤鎴�(ContactId = core.id)
+        User dealerUser = new User( LastName = 'ceshi20200803', FirstName = 'owner20200803', Alias = 'hp', CommunityNickname = 'testUser01', Email = 'olympus_hpowner@sunbridge.com', Username = 'testUser01@prectech.com', IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja',  ProfileId = prof.Id,MarketingStrategy__c =true,ContactId = core.id);
+        insert dealerUser;
+        // 妯℃嫙甯傚満閮ㄥ垱寤虹敤鎴�
+        System.runAs(hpOwner){
+            accountIE = new Account();
+            accountIE.Name = '瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴00';
+            accountIE.FacilityNameD__c = '瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴00鍔ㄥ姏璇曞埗闄�';
+            accountIE.FacilityName__c = '瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴00鍔ㄥ姏璇曞埗闄�';
+            accountIE.DivisionName_D__c = '鍔ㄥ姏璇曞埗闄�';
+            accountIE.RecordTypeId = rectIE[0].Id;
+            accountIE.ProductSegment__c = 'IE';
+            accountIE.stautesD__c = 'Pass';
+
+            insert accountIE;
+
+            // accountNDT
+
+            accountNDT = new Account();
+            accountNDT.Name = '瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01';
+            accountNDT.FacilityNameD__c = '瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01鍔ㄥ姏璇曞埗闄�';
+            accountNDT.FacilityName__c = '瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01鍔ㄥ姏璇曞埗闄�';
+            accountNDT.DivisionName_D__c = '鍔ㄥ姏璇曞埗闄�';
+            accountNDT.RecordTypeId = rectNDT[0].Id;
+            accountNDT.ProductSegment__c = 'NDT';
+            accountNDT.stautesD__c = 'Pass';
+
+            // insert accountNDT;
+        }
+        // 鍒涘缓瀹㈡埛鐨勮仈绯讳汉
+        core2 = new Contact(email='jplumber@salesforce.com', firstname='',lastname='鏇硅繋鏄�1',accountid=accountIE.id);
+        insert core2;
+        core3 = new Contact(email='jplumber@salesforce.com', firstname='',lastname='鏇硅繋鏄�2',accountid=accountIE.id);
+        insert core3;
+       
+        // 鍒涘缓瀹㈡埛鐨勫鎴峰洟闃�
+        List<AccountTeamMember> insertList = new List<AccountTeamMember>();
+        // 瀹㈡埛鍥㈤槦-浠g悊鍟嗙敤鎴�
+        AccountTeamMember atm1 = new AccountTeamMember();
+        atm1.accountId = accountIE.Id;
+        atm1.userId = dealerUser.Id;
+        atm1.teamMemberRole = 'Sales Manager';
+        insertList.add(atm1);
+        // 瀹㈡埛鍥㈤槦-姝e父
+        AccountTeamMember atm2 = new AccountTeamMember();
+        atm2.accountId = accountIE.Id;
+        atm2.userId = hpOwner.Id;
+        atm2.teamMemberRole = 'Sales Manager';
+        insertList.add(atm2);
+        insert insertList;
+        // 鍒涘缓甯傚満娲诲姩
+        campain = new Campaign();
+        campain.Name = '娴嬭瘯甯傚満娲诲姩';
+
+        insert campain;
+
+        List<Account> accountList =    [SELECT id,Name,DivisionName_D__c,ProductSegment__c,createddate,OwnerId ,ManagementCode_F__c from Account where IsMarketingStrategyCreated__c = true];
+
+        System.debug('accountList--->'+accountList);
+
+        PageReference page = new PageReference('/apex/DataLoadAccount?campaignId='+campain.Id);
+        System.Test.setCurrentPage(page);
+        controller = new DataLoadAccountController();
+	}
+	//鍏ㄩ儴瀵煎叆鏁版嵁閮芥湁鍊�
+    static testMethod void fullData_ANI() {
+    	
+    	Basicdata();
+
+        controller.init();
+        String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+    	       strblob+= '"ANI","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鍏朵粬","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+    	controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        controller.save();
+    }
+
+     static testMethod void fullData_NDT_0() {
+        
+        Basicdata();
+
+        controller.init();
+        String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+               strblob+= '"NDT","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鍏朵粬","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        controller.save();
+    }
+
+    static testMethod void fullData_NDT() {
+        
+        Basicdata();
+
+        controller.init();
+        String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+               strblob+= '"NDT","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鍏朵粬","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+               strblob+= '"NDT","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鍏朵粬","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        controller.save();
+    }
+
+    static testMethod void fullData_IE() {
+        
+        Basicdata();
+
+        controller.init();
+        String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+               strblob+= '"IE","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01","鍔ㄥ姏璇曞埗闄�1","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鐢靛瓙閮ㄥ搧","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄E01","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+               strblob+= '"IE","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴02","鍔ㄥ姏璇曞埗闄�2","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鐢靛瓙閮ㄥ搧","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄E02","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�2","13956020242","230000","鑱旂郴浜�1"\n';
+               strblob+= '"IE","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴03","鍔ㄥ姏璇曞埗闄�3","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鐢靛瓙閮ㄥ搧","anhuijianghuaiqichegufenyouxiangongsi1","閿�鍞椿鍔�","鍏叡鏈烘瀯","鐩爣","瀹㈡埛1","鏇硅繋鏄E03","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�3","13956020243","230000","鑱旂郴浜�1"\n';
+            
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        controller.save();
+    }
+
+    // 楠岃瘉瀹㈡埛蹇呭~瀛楁
+    static testMethod void inspectData_Account() {
+    	Basicdata();
+    	controller.init();
+    	String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+              strblob +=  '"IE","娴嬭瘯瀹㈡埛瀛楁楠岃瘉","娴嬭瘯瀹㈡埛瀛楁楠岃瘉","","","","","","","","","","","","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+              strblob +=  '"IE","娴嬭瘯瀹㈡埛瀛楁楠岃瘉2","娴嬭瘯瀹㈡埛瀛楁楠岃瘉","xxxx","xxx","","","xxx","xxx","","xxx","xxx","xxx","xxx","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+    	controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+    }
+    // 楠岃瘉鑱旂郴浜�
+    static testMethod void inspectData_Contact() {
+    	Basicdata();
+    	controller.init();
+    	String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+    		   strblob += '"RVI","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴00","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","Security/Defense","","","","","瀹㈡埛1","","","","",""\n';
+    		   strblob += '"","","","","","","","","","","","","","","鏇硅繋鏄�1","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+    		   strblob += '"","","","","","","","","","","","","","","鏇硅繋鏄�2","","","","鑱旂郴浜�1"\n';
+    		   strblob += '"","","","","","","","","","","","","","","鏇硅繋鏄�3","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","23000","鑱旂郴浜�1"\n';
+    		   strblob += '"","","","","","","","","","","","","","","","鍚堣偉甯傝渶灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","13956020241","230000","鑱旂郴浜�1"\n';
+    		   strblob += '"RVI","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴01","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","23001","Security/Defense","","","","","瀹㈡埛1","","","","",""\n';
+    	controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+    }
+    // 鍚屼竴瀹㈡埛涓嬬殑鍓嶉潰鐨勮仈绯讳汉閮戒负绌烘垨楠岃瘉涓嶉�氳繃銆傚皢鍓╀綑绗﹀悎瑙勫垯鐨勬斁鍏ヨ仈绯讳汉闆嗗悎涓��
+    static testMethod void inspectData_Contact_1() {
+    	Basicdata();
+    	controller.init();
+    	String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+    		   strblob += '"ANI","瀹夊窘姹熸樊姹借溅鑲′唤鏈夐檺鍏徃鎶�鏈腑蹇�-娴嬭瘯瀵煎叆椤甸潰鍏抽棴ANI","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","涓夊厓鍌寲鍓�","","","","","瀹㈡埛1","","","","",""\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+    	controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+    }
+    // 瀹㈡埛鍚嶄负绌�
+    static testMethod void inspectData_Contact_AccountNameIsNull() {
+        Basicdata();
+        controller.init();
+        String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+               strblob += '"ANI","","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鐢靛瓙閮ㄥ搧","","","","","瀹㈡埛1","","","","",""\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+    }
+
+    // csv鏍煎紡閿欒
+    static testMethod void csvRead_csvFormalError() {
+        Basicdata();
+        controller.init();
+        String strblob = '"瀹㈡埛","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�","鑱旂郴浜哄娉�"\n';
+               strblob += '"ANI","","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鐢靛瓙閮ㄥ搧","","","","","瀹㈡埛1","","","","",""\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+        controller.contentFile = Blob.valueOf(strblob);
+        controller.csvRead();
+    }
+
+    // csv 鍒楁暟涓嶈冻
+    static testMethod void csvRead_csvWrongNumberOfColumns() {
+        Basicdata();
+        controller.init();
+        String strblob = '"瀹㈡埛鍒嗛噹","瀹㈡埛/浠g悊鍟嗗悕绉�.","瀹㈡埛閮ㄩ棬鍚嶇О","瀹㈡埛瀹℃壒浜�","瀹㈡埛鐪�","瀹㈡埛鍩庡競","瀹㈡埛鍦板潃","瀹㈡埛閭紪","瀹㈡埛Sub Use","瀹㈡埛鑻辨枃鍚嶇О(IE蹇呭~)","瀹㈡埛鏉ユ簮(IE蹇呭~)","瀹㈡埛鐢ㄦ埛灞炴��(IE蹇呭~)","瀹㈡埛绫诲瀷(IE蹇呭~)","瀹㈡埛澶囨敞","鑱旂郴浜哄鍚�","鑱旂郴浜哄湴鍧�","鑱旂郴浜烘墜鏈�","鑱旂郴浜洪偖鏀跨紪鐮�"\n';
+               strblob += '"ANI","","鍔ㄥ姏璇曞埗闄�","鐜� 纾�","瀹夊窘","鍚堣偉","瀹夊窘鐪佸悎鑲ュ競铚�灞卞尯鍖呮渤缁忔祹寮�鍙戝尯绱簯璺�1","230000","鐢靛瓙閮ㄥ搧","","","","","瀹㈡埛1","","","","",""\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+               strblob += '"","","","","","","","","","","","","","","棣栬涓虹┖","棣栬涓虹┖","棣栬涓虹┖","230000","棣栬涓虹┖"\n';
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/DataLoadAccountControllerTest.cls-meta.xml b/scr/classes/DataLoadAccountControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/DataLoadAccountControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DeleteSSBatch.cls b/scr/classes/DeleteSSBatch.cls
new file mode 100644
index 0000000..9a4e48f
--- /dev/null
+++ b/scr/classes/DeleteSSBatch.cls
@@ -0,0 +1,114 @@
+global class DeleteSSBatch implements Database.Batchable<sObject> {
+    public String query;
+
+
+    global DeleteSSBatch() {
+        this.query = query;
+    }
+
+    global Database.QueryLocator start(Database.BatchableContext bc) {
+
+        return Database.getQueryLocator([select Id from SS_Opportunity_detail_product__c]);
+
+    }
+
+    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
+        if(scope.size() > 0){
+            delete scope;
+        }
+    }
+
+    global void finish(Database.BatchableContext BC) {
+
+        Integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/DeleteSSBatch.cls-meta.xml b/scr/classes/DeleteSSBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/DeleteSSBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DeleteSSBatchTest.cls b/scr/classes/DeleteSSBatchTest.cls
new file mode 100644
index 0000000..b60a743
--- /dev/null
+++ b/scr/classes/DeleteSSBatchTest.cls
@@ -0,0 +1,6 @@
+@isTest
+private class DeleteSSBatchTest {
+    static testMethod void testMethod1() {
+        Database.executeBatch(new DeleteSSBatch(), 200);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/DeleteSSBatchTest.cls-meta.xml b/scr/classes/DeleteSSBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/DeleteSSBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DeliveryConfirmPDFController.cls b/scr/classes/DeliveryConfirmPDFController.cls
new file mode 100644
index 0000000..61e0288
--- /dev/null
+++ b/scr/classes/DeliveryConfirmPDFController.cls
@@ -0,0 +1,177 @@
+public with sharing class DeliveryConfirmPDFController {
+	
+	//鍩虹url
+	public String baseUrl { get; private set; }
+    public String agentName {get; private set; }
+	//鏁版嵁List
+	public List<DataLineBean> dataLines {get; private set;}
+	//璁㈠崟Id
+	public String laId {get; private set;}
+	public Map<String,DataLineBean> numMap {get; private set; }
+    public loaner_application__c la{get;private set;}
+	public laDataLineBean lab {get; private set;}
+    public List<UserDataLineBean> luData {get; private set;}
+    public Integer rowNum {get; private set;}
+
+    public boolean isSelf{get; private set; }
+    public boolean isExpress{get; private set; }
+    public boolean isRenew{get; private set; }
+    public String OCM_Number{get; private set; }
+
+	public DeliveryConfirmPDFController() {
+		 laId = System.currentPageReference().getParameters().get('id');
+	}
+    //鍒濆鍖栨暟鎹�
+	public PageReference init(){
+        isSelf = false;
+        isExpress = false;
+        isRenew = false;
+        rowNum = 0;
+		dataLines = new List<DataLineBean>();
+		numMap = new Map<String,DataLineBean>();
+        luData = new List<UserDataLineBean>();
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        //鑾峰彇鍊熺敤鍗曚俊鎭�
+        List<loaner_application__c> laList = [select Id,Follow_Opp_text__c,Follow_Opp__r.InquiryNumber__c,Equipment_Type__c ,pickup_time__c,Loaner_Apply_Renewal_Date__c,loaner_Remark__c,Rental_End_Date__c,Loaner_Ser__c,Approval_Date__c,loaner_request_number__c,Agent__r.Name,Approver__r.Name,Rental_Start_Date__c,loaner_place__c,Demo_purpose__c,direct_shippment_address__c,Loaner_receive_staff__c,Loaner_receive_staff_phone__c,CreatorUserType__c,Applicant_department__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        OCM_Number = la.Follow_Opp_text__c;
+        agentName = la.Agent__r.Name;
+        if(agentName != null){
+            agentName = agentName.replace('(P)', '').replace('锛圥锛�','');
+        }
+        String dateString = String.valueOf(la.Rental_Start_Date__c) + ' 鑷� ' +String.valueOf(la.Rental_End_Date__c);
+        dateString = dateString.replace('null', '');
+        if(dateString.equals( ' 鑷� ')){
+            dateString = '';
+        }
+
+        if(la.Loaner_Apply_Renewal_Date__c != null){
+            isRenew = true;
+        }else if(la.pickup_time__c != null){
+            isSelf = true;
+        }else{
+            isExpress = true;
+        }
+
+        Integer dateNum = 0;
+        String dateNumString = '';
+        if(la.Rental_Start_Date__c != null && la.Rental_End_Date__c != null){
+            dateNum = la.Rental_Start_Date__c.daysBetween(la.Rental_End_Date__c );
+            dateNumString = String.valueOf(dateNum) + '澶�';
+        }
+        lab = new laDataLineBean(dateString,la,dateNumString);
+        List<loaner_user__c> luList = [select id,Contact__r.Phone,Follow_UP_Opp__r.InquiryNumber__c,Customer__r.Name,Customer__r.DivisionName__c,Contact__r.Name,FromThePeriod__c,EndThePeriod__c from loaner_user__c where loaner_application__c = : laId];
+        List<loaner_application_detail__c> ladList = [select  id,LOANER__r.Name,LOANER__r.Internal_Asset_number__c,LOANER__r.SerialNumber,LOANER__r.SerialNumber1__c,Remark__c,ECCode__c,SerialNumber__c,OTCODE__c,LOANER__c,LOANER__r.RecordType.Id,LOANER__r.RecordType.Name,LOANER__r.Description from loaner_application_detail__c where loaner_application__c = :laId];
+		
+        for(loaner_user__c lu :luList){
+           
+            String borrowDate = String.valueOf(lu.FromThePeriod__c) + ' 鑷� ' +String.valueOf(lu.EndThePeriod__c);
+            borrowDate = borrowDate.replace('null', '');
+            if(borrowDate.equals(' 鑷� ')){
+                borrowDate = '';
+            }
+            String name = lu.Customer__r.Name == null?'':lu.Customer__r.Name;
+            rowNum = rowNum+1+(name.length()/30);
+            UserDataLineBean udlb = new UserDataLineBean(borrowDate,lu);
+            luData.add(udlb);
+        }
+
+        for(loaner_application_detail__c lad : ladList){
+  
+        	/*String typeId = lad.LOANER__r.RecordType.id;
+        	
+        	if( typeId.substring(0, 15) == System.label.Asset_Record_Type2){
+        		if(numMap.size() == 0){
+        			DataLineBean dataBean = new DataLineBean(lad.LOANER__r.RecordType.Name,1,lad);
+        			numMap.put(lad.LOANER__c, dataBean);
+        		}else{
+        			if(numMap.containsKey(lad.LOANER__c)){
+
+						DataLineBean da = numMap.get(lad.LOANER__c);
+						da.num = da.num+1;
+        			}else{
+        				DataLineBean dataBean = new DataLineBean(lad.LOANER__r.RecordType.Name,1,lad);
+        				numMap.put(lad.LOANER__c, dataBean);
+        			}
+        		}
+        	}else{
+        		DataLineBean da = new DataLineBean(lad.LOANER__r.RecordType.Name,1,lad);
+        		dataLines.add(da);
+        	}*/
+
+            DataLineBean da = new DataLineBean(lad.LOANER__r.RecordType.Name,1,lad);
+                dataLines.add(da);
+        	
+        }
+        if(numMap.size() > 0){
+        	dataLines.addAll(numMap.values());
+        }
+       
+        
+        if(dataLines.size() < 12){
+            Integer num = dataLines.size();
+            for(Integer i =0; i<(12-num); i++){
+            loaner_application_detail__c lac = new loaner_application_detail__c();
+            DataLineBean demo = new DataLineBean(null,null,lac);
+            System.debug(i);
+            dataLines.add(demo);
+            }  
+        }
+        rowNum = rowNum+dataLines.size();
+		return null;
+	}
+
+
+	 public class DataLineBean {
+        // 鏍锋満绫诲瀷
+        public String recordType { get;private set; }
+        // 鏁伴噺
+        public Integer num { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(String rtype,Integer in_no, loaner_application_detail__c in_lad) {
+            recordType = rtype;
+            num = in_no;
+            lad = in_lad;
+        }
+    }
+
+    public class UserDataLineBean{
+        //鍊熺敤鏃ユ湡
+        public String borrowDate {get;private set;}
+
+        public loaner_user__c lu {get;private set;}
+
+        public UserDataLineBean(String rdate,loaner_user__c in_lu){
+            borrowDate = rdate;
+            lu = in_lu;
+        }
+
+    }
+
+      public class laDataLineBean{
+        //鍊熺敤鏃ユ湡
+        public String ladate {get;private set;}
+
+        //鍊熺敤鏈熼檺
+        public String ladateNumS {get; private set;}
+        public loaner_application__c lala {get;private set;}
+
+        public laDataLineBean(String in_ladate,loaner_application__c in_la,String in_laNum){
+            ladate = in_ladate;
+            lala = in_la;
+            ladateNumS = in_laNum;
+        }
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/DeliveryConfirmPDFController.cls-meta.xml b/scr/classes/DeliveryConfirmPDFController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/DeliveryConfirmPDFController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DeliveryConfirmPDFControllerTest.cls b/scr/classes/DeliveryConfirmPDFControllerTest.cls
new file mode 100644
index 0000000..70b650d
--- /dev/null
+++ b/scr/classes/DeliveryConfirmPDFControllerTest.cls
@@ -0,0 +1,118 @@
+@isTest
+private class DeliveryConfirmPDFControllerTest {
+	
+	@isTest static void test_method_one() {
+		// Implement test code
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+       	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner.Request_return_Date__c = Date.today().addDays(10);
+        loaner.Status__c = '閮ㄥ垎鍙戣揣';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+       loaner.pickup_time__c  = Date.today();
+        loaner.Rental_Start_Date__c = Date.today().addDays(1);
+        loaner.Rental_End_Date__c  = Date.today().addDays(2);
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        Loaner_Express__c le = new Loaner_Express__c(
+    	Name = 'test01',
+    	loaner_application__c = loaner.Id,
+    	NotReceivingNum__c = 3
+    	);
+
+        insert le;
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        detail.Loaner_Express__c = le.id;
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        detail.Loaner_Express__c = le.id;
+		//detail.Shipment_Request_Date__c = Date.today();
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '娆犲搧涓�';
+        detail.Loaner_Express__c = le.id;
+        In_detail.add(detail);
+
+        insert In_detail;
+
+
+        PageReference page = new PageReference('/apex/DeliveryConfirmPDFController?Id=' + loaner.Id );
+        System.Test.setCurrentPage(page);
+        DeliveryConfirmPDFController  controller = new DeliveryConfirmPDFController();
+
+
+        controller.init();
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/DeliveryConfirmPDFControllerTest.cls-meta.xml b/scr/classes/DeliveryConfirmPDFControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/DeliveryConfirmPDFControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/DeliveryTriggerHandler.cls b/scr/classes/DeliveryTriggerHandler.cls
new file mode 100644
index 0000000..c272e04
--- /dev/null
+++ b/scr/classes/DeliveryTriggerHandler.cls
@@ -0,0 +1,25 @@
+public without sharing class DeliveryTriggerHandler {
+  public static void setDeliveryReceiver(List<Delivery__c> newList, Map<Id, Delivery__c> newMap, List<Delivery__c > oldList, Map<Id, Delivery__c> oldMap)
+   {
+   
+       List<String> ordidList = new List<String>();
+       Map<String,String> DeliveryToReceiver = new Map<String,String>();
+        for (Delivery__c del : newList) {
+            ordidList.add(del.SSBD_Contract__c);
+        }
+      
+      List<Order> ordList = [select Id, CreatedById from Order where Id IN :ordidList];
+        for (Order ord : ordList ) {
+           DeliveryToReceiver.put(ord.Id, ord.CreatedById );
+         }
+         for (Delivery__c del : newList)
+        {   
+          String s = DeliveryToReceiver.get(del.SSBD_Contract__c);
+          if (s!= del.OrderCreatedbyText__c && s!= null)
+            { 
+                 del.OrderCreatedbyText__c  = s;} 
+        }
+    }
+    }
+   
+   //How annoying!s-s
\ No newline at end of file
diff --git a/scr/classes/DeliveryTriggerHandler.cls-meta.xml b/scr/classes/DeliveryTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..8b061c8
--- /dev/null
+++ b/scr/classes/DeliveryTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/EmailComeBackListen.cls b/scr/classes/EmailComeBackListen.cls
new file mode 100644
index 0000000..ea14d5a
--- /dev/null
+++ b/scr/classes/EmailComeBackListen.cls
@@ -0,0 +1,182 @@
+global class EmailComeBackListen implements Messaging.InboundEmailHandler {
+    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
+    	//浠庢爣棰樹腑鎴彇鍑哄叧鑱斾俊鎭�
+		System.debug('SWO閭欢鍥炲鐩戝惉');
+		String id = '';
+		String type = '';
+		if(String.isNotBlank(email.subject)){
+			System.debug('email.subject:'+email.subject);
+			List<String> str = email.subject.split('~');
+			if(str!=null && str.size()!=0){
+				//鎴彇閭欢鍏宠仈淇℃伅锛屾煡璇㈤偖浠跺叧鑱斿璞★紝鍒ゆ柇鏄惁璺宠繃閭欢鏈嶅姟
+				String name = str[1];
+				System.debug('name:'+name);
+				//SWO 鐨勯偖浠惰繑鍥�
+				if(name.startsWith('S')){
+					type = 'S';
+					name = name.substring(name.indexOf(':')+1,name.length());
+					if(String.isNotBlank(name)){
+						System.debug('name:'+name);
+						List<SWO__c> swoList = [select Id,notSaveEmail__c,Name from SWO__c where Name=:name];
+						if (swoList!=null && swoList.size()!=0) {
+							id = swoList[0].Id;
+							System.debug('鍥炲鐩戝惉id锛�'+id);
+							System.debug('SWO閭欢鍥炲鐩戝惉:'+swoList[0].notSaveEmail__c);
+							if(swoList[0].notSaveEmail__c){
+								System.debug('璺宠繃閭欢鏈嶅姟鐩戝惉');
+								swoList[0].notSaveEmail__c = false;
+								update swoList[0];
+								return null;
+							}
+						}	
+					}
+				}
+				//Case 鐨勯偖浠惰繑鍥�
+				if(name.startsWith('C')){
+					type = 'C';
+					System.debug('Case 鐨勯偖浠惰繑鍥�');
+					name = name.substring(name.indexOf(':')+1, name.length());
+					if(String.isNotBlank(name)){
+						List<User_FaultInfo__c> caseList = [select Id,notSaveEmail__c,Name from User_FaultInfo__c where Name=:name];
+						System.debug('caseList:'+caseList);
+						if(caseList!=null && caseList.size()!=0){
+							id = caseList[0].Id;
+							System.debug('Case閭欢鍥炲鐩戝惉:'+caseList[0].notSaveEmail__c);
+							if(caseList[0].notSaveEmail__c){
+								System.debug('璺宠繃閭欢鏈嶅姟鐩戝惉');
+								caseList[0].notSaveEmail__c = false;
+								update caseList[0];
+								return null;
+							}
+						}
+					}
+				}
+				//鎶ヤ环鐨勯偖浠惰繑鍥�
+				if(name.startsWith('Q')){
+					type = 'Q';
+					name = name.substring(name.indexOf(':')+1, name.length());
+					if(String.isNotBlank(name)){
+						List<Quotes__c> quotesList = [select Id,notSaveEmail__c,Name from Quotes__c where Name=:name];
+						if (quotesList!=null && quotesList.size()!=0) {
+							id = quotesList[0].Id;
+							System.debug('Quoteses閭欢鍥炲鐩戝惉:'+quotesList[0].notSaveEmail__c);
+							if(quotesList[0].notSaveEmail__c){
+								System.debug('璺宠繃閭欢鏈嶅姟鐩戝惉');
+								quotesList[0].notSaveEmail__c = false;
+								update quotesList[0];
+								return null;
+							}
+						}
+					}
+				}
+				if (String.isNotBlank(id)) {
+					createEmail(email,id,type);
+				}
+			}
+		}
+		Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
+		//createEmail(email,id);
+		//SendEmail();
+		result.success = true;
+		return result;
+	}
+
+	public void createEmail(Messaging.InboundEmail email,String id,String type){
+		Mail_Merge__c mailMerge = new Mail_Merge__c();
+		mailMerge.RECORD__c = id;
+		//閭欢鏍囬
+		if(String.isNotBlank(email.subject)){
+			mailMerge.SUBJECTCOPY__c = email.subject;
+			List<String> str = email.subject.split('~');
+			if(str!=null && str.size()!=0){
+				mailMerge.SUBJECT__c = str[0];
+				mailMerge.Name = str[0];
+			}
+		}else{
+			mailMerge.SUBJECTCOPY__c = '';
+			mailMerge.SUBJECT__c = '';
+			mailMerge.Name = '';
+		}
+		if(type == 'S'){
+			mailMerge.SWO__c = id;
+			mailMerge.RECORD_TYPE__c = 'SWO';
+		}
+		if(type == 'C'){
+			mailMerge.CaseF__c = id;
+			mailMerge.RECORD_TYPE__c = 'Case';
+		}
+		if(type == 'Q'){
+			mailMerge.Quotes__c = id;
+			mailMerge.RECORD_TYPE__c = 'Quotes';
+		}
+		//鍙戜欢浜哄湴鍧�
+		mailMerge.FROM__c = email.fromAddress;
+		//鏀朵欢浜哄湴鍧�
+		mailMerge.RECIPIENT__c = getAddresses(email.toAddresses);
+		//鎶勯�佷汉
+		mailMerge.CC__c = getAddresses(email.ccAddresses);
+
+		setAllMember(mailMerge,email.toAddresses,email.ccAddresses);
+		//閭欢淇℃伅
+		mailMerge.MESSAGE__c = email.plainTextBody;
+		//鏀跺彇鍥炲閭欢鏃堕棿
+		mailMerge.DATE__c = Datetime.now();
+
+		mailMerge.TYPE__c = 'reply';
+		
+		mailMerge.EMAIL_SENT__c = 'YES';
+
+		insert mailMerge;
+		//淇濆瓨閭欢闄勪欢
+		saveFile(email.binaryAttachments,mailMerge.Id);
+	}
+
+	public String getAddresses(List<String> addresses){
+		String returnStr = '';
+		if(addresses!=null && addresses.size()!=0){
+			for(String str:addresses){
+				returnStr += str+';';
+			}
+		}
+		return returnStr;
+	}
+	public void setAllMember(Mail_Merge__c mailMerge,List<String> toAddress,List<String> ccAddresses){
+		mailMerge.ALL_MEMBER__c = '';
+		mailMerge.ALL_MEMBER_NAME__c = '';
+        mailMerge.ALL_MEMBER_TYPE__c = '';
+		if(toAddress !=null && toAddress.size()!=0){
+			for(String str : toAddress){
+				//閭欢鍦板潃涔嬮棿鐢ㄢ��;鈥濋殧寮�锛屽彂閫侀偖浠堕〉浼氱敤鈥�;鈥濆垎鍓插瓧绗︿覆
+				mailMerge.ALL_MEMBER__c = mailMerge.ALL_MEMBER__c + str + ';';
+				//鍚嶅瓧鏆傛椂閮界敤鈥�-鈥濓紝閭欢椤甸潰鍒嗗壊鍑衡��-鈥濅細鐢ㄧ┖浠f浛
+				mailMerge.ALL_MEMBER_NAME__c = mailMerge.ALL_MEMBER_NAME__c + '-;';
+				mailMerge.ALL_MEMBER_TYPE__c = mailMerge.ALL_MEMBER_TYPE__c + 'to;';
+			}
+		}
+		if(ccAddresses !=null && ccAddresses.size()!=0){
+			for(String str : ccAddresses){
+				if(str.startsWith('email@') || str.equals('') || str.equals('')){
+					continue;
+				}
+				//閭欢鍦板潃涔嬮棿鐢ㄢ��;鈥濋殧寮�锛屽彂閫侀偖浠堕〉浼氱敤鈥�;鈥濆垎鍓插瓧绗︿覆
+				mailMerge.ALL_MEMBER__c = mailMerge.ALL_MEMBER__c + str + ';';
+				//鍚嶅瓧鏆傛椂閮界敤鈥�-鈥濓紝閭欢椤甸潰鍒嗗壊鍑衡��-鈥濅細鐢ㄧ┖浠f浛
+				mailMerge.ALL_MEMBER_NAME__c = mailMerge.ALL_MEMBER_NAME__c + '-;';
+				mailMerge.ALL_MEMBER_TYPE__c = mailMerge.ALL_MEMBER_TYPE__c + 'cc;';
+			}
+		}
+	}
+	public void saveFile(List<Messaging.InboundEmail.BinaryAttachment> binaryAttachments,String Id){
+		if (binaryAttachments != null && binaryAttachments.size()!=0) {
+			List<Attachment> attachmentList = new List<Attachment>();
+			for(Messaging.InboundEmail.BinaryAttachment emailFile : binaryAttachments){
+				Attachment attachment = new Attachment();
+				attachment.Name = emailFile.fileName;
+				attachment.Body = emailFile.body;
+				attachment.ParentId = Id;
+				attachmentList.add(attachment);
+			}
+			insert attachmentList;
+		}
+	} 
+}
\ No newline at end of file
diff --git a/scr/classes/EmailComeBackListen.cls-meta.xml b/scr/classes/EmailComeBackListen.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/EmailComeBackListen.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/EmailComeBackListenTest.cls b/scr/classes/EmailComeBackListenTest.cls
new file mode 100644
index 0000000..0c0073f
--- /dev/null
+++ b/scr/classes/EmailComeBackListenTest.cls
@@ -0,0 +1,90 @@
+@isTest
+private class EmailComeBackListenTest {
+    static testMethod void testMethod1() {
+
+    	User_FaultInfo__c ca = new User_FaultInfo__c();
+    	ca.ORIGIN__c = 'Web';
+    	ca.SUBJECT__c = 'test';
+    	ca.OFFICE_OWNER__c = 'Beijing';
+    	ca.Product_Type__c = 'NDT';
+    	ca.TYPE__c = 'Service';
+    	ca.LOGISTICS_SHIPMENT_TYPE__c = 'Domestic';
+    	ca.STATUS__c = 'Not Started';
+    	ca.PRIORITY__c = 'High';
+    	insert ca;
+    	User_FaultInfo__c cas = [select Name from User_FaultInfo__c where Id =: ca.Id];
+
+    	List<String> toAddressesList = new List<String>();
+    	toAddressesList.add('dai_prectech@olympus.com.cn');
+    	List<String> ccAddressesList = new List<String>();
+    	ccAddressesList.add('dai_prectech@olympus.com.cn');
+    	Messaging.InboundEmail email = new Messaging.InboundEmail();
+    	email.fromAddress = 'dai_prectech@olympus.com.cn';
+    	email.toAddresses = toAddressesList; 
+    	email.ccAddresses = ccAddressesList;
+    	email.plainTextBody = 'test';
+    	email.subject = 'test~Ctest:'+cas.Name;
+        EmailComeBackListen listen = new EmailComeBackListen();
+        listen.handleInboundEmail(email, new Messaging.InboundEnvelope());
+        ca.notSaveEmail__c = true;
+        update ca;
+        listen.handleInboundEmail(email, new Messaging.InboundEnvelope());
+    }
+    static testMethod void testMethod2() {
+
+    	SWO__c swo = new SWO__c();
+        swo.Name = 'test2';
+        swo.QUANTITY__c = 22;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+    	List<String> toAddressesList = new List<String>();
+    	toAddressesList.add('dai_prectech@olympus.com.cn');
+    	List<String> ccAddressesList = new List<String>();
+    	ccAddressesList.add('dai_prectech@olympus.com.cn');
+    	Messaging.InboundEmail email = new Messaging.InboundEmail();
+    	email.fromAddress = 'dai_prectech@olympus.com.cn';
+    	email.toAddresses = toAddressesList; 
+    	email.ccAddresses = ccAddressesList;
+    	email.plainTextBody = 'test';
+    	email.subject = 'test~Stest:'+swo.Name;
+        EmailComeBackListen listen = new EmailComeBackListen();
+        listen.handleInboundEmail(email, new Messaging.InboundEnvelope());
+        swo.notSaveEmail__c = true;
+        update swo;
+        listen.handleInboundEmail(email, new Messaging.InboundEnvelope());
+    }
+    static testMethod void testMethod3() {
+    	SWO__c swo = new SWO__c();
+        swo.Name = 'test3';
+        swo.QUANTITY__c = 22;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.Name = 'test4';
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        insert quotes;
+
+        Quotes__c quo = [select Name from Quotes__c where Id =: quotes.Id];
+
+    	List<String> toAddressesList = new List<String>();
+    	toAddressesList.add('dai_prectech@olympus.com.cn');
+    	List<String> ccAddressesList = new List<String>();
+    	ccAddressesList.add('dai_prectech@olympus.com.cn');
+    	Messaging.InboundEmail email = new Messaging.InboundEmail();
+    	email.fromAddress = 'dai_prectech@olympus.com.cn';
+    	email.toAddresses = toAddressesList; 
+    	email.ccAddresses = ccAddressesList;
+    	email.plainTextBody = 'test';
+    	email.subject = 'test~Qtest:'+quo.Name;
+        EmailComeBackListen listen = new EmailComeBackListen();
+        listen.handleInboundEmail(email, new Messaging.InboundEnvelope());
+        quotes.notSaveEmail__c = true;
+        update quotes;
+        listen.handleInboundEmail(email, new Messaging.InboundEnvelope());
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/EmailComeBackListenTest.cls-meta.xml b/scr/classes/EmailComeBackListenTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/EmailComeBackListenTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/EquipmentLoanerApplyController.cls b/scr/classes/EquipmentLoanerApplyController.cls
new file mode 100644
index 0000000..ab059a7
--- /dev/null
+++ b/scr/classes/EquipmentLoanerApplyController.cls
@@ -0,0 +1,1556 @@
+public without sharing class EquipmentLoanerApplyController {
+	// 鏍锋満鍊熷嚭鐢宠ID
+    private String loanerApplyId;
+    public Asset rec { get; set; }
+    public String assName { get; set; }
+    public String assECcode { get; set; }
+
+    public string userType {get;private set; }
+
+    /*****************鎺掑簭鐢�******************/
+    public String sortKey { get; set; }
+    public String setId { get; set; }
+    public String preSortKey { get; private set; }
+    public Boolean sortOrderAsc { get; private set; }
+    public Boolean isManager { get; private set; }
+    //public Boolean isCancel { get; private set; }
+    public String[] sortOrder { get; private set; }
+    private String[] columus = new String[]{ 'SerialNumber', 'OT_Code__c', 'EC_Code__c','loaner_place__c', 'Status'};
+
+    public Boolean getcanSave() {
+        return ((loanerApply.Status__c != '鑽夋涓�' && loanerApply.Status__c != '椹冲洖' && isManager == false));
+        }
+    public Boolean getcanSearch() {
+        return loanerApply.Loaner_LendOrder__c;
+    }
+
+    //鍑嗗澶╂暟
+    private Integer prepareDay;
+    private Integer dayCount = 0;
+    // 鏄剧ず鏁版嵁鏉℃暟闄愬埗
+    private Integer Select_Limit = 200;
+    private Boolean Over_Limit = false;
+
+    /*****************鐢婚潰琛ㄧずBean******************/
+    public loaner_application__c loanerApply { get; set; }
+    //鏄剧ず鏄庣粏
+    public List<EquipmentSetInfo> equipmentSetRecords { get; set; }
+
+    // 鏍锋満Set
+    public List<EquipmentSetInfo> loanerSetRecords { get; set; }
+
+    List<loaner_application_detail__c> del = New List<loaner_application_detail__c>();
+
+    // 鏍锋満Set
+    private List<String> ecCodeList;
+
+    // 宸查�夋嫨鏍锋満
+    private List<String> loanerAssetSelected = new List<String>();
+
+    public Integer pageRecordNo { 
+        get {
+            return equipmentSetRecords == null ? 0 : equipmentSetRecords.size();
+        }
+    }
+
+    public Integer loanerSetNo {
+        get {
+            return loanerSetRecords == null ? 0 : loanerSetRecords.size();
+        }
+    }
+
+	public EquipmentLoanerApplyController() {
+		// 鑾峰緱浼犲叆鍙傛暟
+        loanerApplyId = ApexPages.currentPage().getParameters().get('loid');
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+	}
+
+	// 鐢婚潰鍒濆鍖�
+    public void init() {
+        userType = UserInfo.getUserType();
+        // 榛樿鎺掑簭
+        this.sortKey = '0';
+        this.preSortKey = '0';
+        this.sortOrderAsc = true;
+        //this.isCancel = false;
+        this.sortOrder = new String[4];
+        this.sortOrder = new String[]{ '銆�', '銆�', '銆�', '銆�', '銆�','鈫�'};
+        prepareDay = 0;
+        Over_Limit = false;
+        isManager = false;
+        List<String> profileIdList = new List<String>();
+        Map<String,String> profileIdMap = new Map<String,String>();
+        List<String> lend_DetName = new List<String>();
+        // String profileId = UserInfo.getProfileId().subString(0, 15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+        profileIdList = System.label.LoanerManager.split(',');
+        if(profileIdList.size() > 0){
+            for(String str : profileIdList){
+                profileIdMap.put(str, str);
+            }
+        }
+
+        if(profileIdMap.containsKey(new_profileId.subString(0,15))){
+            isManager = true;
+        }
+
+        /*User userInfo = [SELECT Id,Is_Cancel_Jurisdiction__c FROM User WHERE Id = :UserInfo.getUserId()];
+        if(userInfo.Is_Cancel_Jurisdiction__c) this.isCancel = true;*/
+
+    	if (String.isNotBlank(loanerApplyId)) {
+    		loanerApply = [SELECT id,Name,Demo_purpose__c,EC_Code_1__c,EC_Code_2__c,EC_Code_3__c,EC_Code_4__c,
+    							EC_Code_5__c,EC_Code_6__c,EC_Code_7__c,EC_Code_8__c,EC_Code_9__c,
+    							EC_Code_10__c,Prepare_Day__c,Rental_Start_Date__c,Rental_End_Date__c,EC_Code_11__c
+                                ,EC_Code_12__c,EC_Code_13__c,EC_Code_14__c,EC_Code_15__c,EC_Code_16__c
+                                ,EC_Code_17__c,EC_Code_18__c,EC_Code_19__c,EC_Code_20__c,Status__c,Equipment_Type__c
+                                ,Loaner_LendFrom__c,Loaner_LendOrder__c,Manager_detail_Del__c
+                                ,Loaner_LendFrom__r.Rental_Start_Date__c,Loaner_LendFrom__r.Rental_End_Date__c,Approval_Status__c
+                                ,DealerOrder_From__c,Approval_Step__c,Request_shipping_Date__c,Remind_Date__c
+                                ,Loaner_LendUser1__c,Loaner_LendUser2__c,Loaner_LendUser3__c,Loaner_LendUser4__c
+                                ,Loaner_LendUser5__c,ProductCount19__c,ProductCount20__c,AllLead_OrderName__c
+                                ,ProductCount1__c,ProductCount2__c,ProductCount3__c,ProductCount4__c,ProductCount5__c,ProductCount6__c
+                                ,ProductCount7__c,ProductCount8__c,ProductCount9__c,ProductCount10__c,ProductCount11__c,ProductCount12__c
+                                ,ProductCount13__c,ProductCount14__c,ProductCount15__c,ProductCount16__c,ProductCount17__c,ProductCount18__c
+    						FROM loaner_application__c WHERE Id = :loanerApplyId ];
+
+            rec = new Asset();
+            rec.Equipment_Type__c = loanerApply.Equipment_Type__c;
+            ecCodeList = new List<String>();
+            if(String.isNotBlank(loanerApply.EC_Code_1__c)) ecCodeList.add(loanerApply.EC_Code_1__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_2__c)) ecCodeList.add(loanerApply.EC_Code_2__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_3__c)) ecCodeList.add(loanerApply.EC_Code_3__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_4__c)) ecCodeList.add(loanerApply.EC_Code_4__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_5__c)) ecCodeList.add(loanerApply.EC_Code_5__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_6__c)) ecCodeList.add(loanerApply.EC_Code_6__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_7__c)) ecCodeList.add(loanerApply.EC_Code_7__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_8__c)) ecCodeList.add(loanerApply.EC_Code_8__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_9__c)) ecCodeList.add(loanerApply.EC_Code_9__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_10__c)) ecCodeList.add(loanerApply.EC_Code_10__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_11__c)) ecCodeList.add(loanerApply.EC_Code_11__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_12__c)) ecCodeList.add(loanerApply.EC_Code_12__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_13__c)) ecCodeList.add(loanerApply.EC_Code_13__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_14__c)) ecCodeList.add(loanerApply.EC_Code_14__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_15__c)) ecCodeList.add(loanerApply.EC_Code_15__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_16__c)) ecCodeList.add(loanerApply.EC_Code_16__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_17__c)) ecCodeList.add(loanerApply.EC_Code_17__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_18__c)) ecCodeList.add(loanerApply.EC_Code_18__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_19__c)) ecCodeList.add(loanerApply.EC_Code_19__c.trim());
+            if(String.isNotBlank(loanerApply.EC_Code_20__c)) ecCodeList.add(loanerApply.EC_Code_20__c.trim());
+            if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
+                dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
+            }
+
+    		// 宸插瓨鍦ㄦ牱鏈哄�熷嚭鏄庣粏鍘嗗彶鍙栧緱
+            List<loaner_application_detail__c> loanerApplyDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Description,
+            							LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,LOANER__r.Rental_Start_Date__c 
+                                        ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c,LOANER__r.Name
+                                        ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
+                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
+                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
+                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,loanerOrder_Status__c,Remark__c,LOANER__r.Remarks2__c
+                                        ,loaner_application__r.loaner_request_number__c,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c
+                                     from  loaner_application_detail__c
+                                     where loaner_application__c = :loanerApplyId
+                                     order by Name];
+        	for(Integer i = 0; i < loanerApplyDetSelected.size(); i++){
+                if (i == Select_Limit) {Over_Limit=true; break;}
+                EquipmentSetInfo midData = null;
+                if(loanerApplyDetSelected[i].LendPrimary_Name__c != null){
+                    lend_DetName.add(loanerApplyDetSelected[i].LendPrimary_Name__c);
+                    midData = new EquipmentSetInfo(loanerApplyDetSelected[i]);
+                    midData.firstDet = true;
+                }else{
+                    midData = new EquipmentSetInfo(loanerApplyDetSelected[i]);
+                }
+                loanerAssetSelected.add(loanerApplyDetSelected[i].LOANER__c);
+        		equipmentSetRecords.add(midData);
+        	}
+
+
+            // 鏍锋満杞�熸暟鎹�
+            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[鍊熷嚭寮�濮嬫棩]蹇呴』杈撳叆杞�熺敵璇峰崟寮�濮嬪拰缁撴潫涔嬮棿鐨勬棩鏈熴��'));
+            if(loanerApply.Loaner_LendOrder__c && loanerApply.DealerOrder_From__c != null){
+                List<loaner_application_detail__c> loanerApplyLendDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Description,
+                                            LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,LOANER__r.Rental_Start_Date__c 
+                                            ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c,LOANER__r.Name
+                                            ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
+                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
+                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
+                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,Remark__c,LOANER__r.Remarks2__c,loaner_application__r.loaner_request_number__c
+                                        ,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c,is_distribution__c
+                                         from  loaner_application_detail__c
+                                         where DealerID__c = :String.valueOf(loanerApply.DealerOrder_From__c).subString(0,15)
+                                         AND Id not in : lend_DetName
+                                         AND Lend_Det__c = true 
+                                         AND is_distribution__c = false 
+                                         order by Name];
+                system.debug('111'+loanerApplyLendDetSelected.size());
+                system.debug('111'+lend_DetName);
+                system.debug(loanerApply.DealerOrder_From__c);
+                for(Integer i = 0; i < loanerApplyLendDetSelected.size(); i++){
+                    if (i == Select_Limit) {Over_Limit=true; break;}
+                    loanerAssetSelected.add(loanerApplyLendDetSelected[i].LOANER__c);
+                    EquipmentSetInfo midData = new EquipmentSetInfo(loanerApplyLendDetSelected[i]);
+                    midData.firstDet = true;
+                    midData.check = false;
+                    midData.oldcheck = false;
+                    equipmentSetRecords.add(midData);
+                }
+                system.debug(equipmentSetRecords.size());
+            }
+
+            prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
+            loanerApply.Prepare_Day__c = prepareDay;
+
+            //鍏朵粬宸插瓨鍦ㄧ殑鏍锋満鍊熷嚭鍘嗗彶
+            /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
+                                        LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
+                                        loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
+                                        ,Allocated_Det__c,LendPrimary_Name__c
+                                     from  loaner_application_detail__c
+                                     where loaner_application__c != :loanerApplyId
+                                     and LOANER__c in :loanerAssetSelected
+                                     AND Arrival_wh_Date__c = null
+                                     AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
+                                     and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
+                                     or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
+                                     AND StockUp__c = false
+                                     order by Name];
+            Map<String, Date> othersMap = new Map<String,Date>();
+
+            for (loaner_application_detail__c other : others) {
+                if (othersMap.containsKey(other.LOANER__c)) {
+                    continue;
+                } else {
+                    if(other.Received_loaner_Date__c == null){
+                        othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
+                    }else{
+                        othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
+                    }
+                }
+            }*/
+
+            for (EquipmentSetInfo info : equipmentSetRecords) {
+                info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
+                info.Rental_End_Date = loanerApply.Rental_End_Date__c;
+                info.SEdayCount  = dayCount;
+                /*if(info.aset.Status == '鍦ㄥ簱'){
+                    if(othersMap.containsKey(info.aset.Id)){
+                        info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
+                    }else{
+                        info.earliest_Lend_Date = Date.today();
+                    }
+                }*/
+            }
+    	}
+        this.getLoanerSet();
+        if(loanerApply.Equipment_Type__c != 'BS'){
+            this.getDefaultLoSet();
+        }
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'equipmentSetRecords + ' + equipmentSetRecords));
+        // 鏄剧ず鏁版嵁鏉℃暟淇℃伅
+        makeMessage();
+        system.debug(equipmentSetRecords);
+        system.debug(equipmentSetRecords.size());
+
+    }
+    // 鑾峰彇鍊熷嚭鍏冪殑鎵�鏈夌敤鎴�
+    public void getleadUser() {
+        if(loanerApply.DealerOrder_From__c != null){
+            List<user> userList = [SELECT Id
+                                   FROM user
+                                   WHERE AccountId = :loanerApply.DealerOrder_From__c
+                                    AND IsActive = true];
+            Integer i = 1;
+            for(user us: userList){
+                String column = 'Loaner_LendUser' + i + '__c';
+                loanerApply.put(column,us.Id);
+                i++;
+            }
+        }
+    }
+    // 鑾峰彇鏍锋満濂楄
+    public void getLoanerSet() {
+        // 鎵�鏈夋牱鏈篠et
+        loanerSetRecords = new List<EquipmentSetInfo>();
+        List<loaner_Set__c> loanerSetSearch = [select Id,set_type__c, Name, Equipment_Type__c,Remarks__c,SerialNumber__c,Internal_Asset_number__c,Status__c,loaner_place__c,Reservation_information__c
+                                                 from  Loaner_Set__c
+                                                 WHERE Equipment_Type__c = :loanerApply.Equipment_Type__c
+                                                 order by Name];
+        Integer line = 0;
+        for(loaner_Set__c ls : loanerSetSearch){
+            EquipmentSetInfo li = new EquipmentSetInfo(line, ls);
+            loanerSetRecords.add(li);
+            line += 1;
+        }
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'loanerSetRecords' + loanerSetRecords));
+    }
+
+    // 鑾峰彇鐢宠鍗曚腑榛樿鏍锋満
+    public void getDefaultLoSet() {
+        system.debug('getDefaultLoSet');
+        List<String> lend_DetName = new List<String>();
+        //宸查�夋嫨涓綋绠$悊鏍锋満
+        List<String> loanerindividualList = new List<String>();
+        //// 鐢婚潰宸叉墦鍕剧殑鏄庣粏淇濈暀
+        List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            if (info.check == true) {
+                selectedloanerRecords.add(info);
+                if(String.isNotEmpty(info.lad.LendPrimary_Name__c)){
+                    lend_DetName.add(info.lad.LendPrimary_Name__c);
+                }
+                if(String.valueOf(info.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
+                    loanerindividualList.add(info.aset.Id);
+                }
+            }
+        }
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+        loanerAssetSelected = new list<String>();
+        for (EquipmentSetInfo info : selectedloanerRecords) {
+            loanerAssetSelected.add(info.aset.Id);
+        }
+
+        // 宸插瓨鍦ㄦ槑缁嗚鍋氭垚
+        equipmentSetRecords.addAll(selectedloanerRecords);
+        // 鎵�鏈塃Ccode鏍锋満
+
+        //loanerSetRecords = new List<loaner_Set__c>();
+        //杞�熷垎鏀�
+        if(loanerApply.Loaner_LendOrder__c){
+            List<loaner_application_detail__c> loanerApplyLendDetSelected = new List<loaner_application_detail__c>();
+            if(ecCodeList.size() > 0){
+                loanerApplyLendDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Description,LOANER__r.Rental_Start_Date__c,
+                                            LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status
+                                            ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c
+                                            ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
+                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
+                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
+                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,Remark__c,LOANER__r.Remarks2__c,loaner_application__r.loaner_request_number__c
+                                        ,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c,LOANER__r.Name
+                                     from  loaner_application_detail__c
+                                     where DealerID__c = :String.valueOf(loanerApply.DealerOrder_From__c).subString(0,15)
+                                     AND Id not in : lend_DetName
+                                     AND LOANER__r.EC_Code__c in : ecCodeList
+                                     AND Lend_Det__c = true 
+                                     AND is_distribution__c = false 
+                                     order by Name];
+                system.debug('1');
+     //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'loanerApplyLendDetSelected. ' + loanerApplyLendDetSelected.size()));
+     //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'ecCodeList.' + ecCodeList.size()));
+            }else{
+                loanerApplyLendDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Rental_Start_Date__c,
+                                            LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,LOANER__r.Description
+                                            ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c
+                                            ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
+                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
+                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
+                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,Remark__c,LOANER__r.Remarks2__c,loaner_application__r.loaner_request_number__c
+                                        ,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c,LOANER__r.Name
+                                     from  loaner_application_detail__c
+                                     where DealerID__c = :String.valueOf(loanerApply.DealerOrder_From__c).subString(0,15)
+                                     AND Id not in : lend_DetName
+                                     AND Lend_Det__c = true 
+                                     AND is_distribution__c = false 
+                                     order by Name];
+                system.debug('2');
+            }
+            
+            for(Integer i = 0; i < loanerApplyLendDetSelected.size(); i++){
+                if (i == Select_Limit) {Over_Limit=true; break;}
+                loanerAssetSelected.add(loanerApplyLendDetSelected[i].LOANER__c);
+                EquipmentSetInfo midData = new EquipmentSetInfo(loanerApplyLendDetSelected[i]);
+                midData.firstDet = true;
+                midData.check = false;
+                midData.oldcheck = false;
+                equipmentSetRecords.add(midData);
+            }
+            system.debug(equipmentSetRecords.size());
+        }else{
+            //闈炶浆鍊熷垎鏀�
+            /* WLIG-C3N6BW XHL 鏍锋満鍒嗛厤鏄剧ず鍏跺畠鍒嗛噹鐨勪繚鏈夎澶囷紝鏁呮坊鍔犺繃婊ゆ潯浠�
+            AND Equipment_Type__c = :loanerApply.Equipment_Type__c
+             */
+
+            List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c, OT_Code__c,AssetType__c,Description,
+                                                EC_Code__c, status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c
+                                                ,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,Name__c,ProductName__c,Rental_Start_Date__c 
+                                            from Asset
+                                            WHERE EC_Code__c in : ecCodeList
+                                            AND Id not in : loanerindividualList 
+                                            AND Equipment_Type__c = :loanerApply.Equipment_Type__c
+                                            order by EC_Code__c];
+            for (Asset query : queryList) {
+                loanerAssetSelected.add(query.Id);
+            }
+            system.debug(queryList);
+            // 鏂版槑缁嗚鍋氭垚
+            Integer j = 0;
+            for (Integer i = 0;  i < queryList.size(); i++) {
+                if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+                j++;
+            }
+        }
+        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
+            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
+        }
+        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
+        loanerApply.Prepare_Day__c = prepareDay;
+
+        //鍏朵粬宸插瓨鍦ㄧ殑鏍锋満鍊熷嚭鍘嗗彶
+        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
+                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
+                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
+                                    ,Allocated_Det__c,LendPrimary_Name__c,Remark__c,LOANER__r.Remarks2__c
+                                 from  loaner_application_detail__c
+                                 where loaner_application__c != :loanerApplyId
+                                 and LOANER__c in :loanerAssetSelected
+                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
+                                 AND Arrival_wh_Date__c = null
+                                and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
+                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
+                                 AND StockUp__c = false
+                                 order by Name];
+                                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'others銆�' + others[0].Id));
+        Map<String, Date> othersMap = new Map<String,Date>();
+
+        for (loaner_application_detail__c other : others) {
+            if (othersMap.containsKey(other.LOANER__c)) {
+                continue;
+            } else {
+                if(other.Received_loaner_Date__c == null){
+                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
+                }else{
+                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
+                }
+            }
+        }*/
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'othersMap + ' + othersMap));
+
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
+            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
+            info.SEdayCount  = dayCount;
+            /*if(info.aset.Status == '鍦ㄥ簱'){
+                if(othersMap.containsKey(info.aset.Id)){
+                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
+                }else{
+                    info.earliest_Lend_Date = Date.today();
+                }
+            }*/
+        }
+        system.debug('end');
+    }
+
+    // 鑾峰彇鏍锋満濂楄
+    public void getLoanerSetdet() {
+        //宸查�夋嫨涓綋绠$悊鏍锋満
+        List<String> loanerindividualList = new List<String>();
+        //// 鐢婚潰宸叉墦鍕剧殑鏄庣粏淇濈暀
+        List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            if (info.check == true) {
+                selectedloanerRecords.add(info);
+                if(String.valueOf(info.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
+                    loanerindividualList.add(info.aset.Id);
+                }
+            }
+        }
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+        loanerAssetSelected = new list<String>();
+        for (EquipmentSetInfo info : selectedloanerRecords) {
+            loanerAssetSelected.add(info.aset.Id);
+        }
+
+        // 宸插瓨鍦ㄦ槑缁嗚鍋氭垚
+        equipmentSetRecords.addAll(selectedloanerRecords);
+
+        // 鏍锋満set涓墍鏈夋牱鏈�
+        List<String> loanerSetDetIDList = new List<String>();
+        
+        for(Loaner_Set_Detail__c lSD : [SELECT Id,Asset__c FROM Loaner_Set_Detail__c WHERE Loaner_Set__c = :setId]){
+            loanerSetDetIDList.add(lSD.Asset__c);
+        }
+        /* WLIG-C3N6BW XHL 鏍锋満鍒嗛厤鏄剧ず鍏跺畠鍒嗛噹鐨勪繚鏈夎澶囷紝鏁呮坊鍔犺繃婊ゆ潯浠�
+            AND Equipment_Type__c = :loanerApply.Equipment_Type__c
+         */
+        List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c,Name__c,AssetType__c,Loaner__c,Rental_Start_Date__c ,
+                                        OT_Code__c, EC_Code__c, status,Count_can_allocate_F__c,Description,
+                                        RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,ProductName__c
+                                    from Asset
+                                    where Id in :loanerSetDetIDList
+                                    AND Id not in : loanerindividualList
+                                    AND Equipment_Type__c = :loanerApply.Equipment_Type__c
+                                    /*AND status = '鍦ㄥ簱'*/];
+        for (Asset query : queryList) {
+            loanerAssetSelected.add(query.Id);
+        }
+        // 鏂版槑缁嗚鍋氭垚
+        Integer j = 0;
+        for (Integer i = 0;  i < queryList.size(); i++) {
+            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+                j++;
+            //}
+        }
+        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
+            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
+        }
+        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
+        loanerApply.Prepare_Day__c = prepareDay;
+
+        //鍏朵粬宸插瓨鍦ㄧ殑鏍锋満鍊熷嚭鍘嗗彶
+        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
+                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
+                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
+                                    ,Allocated_Det__c,LendPrimary_Name__c
+                                 from  loaner_application_detail__c
+                                 where loaner_application__c != :loanerApplyId
+                                 and LOANER__c in :loanerAssetSelected
+                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
+                                 AND Arrival_wh_Date__c = null
+                                and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
+                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
+                                 AND StockUp__c = false
+                                 order by Name];
+                                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'others銆�' + others[0].Id));
+        Map<String, Date> othersMap = new Map<String,Date>();
+
+        for (loaner_application_detail__c other : others) {
+            if (othersMap.containsKey(other.LOANER__c)) {
+                continue;
+            } else {
+                if(other.Received_loaner_Date__c == null){
+                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
+                }else{
+                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
+                }
+            }
+        }*/
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'othersMap + ' + othersMap));
+
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
+            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
+            info.SEdayCount  = dayCount;
+            /*if(info.aset.Status == '鍦ㄥ簱'){
+                if(othersMap.containsKey(info.aset.Id)){
+                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
+                }else{
+                    info.earliest_Lend_Date = Date.today();
+                }
+            }*/
+        }
+    }
+
+    // 妫�绱㈡牱鏈�
+    public void searchLoanerApp() {
+        //宸查�夋嫨涓綋绠$悊鏍锋満
+        List<String> loanerindividualList = new List<String>();
+    	//// 鐢婚潰宸叉墦鍕剧殑鏄庣粏淇濈暀
+    	List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
+    	for (EquipmentSetInfo info : equipmentSetRecords) {
+            if (info.check == true) {
+                selectedloanerRecords.add(info);
+                if(String.valueOf(info.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
+                    loanerindividualList.add(info.aset.Id);
+                }
+            }else{
+                if(info.oldcheck == true && info.lad != null){
+                    del.add(info.lad);
+                }
+            }
+        }
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+        loanerAssetSelected = new list<String>();
+        for (EquipmentSetInfo info : selectedloanerRecords) {
+            loanerAssetSelected.add(info.aset.Id);  
+        }
+        // 宸插瓨鍦ㄦ槑缁嗚鍋氭垚
+        equipmentSetRecords.addAll(selectedloanerRecords);
+        // 鎵�鏈塃Ccode鏍锋満
+        String ecCodeTail = '(\'';
+        for(Integer i = 0 ; i< ecCodeList.size();i++){
+            if(i<ecCodeList.size()-1){
+                ecCodeTail += ecCodeList[i]+'\',\'';
+            }else{
+                ecCodeTail += ecCodeList[i]+'\')';
+            }
+        }
+
+        String loanerindTail = '(\'';
+        for(Integer i = 0 ; i< loanerindividualList.size();i++){
+            if(i<loanerindividualList.size()-1){
+                loanerindTail += loanerindividualList[i]+'\',\'';
+            }else{
+                loanerindTail += loanerindividualList[i]+'\')';
+            }
+        }
+
+        String soql = 'select Id,Name, SerialNumber, Loaner__c,Internal_Asset_number__c, OT_Code__c,EC_Code__c, Name__c,ProductName__c,AssetType__c,Description,Rental_Start_Date__c,';
+              soql += ' status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c from Asset WHERE Id != null ';
+
+
+        if (!String.isBlank(assName)) {
+            soql += ' and Name like \'%' + String.escapeSingleQuotes(assName.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(rec.OT_Code__c)) {
+            soql += ' and OT_Code__c like \'%' + String.escapeSingleQuotes(rec.OT_Code__c.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(assECcode)) {
+            soql += ' and EC_Code__c like \'%' + String.escapeSingleQuotes(assECcode.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(rec.Equipment_Type__c)) {
+            soql += ' and Equipment_Type__c = \'' + String.escapeSingleQuotes(rec.Equipment_Type__c) + '\'';
+        }
+        if (!String.isBlank(rec.loaner_place__c)) {
+            soql += ' and loaner_place__c = \'' + String.escapeSingleQuotes(rec.loaner_place__c) + '\'';
+        }
+        if (!String.isBlank(rec.Status)) {
+            soql += ' and status = \'' + String.escapeSingleQuotes(rec.Status) + '\'';
+        }
+         if (!String.isBlank(rec.SerialNumber)) {
+            soql += ' and SerialNumber like \'%' + String.escapeSingleQuotes(rec.SerialNumber.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(rec.Internal_Asset_number__c)) {
+            soql += ' and Internal_Asset_number__c like \'%' + String.escapeSingleQuotes(rec.Internal_Asset_number__c.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        /**
+         *2018/10/15
+         *NDT/ANI鍒嗛噹淇敼
+        */
+
+        if(!String.isBlank(rec.Remarks2__c)){
+            soql +=  ' and Remarks2__c like \'%' + String.escapeSingleQuotes(rec.Remarks2__c.trim().replaceAll('%','\\%')) + '%\'';
+        }
+
+        if (loanerindividualList.size() > 0) {
+            soql += ' and Id not in ' + loanerindTail;
+        }
+        if (ecCodeList.size() > 0) {
+            soql += ' and EC_Code__c in ' + ecCodeTail;
+        }
+
+        system.debug(soql);
+        List<Asset> queryList = Database.query(soql);
+        /*List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c, OT_Code__c,
+                                            EC_Code__c, status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c
+                                        from Asset
+                                        WHERE EC_Code__c in : ecCodeList
+                                        AND Id not in : loanerindividualList
+                                        order by EC_Code__c];*/
+        for (Asset query : queryList) {
+            loanerAssetSelected.add(query.Id);
+            loanerindividualList.add(query.Id);
+        }
+        system.debug(queryList);
+        // 鏂版槑缁嗚鍋氭垚
+        Integer j = 0;
+        for (Integer i = 0;  i < queryList.size(); i++) {
+            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+                j++;
+            //}
+        }
+
+
+        // 鎵�鏈夋牱鏈�
+        soql = this.makeSoql(assName, rec.OT_Code__c, assECcode, rec.Equipment_Type__c, rec.loaner_place__c, rec.Status,rec.SerialNumber,rec.Internal_Asset_number__c, loanerindividualList);
+        soql += ' order by RecordType.Name asc limit ' + (Select_Limit + 1);
+        system.debug(soql);
+        queryList = Database.query(soql);
+        for (Asset query : queryList) {
+            loanerAssetSelected.add(query.Id);
+        }
+        system.debug(queryList);
+        // 鏂版槑缁嗚鍋氭垚
+        j = 0;
+        for (Integer i = 0;  i < queryList.size(); i++) {
+            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+                j++;
+            //}
+        }
+        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
+            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
+        }
+        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
+        loanerApply.Prepare_Day__c = prepareDay;
+
+        //鍏朵粬宸插瓨鍦ㄧ殑鏍锋満鍊熷嚭鍘嗗彶
+        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
+                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
+                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
+                                    ,Allocated_Det__c,LendPrimary_Name__c
+                                 from  loaner_application_detail__c
+                                 where loaner_application__c != :loanerApplyId
+                                 and LOANER__c in :loanerAssetSelected
+                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
+                                 AND Arrival_wh_Date__c = null
+                                and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
+                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
+                                 AND StockUp__c = false
+                                 order by Name];
+                                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'others銆�' + others[0].Id));
+        Map<String, Date> othersMap = new Map<String,Date>();
+
+        for (loaner_application_detail__c other : others) {
+            if (othersMap.containsKey(other.LOANER__c)) {
+                continue;
+            } else {
+                if(other.Received_loaner_Date__c == null){
+                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
+                }else{
+                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
+                }
+            }
+        }*/
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'othersMap + ' + othersMap));
+
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
+            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
+            info.SEdayCount  = dayCount;
+            /*if(info.aset.Status == '鍦ㄥ簱'){
+                if(othersMap.containsKey(info.aset.Id)){
+                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
+                }else{
+                    info.earliest_Lend_Date = Date.today();
+                }
+            }*/
+        }
+        // 鏄剧ず鏁版嵁鏉℃暟淇℃伅
+        makeMessage();
+    }
+
+    public PageReference save() {
+        system.debug(isManager);    
+        Boolean hasError = false;
+        Boolean chukuStatus = false;
+        String strMessage = null;
+        Map<String,String> asetEquipmentMap = new Map<String,String>();
+        List<String> asetEquipmentList = new List<String>();
+        Set<String> typeSet = new Set<String>();
+        Set<String> LoanerSet = new Set<String>();
+        if(loanerApply.Equipment_Type__c == 'IE' && loanerApply.Remind_Date__c != null){
+            if(loanerApply.Remind_Date__c > Date.today()){
+                hasError = true;
+                strMessage = '璇锋彁鍓�3涓伐浣滄棩鍒嗛厤鏍锋満銆�';
+            }
+        }
+
+        Integer num = 0;
+        /*if(isCancel){
+            hasError = true;
+            strMessage = '鎮ㄧ殑璐︽埛宸茶鍐荤粨锛岃鑱旂郴绠$悊鍛樸��';
+        }*/
+
+        /*if(loanerApply.Rental_Start_Date__c == null){
+            hasError = true;
+            strMessage = '璇疯緭鍏鍊熷嚭寮�濮嬫棩]';
+        }
+        if(loanerApply.Rental_End_Date__c == null){
+            hasError = true;
+            strMessage = '璇疯緭鍏鍊熷嚭缁撴潫鏃';
+        }
+        if (loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null && loanerApply.Rental_Start_Date__c > loanerApply.Rental_End_Date__c) {
+            hasError = true;
+            strMessage = '[鍊熷嚭寮�濮嬫棩]蹇呴』灏忎簬绛変簬[鍊熷嚭缁撴潫鏃';
+        }*/
+        for (EquipmentSetInfo ass : equipmentSetRecords)  {
+            if(ass.check == true){
+                
+                asetEquipmentMap.put(ass.aset.loaner_place__c, ass.aset.loaner_place__c);
+                asetEquipmentList.add(ass.aset.loaner_place__c);
+                typeSet.add(ass.aset.AssetType__c);
+                if(loanerApply.Equipment_Type__c  == 'BS' && loanerApply.Loaner_LendOrder__c){
+                    LoanerSet.add(ass.lad.loaner_application__c);
+                    num++;
+                }
+            }
+        }
+
+        if ((loanerApply.Equipment_Type__c != 'IE' && loanerApply.Equipment_Type__c != 'NDT' && loanerApply.Equipment_Type__c != 'ANI')  && asetEquipmentMap.size() > 1) {
+            hasError = true;
+            strMessage = 'IE浠ュ鐨勭敵璇峰崟锛屽彧鑳藉�熶竴涓瓨鏀惧湴鐨勬牱鏈恒��';
+        }
+        if ((loanerApply.Equipment_Type__c != 'IE' && loanerApply.Equipment_Type__c != 'NDT' && loanerApply.Equipment_Type__c != 'ANI') && loanerApply.Approval_Status__c == false && asetEquipmentMap.size() > 1) {
+            hasError = true;
+            strMessage = '鍙兘鍊熶竴涓瓨鏀惧湴鐨勬牱鏈恒��';
+        }
+        if(loanerApply.Equipment_Type__c  == 'BS' && typeSet.size()>1 && typeSet.contains('缁翠慨閮ㄤ欢') ){
+            hasError = true;
+            strMessage = '缁翠慨浜у搧鍙兘鍗曠嫭鍑哄�熴��'; 
+        }
+        if(loanerApply.Equipment_Type__c  == 'BS' && LoanerSet.size()>1 && loanerApply.Loaner_LendOrder__c){
+            hasError = true;
+            strMessage = '鍙兘杞�熶竴涓�熺敤鍗曠殑鏍锋満銆�'; 
+        }
+
+        List<loaner_application_detail__c> temp = [select id from loaner_application_detail__c where loaner_application__c = :LoanerSet and Receipt_Status__c = 'OK'];
+        system.debug(temp.size()+'------'+num);
+        if(temp.size() > num && loanerApply.Equipment_Type__c  == 'BS' && loanerApply.Loaner_LendOrder__c){
+            hasError = true;
+            strMessage = '杞�熸椂璇烽�夋嫨鐢宠鍗曞唴鍏ㄩ儴鏍锋満銆�'; 
+        }
+
+        if (hasError) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, strMessage));
+            return null;
+        }
+        Savepoint sp = Database.setSavepoint();
+        try{
+            //杞�熷垎鏀�
+            if(loanerApply.Loaner_LendOrder__c){
+                Map<String,String> lendOrderName = new Map<String,String>();
+                List<loaner_application_detail__c> ins = New List<loaner_application_detail__c>();
+                //del = New List<loaner_application_detail__c>();
+                List<String> lendPrimaryList = new List<String>();
+                List<String> delendIDList = new List<String>();
+                Map<String,Decimal> asetNoMap = new Map<String,Decimal>();
+                List<loaner_application_detail__c> oldList = new List<loaner_application_detail__c>();
+                Integer indexNum = 1;
+                Integer i = 1;
+                if (loanerApply.Loaner_LendFrom__r.Rental_Start_Date__c > loanerApply.Rental_Start_Date__c || loanerApply.Loaner_LendFrom__r.Rental_End_Date__c < loanerApply.Rental_Start_Date__c) {
+                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[鍊熷嚭寮�濮嬫棩]蹇呴』杈撳叆杞�熺敵璇峰崟寮�濮嬪拰缁撴潫涔嬮棿鐨勬棩鏈熴��'));
+                    return null;
+                }
+                for (EquipmentSetInfo ass : equipmentSetRecords)  {
+                    if(ass.check == true){
+                        //鍒ゆ柇鏄惁宸茬粡鍒嗛厤锛屽�熷嚭鍚庝笉璁$畻鏁伴噺
+                        if(ass.lad.Allocated_Det__c == true){
+
+                        }else{
+                            if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
+                                if(asetNoMap.containsKey(ass.aset.Id)){
+                                    if(ass.deatilNo > 0){
+                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + ass.deatilNo);
+                                    }else if(ass.lad.RAESD_Status__c == '宸插垎閰�'){
+                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + 1);
+                                    }
+                                }else{
+                                    if(ass.deatilNo > 0){
+                                        asetNoMap.put(ass.aset.Id,ass.deatilNo);
+                                    }else if(ass.lad.RAESD_Status__c == '宸插垎閰�'){
+                                        asetNoMap.put(ass.aset.Id,1);
+                                    }
+                                }
+                                if(ass.aset.Count_can_allocate_F__c < asetNoMap.get(ass.aset.Id)){
+                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '鏍锋満 ' + ass.aset.EC_Code__c + ' 鍊熷嚭鏁伴噺瓒呭嚭鍙垎閰嶆暟閲忋��'));
+                                    return null;
+                                }
+                            }
+                        }
+                        if(ass.lad.Name == null && String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 && ass.aset.status != '鍦ㄥ簱'){
+                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '绗�' + indexNum +'琛屾暟鎹殑鐘舵�佹槸' + ass.aset.status + '锛屾棤娉曞啀鍒嗛厤銆�'));
+                            return null;
+                        }
+                        if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2 && ass.aset.Count_can_allocate_F__c <= 0){
+                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '绗�' + indexNum +'琛屾暟鎹殑鍙互鍒嗛厤鏁伴噺鏄�'+ ass.aset.Count_can_allocate_F__c +'锛屾棤娉曞啀鍒嗛厤銆�'));
+                            return null;
+                        }
+                        if (ass.firstDet == false && loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_Start_Date__c < ass.earliest_Lend_Date) {
+                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '绗�' + indexNum +'琛屾暟鎹殑[鍊熷嚭寮�濮嬫棩]蹇呴』杈撳叆浠嶽鏈�鏃╁彲鍊熷嚭鏃寮�濮嬭捣鐨勬棩鏈熴��'));
+                            return null;
+                        }
+                        if(ass.deatilNo > 0){
+                            for(Integer j = 0;  j < ass.deatilNo; j++){
+                                loaner_application_detail__c insertDet = new loaner_application_detail__c();
+                                String str = string.valueOf(i);
+                                if(str.length() == 1){
+                                    str = '0' + str;
+                                }
+                                if(String.isNotEmpty(ass.lad.Id)){
+                                    if(ass.firstDet && ass.lad.loaner_application__c != loanerApplyId){
+                                        lendOrderName.put(ass.lad.loaner_application__r.loaner_request_number__c, ass.lad.loaner_application__r.loaner_request_number__c);
+                                        insertDet.loanerOrder_Status__c = ass.lad.loaner_application__c +',' + ass.lad.loaner_application__r.Status__c;
+                                        insertDet.LendPrimary_Name__c = ass.lad.Id;
+                                        insertDet.LOANER__c = ass.aset.Id;
+                                        ass.lad.is_distribution__c = true;
+                                        oldList.add(ass.lad);
+                                    }else{
+                                        insertDet.Id = ass.lad.Id;
+                                    }
+                                    insertDet.loaner_application__c = loanerApplyId;
+                                    insertDet.RAESD_Status__c = '宸插垎閰�';
+                                    insertDet.Allocate_Date__c = Date.today();
+                                }
+                                //else{
+                                //    insertDet.loaner_application__c = loanerApplyId;
+                                //    insertDet.RAESD_Status__c = '宸插垎閰�';
+                                //    insertDet.LOANER__c = ass.aset.Id;
+                                //    insertDet.Allocate_Date__c = Date.today();
+                                //}
+                                if(String.isNotBlank(ass.lad.LendPrimary_Name__c)) lendPrimaryList.add(ass.lad.LendPrimary_Name__c);
+                                insertDet.Name = loanerApply.Name + '-' + str;
+                                insertDet.Remark__c = ass.remark;
+                                ins.add(insertDet);
+                                i ++;
+                            }
+                        }
+                        /*else{
+                            loaner_application_detail__c insertDet = new loaner_application_detail__c();
+                            String str = string.valueOf(i);
+                            if(str.length() == 1){
+                                str = '0' + str;
+                            }
+                            if(String.isNotEmpty(ass.lad.Id)){
+                                if(ass.firstDet && ass.lad.loaner_application__c != loanerApplyId){
+                                    lendOrderName.put(ass.lad.loaner_application__r.loaner_request_number__c, ass.lad.loaner_application__r.loaner_request_number__c);
+                                    insertDet.loanerOrder_Status__c = ass.lad.loaner_application__c +',' + ass.lad.loaner_application__r.Status__c;
+                                    insertDet.LendPrimary_Name__c = ass.lad.Id ;
+                                    insertDet.LOANER__c = ass.aset.Id;
+                                }else{
+                                    insertDet.Id = ass.lad.Id;
+                                }
+                                insertDet.loaner_application__c = loanerApplyId;
+                                insertDet.RAESD_Status__c = '宸插垎閰�';
+                                insertDet.Allocate_Date__c = Date.today();
+                            }
+                            //else{
+                            //    insertDet.loaner_application__c = loanerApplyId;
+                            //    insertDet.RAESD_Status__c = '宸插垎閰�';
+                            //    insertDet.Allocate_Date__c = Date.today();
+                            //    insertDet.LOANER__c = ass.aset.Id;
+                            //}
+                            if(String.isNotBlank(ass.lad.LendPrimary_Name__c)) lendPrimaryList.add(ass.lad.LendPrimary_Name__c);
+                            insertDet.Name = loanerApply.Name + '-' + str;
+                            insertDet.Remark__c = ass.remark;
+                            ins.add(insertDet);
+                            i ++;
+                        }*/
+                    }else if(ass.oldcheck == true && ass.firstDet == false){
+                        loaner_application_detail__c delDet = new loaner_application_detail__c();
+                        delDet.Id = ass.lad.Id;
+                        del.add(delDet);
+                    }else if(ass.oldcheck == true && ass.firstDet == true){
+                        delendIDList.add(ass.lad.Id);
+
+
+                    }
+                    indexNum += 1;
+                }
+                loanerApply.loaner_place__c = '';
+                if(asetEquipmentMap.size() == 1){
+                    if(asetEquipmentList.size() > 0) loanerApply.loaner_place__c = asetEquipmentList[0];
+                }
+                this.getleadUser();
+                
+                this.moveDetail(delendIDList);
+                //return null;
+                //this.addDetail(inlendIDList);
+
+                //鍒犻櫎鍙栨秷鐨勬牱鏈烘槑缁�
+                if (del.size()>0){
+                    delete del;
+                }
+                if(ins.size()>0){
+                    upsert ins;
+                }
+                if(oldList.size()>0){
+                    update oldList;
+                }
+                for(loaner_application_detail__c lad : [SELECT Id,loaner_application__r.loaner_request_number__c FROM loaner_application_detail__c WHERE Id in : lendPrimaryList]){
+                    lendOrderName.put(lad.loaner_application__r.loaner_request_number__c, lad.loaner_application__r.loaner_request_number__c);
+                }
+                loanerApply.AllLead_OrderName__c = '';
+                if(lendOrderName.size() > 0){
+                    for(String lon : lendOrderName.keySet()){
+                        loanerApply.AllLead_OrderName__c += lon + ' \r\n ';
+                    }
+                }
+                system.debug(typeSet);
+                if(loanerApply.Equipment_Type__c  == 'BS' &&  typeSet.contains('缁翠慨閮ㄤ欢')){
+                    loanerApply.Is_Repair_Products__c = true;
+                }else{
+                    loanerApply.Is_Repair_Products__c = false;
+                }
+
+                if(loanerApply.Equipment_Type__c == 'BS' && typeSet.contains('楂樼鏍锋満')){
+                    loanerApply.Is_High_end_Products__c = true;
+                }else{
+                    loanerApply.Is_High_end_Products__c = false;
+                }
+                update loanerApply;
+
+
+            }else{
+                //闈炶浆鍊熷垎鏀�
+                List<loaner_application_detail__c> ins = New List<loaner_application_detail__c>();
+                //del = New List<loaner_application_detail__c>();
+                Map<String,Decimal> asetNoMap = new Map<String,Decimal>();
+                Integer indexNum = 1;
+                Integer i = 1;
+                for (EquipmentSetInfo ass : equipmentSetRecords)  {
+                    if(ass.check == true){
+                        //鍒ゆ柇鏄惁宸茬粡鍒嗛厤锛屽�熷嚭鍚庝笉璁$畻鏁伴噺
+                        if(ass.lad.Allocated_Det__c == true){
+
+                        }else{
+                            if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
+                                if(asetNoMap.containsKey(ass.aset.Id)){
+                                    if(ass.deatilNo > 0){
+                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + ass.deatilNo);
+                                    }else if(ass.lad.RAESD_Status__c == '宸插垎閰�'){
+                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + 1);
+                                    }
+                                }else{
+                                    if(ass.deatilNo > 0){
+                                        asetNoMap.put(ass.aset.Id,ass.deatilNo);
+                                    }else if(ass.lad.RAESD_Status__c == '宸插垎閰�'){
+                                        asetNoMap.put(ass.aset.Id,1);
+                                    }
+                                }
+                                if(ass.aset.Count_can_allocate_F__c < asetNoMap.get(ass.aset.Id)){
+                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '鏍锋満 ' + ass.aset.EC_Code__c + ' 鍊熷嚭鏁伴噺瓒呭嚭鍙垎閰嶆暟閲忋��'));
+                                    return null;
+                                }
+                            }
+                        }
+                        if(ass.lad.Name == null && String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 && ass.aset.status != '鍦ㄥ簱'){
+                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '绗�' + indexNum +'琛屾暟鎹殑鐘舵�佹槸' + ass.aset.status + '锛屾棤娉曞啀鍒嗛厤銆�'));
+                            return null;
+                        }
+                        if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2 && ass.aset.Count_can_allocate_F__c <= 0){
+                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '绗�' + indexNum +'琛屾暟鎹殑鍙互鍒嗛厤鏁伴噺鏄�'+ ass.aset.Count_can_allocate_F__c +'锛屾棤娉曞啀鍒嗛厤銆�'));
+                            return null;
+                        }
+                        //if (loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_Start_Date__c < ass.earliest_Lend_Date) {
+                        //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '绗�' + indexNum +'琛屾暟鎹殑[鍊熷嚭寮�濮嬫棩]蹇呴』鍏ュ姏浠嶽鏈�鏃╁彲鍊熷嚭鏃寮�濮嬭捣鐨勬棩鏈熴��'));
+                        //     return null;
+                        //}
+                        if(!isManager){
+                            if(ass.deatilNo > 0){
+                                for(Integer j = 0;  j < ass.deatilNo; j++){
+                                    loaner_application_detail__c insertDet = new loaner_application_detail__c();
+                                    String str = string.valueOf(i);
+                                    if(str.length() == 1){
+                                        str = '0' + str;
+                                    }
+                                    if(String.isNotBlank(ass.lad.Id)){
+                                        insertDet.Id = ass.lad.Id;
+                                        if(loanerApply.Status__c == '椹冲洖'){
+                                            insertDet.RAESD_Status__c = '宸插垎閰�';
+                                        }
+                                    }else{
+                                        insertDet.loaner_application__c = loanerApplyId;
+                                        insertDet.LOANER__c = ass.aset.Id;
+                                    }
+                                    insertDet.Name = loanerApply.Name + '-' + str;
+                                    insertDet.RAESD_Status__c = '宸插垎閰�';
+                                    insertDet.Allocate_Date__c = Date.today();
+                                    insertDet.Remark__c = ass.remark;
+                                    ins.add(insertDet);
+                                    i ++;
+                                }
+                            }else{
+                                loaner_application_detail__c insertDet = new loaner_application_detail__c();
+                                String str = string.valueOf(i);
+                                if(str.length() == 1){
+                                    str = '0' + str;
+                                }
+                                if(String.isNotBlank(ass.lad.Id)){
+                                    insertDet.Id = ass.lad.Id;
+                                    if(loanerApply.Status__c == '椹冲洖'){
+                                        insertDet.RAESD_Status__c = '宸插垎閰�';
+                                    }
+                                }else{
+                                    insertDet.loaner_application__c = loanerApplyId;
+                                    insertDet.LOANER__c = ass.aset.Id;
+                                }
+                                insertDet.Name = loanerApply.Name + '-' + str;
+                                insertDet.RAESD_Status__c = '宸插垎閰�';
+                                insertDet.Allocate_Date__c = Date.today();
+                                insertDet.Remark__c = ass.remark;
+                                ins.add(insertDet);
+                                i ++;
+                            }
+                        }else{
+                            if(ass.deatilNo > 0){
+                                for(Integer j = 0;  j < ass.deatilNo; j++){
+                                    loaner_application_detail__c insertDet = new loaner_application_detail__c();
+                                    String str = string.valueOf(i);
+                                    if(str.length() == 1){
+                                        str = '0' + str;
+                                    }
+                                    if(String.isNotBlank(ass.lad.Id)){
+                                        insertDet.Id = ass.lad.Id;
+                                        if(loanerApply.Status__c == '椹冲洖'){
+                                            insertDet.RAESD_Status__c = '宸插垎閰�';
+                                        }
+                                    }else{
+                                        insertDet.loaner_application__c = loanerApplyId;
+                                        if(loanerApply.Status__c == '宸叉壒鍑�'){
+                                            insertDet.RAESD_Status__c = '宸叉壒鍑�';
+                                        }else if(loanerApply.Status__c == '鐢宠涓�'){
+                                            if(loanerApply.Equipment_Type__c == 'IE' && loanerApply.Approval_Step__c == 1){
+                                                insertDet.RAESD_Status__c = '宸插垎閰�';
+                                            }else{
+                                                insertDet.RAESD_Status__c = '鐢宠涓�';
+                                            }
+                                        }else if(loanerApply.Status__c == '鑽夋涓�' || loanerApply.Status__c == '椹冲洖' || loanerApply.Status__c == '閿�鍞媴褰撴壒鍑�'){
+                                            insertDet.RAESD_Status__c = '宸插垎閰�';
+                                        }else{
+                                            insertDet.RAESD_Status__c = '宸插嚭搴撴寚绀�';
+                                            chukuStatus = true;
+                                        }
+                                        insertDet.LOANER__c = ass.aset.Id;
+                                    }
+                                    insertDet.Name = loanerApply.Name + '-' + str;
+                                    insertDet.Allocate_Date__c = Date.today();
+                                    insertDet.Remark__c = ass.remark;
+                                    ins.add(insertDet);
+                                    i ++;
+                                }
+                            }else{
+                                loaner_application_detail__c insertDet = new loaner_application_detail__c();
+                                String str = string.valueOf(i);
+                                if(str.length() == 1){
+                                    str = '0' + str;
+                                }
+                                if(String.isNotBlank(ass.lad.Id)){
+                                    insertDet.Id = ass.lad.Id;
+                                    if(loanerApply.Status__c == '椹冲洖'){
+                                        insertDet.RAESD_Status__c = '宸插垎閰�';
+                                    }
+                                }else{
+                                    insertDet.loaner_application__c = loanerApplyId;
+                                    if(loanerApply.Status__c == '宸叉壒鍑�'){
+                                        insertDet.RAESD_Status__c = '宸叉壒鍑�';
+                                    }else if(loanerApply.Status__c == '鐢宠涓�'){
+                                        if(loanerApply.Equipment_Type__c == 'IE' && loanerApply.Approval_Step__c == 1){
+                                            insertDet.RAESD_Status__c = '宸插垎閰�';
+                                        }else{
+                                            insertDet.RAESD_Status__c = '鐢宠涓�';
+                                        }
+                                    }else if(loanerApply.Status__c == '鑽夋涓�'  || loanerApply.Status__c == '椹冲洖' || loanerApply.Status__c == '閿�鍞媴褰撴壒鍑�'){
+                                        insertDet.RAESD_Status__c = '宸插垎閰�';
+                                    }else{
+                                        insertDet.RAESD_Status__c = '宸插嚭搴撴寚绀�';
+                                        chukuStatus = true;
+                                    }
+                                    insertDet.LOANER__c = ass.aset.Id;
+                                }
+                                insertDet.Name = loanerApply.Name + '-' + str;
+                                insertDet.Allocate_Date__c = Date.today();
+                                insertDet.Remark__c = ass.remark;
+                                ins.add(insertDet);
+                                i ++;
+                            }
+                        }
+                        
+                    }else if(ass.oldcheck == true){
+                        loaner_application_detail__c delDet = new loaner_application_detail__c();
+                        delDet.Id = ass.lad.Id;
+                        del.add(delDet);
+                    }
+                    indexNum += 1;
+                }
+                loanerApply.loaner_place__c = '';
+                if(asetEquipmentMap.size() == 1){
+                    if(asetEquipmentList.size() > 0) loanerApply.loaner_place__c = asetEquipmentList[0];
+                }
+                if(chukuStatus == true)loanerApply.Status__c = '宸插嚭搴撴寚绀�';
+                
+                //鍒犻櫎鍙栨秷鐨勬牱鏈烘槑缁�
+                if(isManager && loanerApply.Manager_detail_Del__c == false){
+
+                }else{
+                    if (del.size()>0){
+                        delete del;
+                    }
+                }
+                if(ins.size()>0){
+                    upsert ins;
+                }
+                system.debug(typeSet);
+                if(loanerApply.Equipment_Type__c  == 'BS' &&  typeSet.contains('缁翠慨閮ㄤ欢')){
+                    loanerApply.Is_Repair_Products__c = true;
+                }else{
+                    loanerApply.Is_Repair_Products__c = false;
+                }
+
+                if(loanerApply.Equipment_Type__c == 'BS' && typeSet.contains('楂樼鏍锋満')){
+                    loanerApply.Is_High_end_Products__c = true;
+                }else{
+                    loanerApply.Is_High_end_Products__c = false;
+                }
+                update loanerApply;
+            }
+        }catch(Exception e){
+            ApexPages.addMessages(e);
+            Database.rollback(sp);
+            return  null;
+        }
+    	return new Pagereference('/'+loanerApplyId);
+    }
+    // 杩藉姞杞�熸槑缁�
+    /*public void addDetail(List<String> addlist) {
+        List<loaner_application_detail__c> addDetList = [select Id, Name,Receipt_Status__c,Receipt_Date__c
+                                 from  loaner_application_detail__c
+                                 WHERE Id in : addlist];
+        for(loaner_application_detail__c det : addDetList){
+            if(det.Receipt_Status__c != 'OK' && det.Receipt_Status__c == null){
+                det.Receipt_Status__c = 'OK';
+                det.Receipt_Date__c = Date.today();
+            }
+            //鏃ユ湡
+            det.Asset_Return_Date__c = Date.today();
+            det.Received_loaner_Date__c = Date.today();
+            det.After_Inspection_Date__c = Date.today();
+            det.Arrival_wh_Date__c = Date.today();
+            det.RAESD_Status__c = '宸插洖搴�';
+            //涓婃灦鍔犳垚
+             det.StockUp__c = true;
+            det.Check_lost_Item__c = 'OK';
+            det.Inspection_result_after__c = 'OK';
+            //鐗╂祦淇℃伅
+            det.Return_Track_Company__c = System.label.Default_Logistics_company;
+            det.Return_Track_Number__c = System.label.Default_Logistics_No;
+        }
+        update addDetList;
+
+
+    }*/
+    //鍙栨秷杞�熸槑缁�
+    public void moveDetail(List<String> movelist) {
+
+        if(moveList.size() == 0 || moveList == null){
+            return;
+        }
+
+       
+
+        List<loaner_application_detail__c> moveDetList = [select Id, Name,LendPrimary_Name__c,RAESD_Status__c
+                                       ,loanerOrder_Status__c
+                                 from  loaner_application_detail__c
+                                 WHERE Id in : movelist];
+
+        List<String> idList = new List<String>();
+        for(loaner_application_detail__c lad : moveDetList){
+            idList.add(lad.LendPrimary_Name__c);
+        }
+
+        List<loaner_application_detail__c> oldLadList = [SELECT id FROM loaner_application_detail__c WHERE id IN :idList ];
+        for(loaner_application_detail__c lad : oldLadList){
+            lad.is_distribution__c = false;
+        }
+        if(oldLadList.size() > 0) update oldLadList;
+
+        if(moveDetList.size() > 0 ) delete moveDetList;
+    }
+    // 鍙栨秷杞�熸槑缁�
+    /*public void moveDetail(List<String> movelist) {
+        List<String> deleteList = new List<String>();
+        Map<String,String> deleteMap = new Map<String,String>();
+        Map<String,String> deleteNameMap = new Map<String,String>();
+        Map<String,String> deleteOrderStatusMap = new Map<String,String>();
+
+        List<loaner_application_detail__c> moveDetList = [select Id, Name,LendPrimary_Name__c,RAESD_Status__c
+                                       ,loanerOrder_Status__c
+                                 from  loaner_application_detail__c
+                                 WHERE Id in : movelist];
+        Map<Id,loaner_application__c>  loaner_appMap= new Map<Id,loaner_application__c>();
+        for(loaner_application_detail__c det : moveDetList){
+            loaner_application__c loaner_app = new loaner_application__c();
+            if(String.isNotBlank(det.LendPrimary_Name__c)){
+                deleteList.add(det.LendPrimary_Name__c);
+                if(det.loanerOrder_Status__c.contains(',')){
+                    loaner_app.Id = det.loanerOrder_Status__c.split(',')[0];
+                    loaner_app.Status__c = det.loanerOrder_Status__c.split(',')[1];
+                    loaner_appMap.put(loaner_app.Id, loaner_app);
+                }
+            }
+        }
+        //鍙栧師鐢宠鏄庣粏鐨勫崟鍙稩D
+        List<loaner_application_detail__c> movedeleteList = [select Id,Name,loaner_application__c
+                                 from  loaner_application_detail__c
+                                 WHERE Id in : deleteList];
+        for(loaner_application_detail__c lapp : movedeleteList){
+            deleteMap.put(lapp.Id, lapp.loaner_application__c);
+            deleteNameMap.put(lapp.Id, lapp.Name);
+        }
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'deleteMap-----' + deleteMap));
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'deleteNameMap-----' + deleteNameMap));
+System.debug('deleteMap +++++' + deleteMap);
+        for(loaner_application_detail__c det : moveDetList){
+            if(String.isNotBlank(det.LendPrimary_Name__c)){
+                deleteList.add(det.LendPrimary_Name__c);
+                det.Name = deleteNameMap.get(det.LendPrimary_Name__c);
+                det.loaner_application__c = deleteMap.get(det.LendPrimary_Name__c);
+            }
+            det.LendPrimary_Name__c = '';
+        }
+
+        System.debug('moveDetList +++++' + moveDetList);
+
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'movedeleteList' + movedeleteList));
+        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'moveDetList' + moveDetList));
+        //return;
+        if(movedeleteList.size() > 0 ) delete movedeleteList;
+
+        update moveDetList;
+        if(loaner_appMap.size() > 0 ) update loaner_appMap.values();
+
+    }*/
+    // 鎺掑簭
+    public void sortTable() {
+        //宸查�夋嫨涓綋绠$悊鏍锋満
+        List<String> loanerindividualList = new List<String>();
+        //// 鐢婚潰宸叉墦鍕剧殑鏄庣粏淇濈暀
+        String strProd = null;
+        List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            if (info.check == true) {
+                selectedloanerRecords.add(info);
+            }else{
+                if(strProd==null || strProd.length()==0){
+                    strProd = '\'' + String.valueOf(info.aset.Id) + '\'';
+                }
+                else{
+                    strProd += ',\'' + String.valueOf(info.aset.Id) + '\'';
+                }
+            }
+        }
+        equipmentSetRecords = new List<EquipmentSetInfo>();
+        loanerAssetSelected = new list<String>();
+        //Map<String,String> equipmentSetSelectedMap = new Map<String,String>();
+        for (EquipmentSetInfo info : selectedloanerRecords) {
+            loanerAssetSelected.add(info.aset.Id);
+            //equipmentSetSelectedMap.put(info.aset.Id, info.aset.Id);
+        }
+
+        // 鎺掑簭
+        if (this.sortKey == this.preSortKey) {
+            // 鏂瑰悜銇屽銈忋倠銇伩
+            this.sortOrderAsc = !this.sortOrderAsc;
+            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '鈫�' : '鈫�');
+        } else {
+            this.sortOrderAsc = true;
+            this.sortOrder[Integer.valueOf(this.preSortKey)] = '銆�';
+            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '鈫�' : '鈫�');
+        }
+        this.preSortKey = this.sortKey;
+        // 鎵�鏈夊鍝乻et
+        String soql = this.makeSoql(assName, rec.OT_Code__c, assECcode, rec.Equipment_Type__c, rec.loaner_place__c, rec.Status,rec.SerialNumber,rec.Internal_Asset_number__c,loanerindividualList);
+        soql += ' AND Id IN (' + strProd + ')';
+        soql += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last') + ' limit ' + (Select_Limit + 1);
+        List<Asset> queryList = Database.query(soql);
+        for (Asset query : queryList) {
+            loanerAssetSelected.add(query.Id);
+        }
+
+        // 宸插瓨鍦ㄦ槑缁嗚鍋氭垚
+        //equipmentSetRecords.addAll(selectedloanerRecords);
+        for (Integer i = 0; i < selectedloanerRecords.size(); i++) {
+            // 201銈掕秴銇堛仧鍫村悎鍓�200銇伩銈掑嚭銇�
+            if (i == Select_Limit) {Over_Limit=true; break;}
+            equipmentSetRecords.add(selectedloanerRecords[i]);
+        }
+        // 鏂版槑缁嗚鍋氭垚
+        Integer j = 0;
+        for (Integer i = 0;  i < queryList.size(); i++) {
+            // 201銈掕秴銇堛仧鍫村悎鍓�200銇伩銈掑嚭銇�
+            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
+            //if (!equipmentSetSelectedMap.containsKey(queryList[i].Id)) {
+                j++;
+                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
+            //}
+        }
+        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
+            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
+        }
+        //Integer dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
+        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
+        loanerApply.Prepare_Day__c = prepareDay;
+
+        //鍏朵粬宸插瓨鍦ㄧ殑鏍锋満鍊熷嚭鍘嗗彶
+        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
+                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
+                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
+                                    ,Allocated_Det__c
+                                 from  loaner_application_detail__c
+                                 where loaner_application__c != :loanerApplyId
+                                 and LOANER__c in :loanerAssetSelected
+                                 AND Arrival_wh_Date__c = null
+                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
+                                 and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
+                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
+                                 AND StockUp__c = false
+                                 order by Name];
+        Map<String, Date> othersMap = new Map<String,Date>();
+
+        for (loaner_application_detail__c other : others) {
+            if (othersMap.containsKey(other.LOANER__c)) {
+                continue;
+            } else {
+                //othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
+                if(other.Received_loaner_Date__c == null){
+                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
+                }else{
+                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
+                }
+            }
+        }*/
+
+        for (EquipmentSetInfo info : equipmentSetRecords) {
+            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
+            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
+            info.SEdayCount  = dayCount;
+            /*if(info.aset.Status == '鍦ㄥ簱'){
+                if(othersMap.containsKey(info.aset.Id)){
+                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
+                }else{
+                    info.earliest_Lend_Date = Date.today();
+                }
+            }*/
+        }
+        // 鏄剧ず鏁版嵁鏉℃暟淇℃伅
+        makeMessage();
+    }
+
+    // 鍋氭垚妫�绱QL鏂�
+    private String makeSoql(String assName, String otCode, String eCcode, String equipmentType, String loanerPlace, String status,String serialNumber,String internal_Asset_No,List<String> exId) {
+        String sqlTail = '(\'';
+        for(Integer i = 0 ; i< exId.size();i++){
+            if(i<exId.size()-1){
+                sqlTail += exId[i]+'\',\'';
+            }else{
+                sqlTail += exId[i]+'\')';
+            }
+        }
+        String soql = 'select Id,Description,AssetType__c,Name, Name__c,ProductName__c,SerialNumber, Internal_Asset_number__c, OT_Code__c, EC_Code__c, status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,Rental_Start_Date__c  '
+                    + 'from Asset where Id != null ';
+
+        if (!String.isBlank(assName)) {
+            soql += ' and Name like \'%' + String.escapeSingleQuotes(assName.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(otCode)) {
+            soql += ' and OT_Code__c like \'%' + String.escapeSingleQuotes(otCode.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(eCcode)) {
+            soql += ' and EC_Code__c like \'%' + String.escapeSingleQuotes(eCcode.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (!String.isBlank(equipmentType)) {
+            soql += ' and Equipment_Type__c = \'' + String.escapeSingleQuotes(equipmentType) + '\'';
+        }
+        if (!String.isBlank(loanerPlace)) {
+            soql += ' and loaner_place__c = \'' + String.escapeSingleQuotes(loanerPlace) + '\'';
+        }
+        if (!String.isBlank(status)) {
+            soql += ' and status = \'' + String.escapeSingleQuotes(status) + '\'';
+        }
+         if (!String.isBlank(serialNumber)) {
+            soql += ' and SerialNumber like \'%' + String.escapeSingleQuotes(serialNumber.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        /**
+         *2018/10/15
+         *NDT/ANI鍒嗛噹淇敼
+        */
+
+        if(!String.isBlank(rec.Remarks2__c)){
+            soql +=  ' and Remarks2__c like \'%' + String.escapeSingleQuotes(rec.Remarks2__c.trim().replaceAll('%','\\%')) + '%\'';
+        }
+        if (!String.isBlank(internal_Asset_No)) {
+            soql += ' and Internal_Asset_number__c like \'%' + String.escapeSingleQuotes(internal_Asset_No.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (exId.size() > 0) {
+            soql += ' and Id not in ' + sqlTail;
+        }
+        system.debug(soql);
+        return soql;
+    }
+
+    // 鏄剧ず鏁版嵁鏉℃暟淇℃伅
+    private void makeMessage() {
+        if (Over_Limit) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '鏁版嵁瓒呰繃' + Select_Limit + '浠讹紝鍙樉绀哄墠' + Select_Limit + '浠�'));
+            Over_Limit = false;
+        }
+    }
+
+    // 杩斿洖鎸夐挳
+    public PageReference cancel() {
+        PageReference ref =  new Pagereference('/');
+        //if (String.isNotBlank(loanerApplyId)) {
+            // 杩斿洖鏍锋満鍊熷嚭鐢宠
+        ref = new Pagereference('/' + loanerApplyId);
+        //}
+        //ref.setRedirect(true);
+        return ref;
+    }
+    //data bean
+    class EquipmentSetInfo implements Comparable {
+     	public Boolean check { get; set; }
+        public Boolean oldcheck { get; set; }
+        public loaner_application_detail__c lad { get; set; }
+        public Asset aset { get; set; }
+        public Loaner_Set__c lSet { get; set; }
+        public Date Rental_Start_Date { get; set; }
+        public Date Rental_End_Date { get; set; }
+        //鏈�鏃╁彲鍊熷嚭鏃堕棿
+        public Date earliest_Lend_Date { get; set; }
+        public Integer SEdayCount { get; set; }
+        public Integer deatilNo { get; set; }
+        public Boolean canInput { get; set; }
+        public Boolean showNo { get; set; }
+        public String remark { get; set; }
+        //public Date endDate {get; set; }
+        //杞�熷厓鐢宠鏄庣粏鏍囪
+        public Boolean firstDet { get; set; }
+
+        // 宸插瓨浜у搧鏄庣粏
+        public EquipmentSetInfo(loaner_application_detail__c e) {
+            check = true;
+            oldcheck= true;
+            lad = e;
+            aset = e.LOANER__r;
+            //endDate = aset.Rental_End_Date__c;
+            if(String.isNotBlank(lad.Remark__c)){
+                remark = lad.Remark__c;
+            }else{
+                remark = aset.Remarks2__c;
+            }
+            deatilNo = 1;
+            canInput = false;
+            firstDet = false;
+            if(String.valueOf(aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
+                showNo = true;
+            }else{
+                showNo = false;
+            }
+        }
+        public EquipmentSetInfo(Integer in_line, Loaner_Set__c e) {
+            deatilNo = in_line;
+            lSet = e;
+
+        }
+
+        public EquipmentSetInfo(Asset e) {
+            system.debug(e);
+            check = false;
+            oldcheck = false;
+            lad = new loaner_application_detail__c();
+            aset = e;
+            remark = aset.Remarks2__c;
+            firstDet = false;
+            if(String.valueOf(aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
+                canInput = true;
+                showNo = true;
+            }else{
+                //lad.loaner_ApplyNo__c = 1;
+                deatilNo = 1;
+                canInput = false;
+                showNo = false;
+            }
+        }
+        // 鎺掑簭
+        public Integer compareTo(Object compareTo) {
+            return null;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/EquipmentLoanerApplyController.cls-meta.xml b/scr/classes/EquipmentLoanerApplyController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/EquipmentLoanerApplyController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/EquipmentLoanerApplyControllerTest.cls b/scr/classes/EquipmentLoanerApplyControllerTest.cls
new file mode 100644
index 0000000..1cd0dad
--- /dev/null
+++ b/scr/classes/EquipmentLoanerApplyControllerTest.cls
@@ -0,0 +1,578 @@
+@isTest
+private class EquipmentLoanerApplyControllerTest
+{
+    static Product2 prd1;
+    static Product2 prd2;
+    static Account acc;
+    static Account dealer;
+    static Contact core;
+    static User testUser;
+    static loaner_Set__c loanerSet;
+
+    //杞�熷厓浠g悊鍟�
+    static Account leaddealer;
+    static void setupTestData01() {
+        OlympusCalendar__c oc0 = new OlympusCalendar__c(Date__c = Date.today(), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc0,oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+    }
+	static void setupTestData() {
+        setupTestData01();
+		List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'IE';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'IE';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        loanerSet = new loaner_Set__c();
+        loanerSet.Equipment_Type__c = 'IE';
+        loanerSet.Set_No__c = 'IETEST0001';
+        loanerSet.Name = 'IETEST0001';
+
+        insert loanerSet;
+
+		// 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'IE';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'IE';
+        assetC1.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        insert new Asset[] {asset,assetC1};
+
+        Loaner_Set_Detail__c lSD1 = new Loaner_Set_Detail__c();
+        lSD1.Loaner_Set__c = loanerSet.Id;
+        lSD1.Asset__c = asset.Id;
+        Loaner_Set_Detail__c lSD2 = new Loaner_Set_Detail__c();
+        lSD2.Loaner_Set__c = loanerSet.Id;
+        lSD2.Asset__c = assetC1.Id;
+        insert new Loaner_Set_Detail__c[] {lSD1,lSD2};
+
+
+        //杞�熶唬鐞嗗晢淇℃伅
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        leaddealer = new Account();
+        leaddealer.Name = 'lead dealer';
+        leaddealer.RecordTypeId = rectDealer[0].Id;
+        leaddealer.ProductSegment__c = 'IE';
+        leaddealer.PostCode__c='000000';
+        insert leaddealer;
+        Contact leadcore = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=leaddealer.id);
+        insert leadcore;
+        User leadUser = New User(ContactId = leadcore.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser02@prectech.com');
+        insert leadUser;
+
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0002';
+        loanerApp.Approval_Step__c = 2;
+        loanerApp.Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = leadUser.Id;
+        insert loanerApp;
+
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0002-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = asset.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+	}
+
+    //IE 鏍锋満鍒嗛厤
+    static testMethod void leadWithIE(){
+        setupTestData();
+
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = testUser.Id;
+       loanerApp.pickup_time__c = Date.today();
+        insert loanerApp;
+
+        List<loaner_application__c> loanerAppList = [select Id from loaner_application__c where Id = :loanerApp.Id];
+        System.assertEquals(1, loanerAppList.size());
+        PageReference page = new PageReference('/apex/EquipmentLoanerApply?loid=' + loanerApp.Id);
+        page.setRedirect(true);
+        System.Test.setCurrentPage(page);
+        EquipmentLoanerApplyController loanerApplyCon = new EquipmentLoanerApplyController();
+        loanerApplyCon.init();
+        loanerApplyCon.rec.Equipment_Type__c = 'IE';
+        loanerApplyCon.rec.Status = '鍦ㄥ簱';
+        loanerApplyCon.rec.SerialNumber = 'asset';
+        loanerApplyCon.rec.Name = 'asset';
+        loanerApplyCon.searchLoanerApp();
+        System.assertEquals(2, loanerApplyCon.equipmentSetRecords.size());
+        System.assertEquals('asset', loanerApplyCon.equipmentSetRecords[0].aset.Name);
+        loanerApplyCon.equipmentSetRecords[0].check = true;
+        loanerApplyCon.equipmentSetRecords[0].deatilNo = 2;
+        loanerApplyCon.equipmentSetRecords[1].check = true;
+        //loanerApplyCon.equipmentSetRecords[1].deatilNo = 2;
+        loanerApplyCon.save();
+
+        List<loaner_application_detail__c> loanerAppDetList = [select Id from loaner_application_detail__c
+                            where loaner_application__c = :loanerApp.Id];
+        System.assertEquals(3, loanerAppDetList.size());
+        loanerApplyCon.sortTable();
+
+
+
+
+        // When
+
+
+        // Then
+
+    }
+
+    //IE 鏍锋満鍒嗛厤
+    static testMethod void IEdeatilNoTest (){
+        setupTestData();
+
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = testUser.Id;
+        loanerApp.pickup_time__c = Date.today();
+        insert loanerApp;
+
+        List<loaner_application__c> loanerAppList = [select Id from loaner_application__c where Id = :loanerApp.Id];
+        System.assertEquals(1, loanerAppList.size());
+        PageReference page = new PageReference('/apex/EquipmentLoanerApply?loid=' + loanerApp.Id);
+        page.setRedirect(true);
+        System.Test.setCurrentPage(page);
+        EquipmentLoanerApplyController loanerApplyCon = new EquipmentLoanerApplyController();
+        loanerApplyCon.init();
+        loanerApplyCon.rec.Equipment_Type__c = 'IE';
+        loanerApplyCon.rec.Status = '鍦ㄥ簱';
+        loanerApplyCon.rec.SerialNumber = 'asset';
+        loanerApplyCon.rec.Name = 'asset';
+        loanerApplyCon.searchLoanerApp();
+        System.assertEquals(2, loanerApplyCon.equipmentSetRecords.size());
+        System.assertEquals('asset', loanerApplyCon.equipmentSetRecords[0].aset.Name);
+        loanerApplyCon.equipmentSetRecords[0].check = true;
+        loanerApplyCon.equipmentSetRecords[1].check = true;
+        loanerApplyCon.save();
+
+        List<loaner_application_detail__c> loanerAppDetList = [select Id from loaner_application_detail__c
+                            where loaner_application__c = :loanerApp.Id];
+        System.assertEquals(2, loanerAppDetList.size());
+        loanerApplyCon.sortTable();
+        loanerApplyCon.sortTable();
+
+    }
+    //IE 鏍锋満濂楄
+    static testMethod void loanerSetTest(){
+        setupTestData();
+
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = testUser.Id;
+        loanerApp.pickup_time__c = Date.today();
+        insert loanerApp;
+
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '宸插垎閰�';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+        List<loaner_application__c> loanerAppList = [select Id from loaner_application__c where Id = :loanerApp.Id];
+        System.assertEquals(1, loanerAppList.size());
+        PageReference page = new PageReference('/apex/EquipmentLoanerApply?loid=' + loanerApp.Id);
+        page.setRedirect(true);
+        System.Test.setCurrentPage(page);
+        EquipmentLoanerApplyController loanerApplyCon = new EquipmentLoanerApplyController();
+        loanerApplyCon.init();
+        loanerApplyCon.rec.Equipment_Type__c = 'IE';
+        loanerApplyCon.rec.Status = '鍦ㄥ簱';
+        loanerApplyCon.rec.SerialNumber = 'asset';
+        loanerApplyCon.rec.Name = 'asset';
+        loanerApplyCon.searchLoanerApp();
+        System.assertEquals(3, loanerApplyCon.equipmentSetRecords.size());
+
+        loanerApplyCon.setId = loanerSet.Id;
+        loanerApplyCon.getLoanerSetdet();
+        System.assertEquals(3, loanerApplyCon.equipmentSetRecords.size());
+        loanerApplyCon.sortTable();
+        loanerApplyCon.getcanSave();
+        loanerApplyCon.getcanSearch();
+        loanerApplyCon.cancel();
+
+        loanerApplyCon.rec.Equipment_Type__c = 'IE';
+        loanerApplyCon.rec.Status = '鍦ㄥ簱';
+        loanerApplyCon.rec.SerialNumber = 'asset';
+        loanerApplyCon.rec.Name = 'asset';
+        loanerApplyCon.assECcode = 'test';
+        loanerApplyCon.rec.loaner_place__c = 'test';
+        loanerApplyCon.assName = 'test';
+        loanerApplyCon.searchLoanerApp();
+    }
+
+    //IE 杞�熺敵璇�
+    static testMethod void leadOrderTest(){
+        setupTestData();
+
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = testUser.Id;
+        loanerApp.Loaner_LendOrder__c = true;
+        loanerApp.Dealer_From_txt__c = 'test';
+        loanerApp.DealerOrder_From__c = leaddealer.Id;
+        loanerApp.ProductNameNum1__c = prd2.Id;
+        loanerApp.pickup_time__c = Date.today();
+        insert loanerApp;
+        List<loaner_application__c> loanerAppList = [select Id from loaner_application__c where Id = :loanerApp.Id];
+        System.assertEquals(1, loanerAppList.size());
+        PageReference page = new PageReference('/apex/EquipmentLoanerApply?loid=' + loanerApp.Id);
+        page.setRedirect(true);
+        System.Test.setCurrentPage(page);
+        EquipmentLoanerApplyController loanerApplyCon = new EquipmentLoanerApplyController();
+        loanerApplyCon.init();
+        System.assertEquals(1, loanerApplyCon.equipmentSetRecords.size());
+        loanerApplyCon.equipmentSetRecords[0].check = true;
+        loanerApplyCon.save();
+    }
+
+    //IE 杞�熺敵璇�
+    static testMethod void bSOrderTest(){
+        setupTestData01();
+        List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'BS'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER BS(only loanerEmail)'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'BS';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        loanerSet = new loaner_Set__c();
+        loanerSet.Equipment_Type__c = 'BS';
+        loanerSet.Set_No__c = 'IETEST0001';
+        loanerSet.Name = 'IETEST0001';
+
+        insert loanerSet;
+
+        // 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'BS';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'BS';
+        assetC1.loaner_place__c = '骞垮窞鍔�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_number[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd2.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'BS';
+        assetC2.loaner_place__c = '骞垮窞鍔�';
+        assetC2.total_number__c = 20;
+        assetC2.Remarks2__c = 'asset';
+        insert new Asset[] {asset,assetC1,assetC2};
+
+        Loaner_Set_Detail__c lSD1 = new Loaner_Set_Detail__c();
+        lSD1.Loaner_Set__c = loanerSet.Id;
+        lSD1.Asset__c = asset.Id;
+        Loaner_Set_Detail__c lSD2 = new Loaner_Set_Detail__c();
+        lSD2.Loaner_Set__c = loanerSet.Id;
+        lSD2.Asset__c = assetC1.Id;
+        insert new Loaner_Set_Detail__c[] {lSD1,lSD2};
+
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'BS';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '鍏ㄥ浗鎬у睍浼�';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = testUser.Id;
+        loanerApp.ProductNameNum1__c = prd2.Id;
+       loanerApp.pickup_time__c = Date.today();
+        insert loanerApp;
+        List<loaner_application__c> loanerAppList = [select Id from loaner_application__c where Id = :loanerApp.Id];
+        System.assertEquals(1, loanerAppList.size());
+        system.runAs(testUser){
+            PageReference page = new PageReference('/apex/EquipmentLoanerApply?loid=' + loanerApp.Id);
+            page.setRedirect(true);
+            System.Test.setCurrentPage(page);
+            EquipmentLoanerApplyController loanerApplyCon = new EquipmentLoanerApplyController();
+            loanerApplyCon.init();
+            System.assertEquals(false, loanerApplyCon.isManager);
+            loanerApplyCon.rec.Equipment_Type__c = 'BS';
+            loanerApplyCon.rec.Status = '鍦ㄥ簱';
+            loanerApplyCon.searchLoanerApp();
+            System.assertEquals(3, loanerApplyCon.equipmentSetRecords.size());
+            loanerApplyCon.equipmentSetRecords[0].check = true;
+            if(loanerApplyCon.equipmentSetRecords[0].aset.RecordTypeId == System.label.Asset_Record_Type1)loanerApplyCon.equipmentSetRecords[0].deatilNo = 2;
+            loanerApplyCon.equipmentSetRecords[1].check = true;
+            if(loanerApplyCon.equipmentSetRecords[1].aset.RecordTypeId == System.label.Asset_Record_Type1)loanerApplyCon.equipmentSetRecords[0].deatilNo = 2;
+            loanerApplyCon.equipmentSetRecords[2].check = true;
+            loanerApplyCon.save();
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/EquipmentLoanerApplyControllerTest.cls-meta.xml b/scr/classes/EquipmentLoanerApplyControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/EquipmentLoanerApplyControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ForgotPasswordController.cls b/scr/classes/ForgotPasswordController.cls
new file mode 100644
index 0000000..480df8b
--- /dev/null
+++ b/scr/classes/ForgotPasswordController.cls
@@ -0,0 +1,19 @@
+/**
+ * An apex page controller that exposes the site forgot password functionality
+ */
+public with sharing class ForgotPasswordController {
+    public String username {get; set;}   
+       
+    public ForgotPasswordController() {}
+	
+  	public PageReference forgotPassword() {
+  		boolean success = Site.forgotPassword(username);
+  		PageReference pr = Page.ForgotPasswordConfirm;
+  		pr.setRedirect(true);
+  		
+  		if (success) {  			
+  			return pr;
+  		}
+  		return null;
+  	}
+}
\ No newline at end of file
diff --git a/scr/classes/ForgotPasswordController.cls-meta.xml b/scr/classes/ForgotPasswordController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/ForgotPasswordController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ForgotPasswordControllerTest.cls b/scr/classes/ForgotPasswordControllerTest.cls
new file mode 100644
index 0000000..1712f2c
--- /dev/null
+++ b/scr/classes/ForgotPasswordControllerTest.cls
@@ -0,0 +1,12 @@
+/**
+ * An apex page controller that exposes the site forgot password functionality
+ */
+@IsTest public with sharing class ForgotPasswordControllerTest {
+  	 @IsTest(SeeAllData=true) public static void testForgotPasswordController() {
+    	// Instantiate a new controller with all parameters in the page
+    	ForgotPasswordController controller = new ForgotPasswordController();
+    	controller.username = 'test@salesforce.com';     	
+    
+    	System.assertEquals(controller.forgotPassword(),null); 
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ForgotPasswordControllerTest.cls-meta.xml b/scr/classes/ForgotPasswordControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/ForgotPasswordControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/IENewOpportunityController.cls b/scr/classes/IENewOpportunityController.cls
new file mode 100644
index 0000000..ae51885
--- /dev/null
+++ b/scr/classes/IENewOpportunityController.cls
@@ -0,0 +1,138 @@
+public with sharing class IENewOpportunityController {
+    public boolean hasError { get; set; }
+    //public boolean isDealerPage { get; set; }
+
+    public Opportunity opp { get; set; }
+
+    public String accId { get; set; }
+    public String conId { get; set; }
+    private Account acc;
+    private Contact con;
+
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    //public String ProductSegment { get; set; }
+
+    //public Boolean isIEDealer{get; set; }
+
+    public IENewOpportunityController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+
+    public PageReference init() {
+        hasError = false;
+
+        accId = System.currentPageReference().getParameters().get('accid');
+        conId = System.currentPageReference().getParameters().get('conId');
+
+        List<Account> accList = [select Id, Name, ProductSegment__c,compo_Acc__c,UserType__c from Account where Id = :accId];
+        if (accList.size() > 0) {
+            acc = accList[0];
+        }
+
+        List<Contact> conList = [select Id, Name from Contact where Id = :conId];
+        if (conList.size() > 0) {
+            con = conList[0];
+        }
+
+        //no.6 gwy 2021-06-03
+        opp = new Opportunity();
+        if(acc.ProductSegment__c == 'IE' && acc.compo_Acc__c == 'COMPO瀹㈡埛'){
+            opp.compo_opp__c = true;
+        }
+        opp.AccountId = acc.Id;
+        opp.Account = acc;
+        opp.ProductSegment__c = acc.ProductSegment__c;
+        opp.Type = 'Not Traget';
+        opp.SalesChannel__c = 'direct';
+        opp.NewInquiryDate__c = Date.today();
+        opp.StageName = 'Prospect Created';
+        opp.CloseDate = Date.valueOf('1900-01-01');
+        
+
+        return null;
+    }
+
+    public PageReference saveBtn() {
+        List<Opportunity> checkList = [select id, Name from Opportunity where AccountId = :opp.AccountId and Name = :opp.Name];
+        if (checkList.size() > 0) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇ュ鎴蜂笅鏈夊悕绉颁竴鏍风殑璇环锛屾槸鍚︾户缁垱寤鸿璇环锛�'));
+            hasError = true;
+        } else {
+             if(opp.Have_Computer__c && opp.Association_Opportunity__c == null){
+               
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇烽�夋嫨鍏宠仈鐨勮浠�'));
+                return null;
+                
+            }else if(opp.Have_Computer__c == false && opp.Association_Opportunity__c != null){
+                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info, '璇峰湪鍖呭惈鐢佃剳鐨勮浠蜂腑閫夋嫨涓绘満璇环銆�'));
+                return null;
+            }else if(opp.Have_Computer__c && opp.Association_Opportunity__c != null){
+                Opportunity opp1 = [select id,Have_Computer__c from Opportunity where id = :opp.Association_Opportunity__c];
+                if(opp1.Have_Computer__c){
+                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info, '閫夋嫨鐨勮浠锋槸鐢佃剳璇环锛岃纭璇环淇℃伅鍚庡啀淇濆瓨銆�'));
+                    return null;
+                }
+            }
+            return saveBtnYes();
+        }
+        return null;
+    }
+
+    public PageReference saveBtnYes() {
+        system.debug('=====saveBtnYes');
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+
+            opp.RecordTypeId = '0120T0000003Ser';
+            opp.SalesChannel__c = 'direct';
+            insert opp;
+            if(opp.Have_Computer__c && opp.Association_Opportunity__c != null){
+
+                StaticParameter.OppChangeopp = true;
+                StaticParameter.OppCanChangeOpp = true;
+                Opportunity newopp = new Opportunity();
+                newopp.Id = opp.Association_Opportunity__c;
+                newopp.Association_Opportunity__c = opp.Id;
+                system.debug(opp.Association_Opportunity__c);
+                update newopp;
+            }
+            OpportunityContactRole ocr = new OpportunityContactRole();
+            ocr.OpportunityId = opp.Id;
+            ocr.ContactId = con.Id;
+            ocr.Role = 'End user';
+            ocr.IsPrimary = true;
+            insert ocr;
+
+            hasError = false;
+
+            String url = baseUrl + '\\' + opp.Id;
+            return new Pagereference(url);
+        } catch (Exception e) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+            hasError = false;
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtnNo() {
+        system.debug('=====saveBtnNo');
+        hasError = false;
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/IENewOpportunityController.cls-meta.xml b/scr/classes/IENewOpportunityController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/IENewOpportunityController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/IENewOpportunityControllerTest.cls b/scr/classes/IENewOpportunityControllerTest.cls
new file mode 100644
index 0000000..c670b3b
--- /dev/null
+++ b/scr/classes/IENewOpportunityControllerTest.cls
@@ -0,0 +1,83 @@
+@isTest
+private class IENewOpportunityControllerTest {
+
+	@isTest static void test_method_one() {
+		List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456',
+            compo_Acc__c = 'COMPO瀹㈡埛'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp1 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp1;
+
+        PageReference page = new PageReference('/apex/NewOpportunity?accid=' + accIE.Id + '&conId=' + con.Id);
+        System.Test.setCurrentPage(page);
+        IENewOpportunityController controller = new IENewOpportunityController();
+
+        controller.init();
+
+        controller.opp.Name = 'test opp 001';
+        controller.opp.TradeType__c = 'Taxation';
+        controller.opp.LeadSource = 'Others';
+        controller.opp.SalesChannel__c = 'direct';
+        controller.opp.Have_Computer__c = true;
+        controller.opp.Association_Opportunity__c = opp1.Id;
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.saveBtnYes();
+
+        controller.saveBtnNo();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/IENewOpportunityControllerTest.cls-meta.xml b/scr/classes/IENewOpportunityControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/IENewOpportunityControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/IdentityContextPlugin.cls b/scr/classes/IdentityContextPlugin.cls
new file mode 100644
index 0000000..bdf0e0a
--- /dev/null
+++ b/scr/classes/IdentityContextPlugin.cls
@@ -0,0 +1,80 @@
+global class IdentityContextPlugin implements Process.Plugin {
+    
+    global Process.PluginDescribeResult describe() {
+        Process.PluginDescribeResult result = new Process.PluginDescribeResult(); 
+           result.Tag = 'Identity';
+           result.Name = 'Identity Context Builder';
+           result.description = 'Establishes Context for the current user to be used in Login Flows';
+           result.inputParameters = new List<Process.PluginDescribeResult.InputParameter> {
+              new Process.PluginDescribeResult.InputParameter('LoginFlow_UserAgent', Process.PluginDescribeResult.ParameterType.STRING, false),
+              new Process.PluginDescribeResult.InputParameter('LoginFlow_LoginIpAddress', Process.PluginDescribeResult.ParameterType.STRING, false)
+           };
+       
+           result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter> {
+               new Process.PluginDescribeResult.OutputParameter('User Id', Process.PluginDescribeResult.ParameterType.String),
+               new Process.PluginDescribeResult.OutputParameter('User Type', Process.PluginDescribeResult.ParameterType.String),
+               new Process.PluginDescribeResult.OutputParameter('AuthSession Id', Process.PluginDescribeResult.ParameterType.String),
+               new Process.PluginDescribeResult.OutputParameter('IP Changed Since Login', Process.PluginDescribeResult.ParameterType.Boolean),
+               new Process.PluginDescribeResult.OutputParameter('Is Trusted IP Address', Process.PluginDescribeResult.ParameterType.Boolean),
+               new Process.PluginDescribeResult.OutputParameter('Has Registered Token', Process.PluginDescribeResult.ParameterType.Boolean),
+               new Process.PluginDescribeResult.OutputParameter('Is iPhone', Process.PluginDescribeResult.ParameterType.Boolean),
+               new Process.PluginDescribeResult.OutputParameter('Is iPad', Process.PluginDescribeResult.ParameterType.Boolean),
+               new Process.PluginDescribeResult.OutputParameter('Is Android', Process.PluginDescribeResult.ParameterType.Boolean)
+           };
+           return result; 
+    }
+    
+    global Process.PluginResult invoke(Process.PluginRequest request) {  
+    
+        
+        Map<String, Object> result = new Map<String, Object>();
+        Map<String,String> sessionAttributes;
+        
+        String userId =  UserInfo.getUserId();
+        result.put('User Id', userId);
+        
+        List<TwoFactorInfo> twoFactors = [SELECT UserId, Type FROM TwoFactorInfo where userID = :userid];
+        result.put('Has Registered Token', !TwoFactors.isEmpty());
+        
+        String userAgent = (String)request.inputParameters.get('LoginFlow_UserAgent');
+        if (userAgent != null) {
+            if (userAgent.contains('iPhone')) {
+                result.put('Is iPhone', true);
+            } else {
+                result.put('Is iPhone', false);
+            }
+            if (userAgent.contains('iPad')) { 
+                result.put('Is iPad', true);
+            } else {
+                result.put('Is iPad', false);
+            }
+            if (userAgent.contains('Android')) { 
+                result.put('Is Android', true);
+            } else {
+                result.put('Is Android', false);
+            }
+        }
+
+        if(!Test.isRunningTest())
+            sessionAttributes = Auth.SessionManagement.getCurrentSession();
+   
+        if(sessionAttributes == null)
+            return new Process.PluginResult(result);
+            
+        result.put('User Type', sessionAttributes.get('UserType'));
+        result.put('AuthSession Id', sessionAttributes.get('SessionId'));
+        String sourceIP = sessionAttributes.get('SourceIP');
+        if(sourceIP != null)
+        {
+            result.put('Is Trusted IP Address', Auth.SessionManagement.inOrgNetworkRange(sourceIP));
+            String loginIpAddress = (String)request.inputParameters.get('LoginFlow_LoginIpAddress');
+            if ((sourceIP != null) && (loginIpAddress != null)) result.put('IP Changed Since Login', (sourceIP == loginIpAddress));
+        }
+       
+        System.debug('Session Attributes: ' + sessionAttributes);
+        System.debug('Context Builder Results: ' + result);
+        
+        return new Process.PluginResult(result);
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/IdentityContextPlugin.cls-meta.xml b/scr/classes/IdentityContextPlugin.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/IdentityContextPlugin.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/IdentityContextPluginTest.cls b/scr/classes/IdentityContextPluginTest.cls
new file mode 100644
index 0000000..52a3a72
--- /dev/null
+++ b/scr/classes/IdentityContextPluginTest.cls
@@ -0,0 +1,29 @@
+@isTest
+private class IdentityContextPluginTest {
+
+    static testMethod void inputTest() {
+
+        IdentityContextPlugin identity = new IdentityContextPlugin();
+        Map<String,Object> inputParams = new Map<String,Object>();
+        Map<String,Object> outputParams = new Map<String,Object>();
+        
+        inputParams.put('LoginFlow_UserAgent', 'iPhone');
+        inputParams.put('LoginFlow_LoginIpAddress', '1.1.1.1');
+        
+        Process.PluginRequest request = new Process.PluginRequest(inputParams);
+        Process.PluginResult result;
+        result = identity.invoke(request);
+            
+        System.AssertEquals(1,1);
+            
+     }
+     
+     static testMethod void describeTest() {
+
+        IdentityContextPlugin identity = new IdentityContextPlugin();
+        Process.PluginDescribeResult result = identity.describe();
+        
+        System.AssertEquals(result.inputParameters.size(), 2);
+        System.AssertEquals(result.OutputParameters.size(), 9);
+     }
+}
\ No newline at end of file
diff --git a/scr/classes/IdentityContextPluginTest.cls-meta.xml b/scr/classes/IdentityContextPluginTest.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/IdentityContextPluginTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LicenseCheckUtil.cls b/scr/classes/LicenseCheckUtil.cls
new file mode 100644
index 0000000..04bc005
--- /dev/null
+++ b/scr/classes/LicenseCheckUtil.cls
@@ -0,0 +1,118 @@
+public without sharing class LicenseCheckUtil {
+    public static String LicenseCheck1(String str){
+        String isOk = '1';
+        List<License_Information__c> liList= [select id,IfQuantityCtrl__c,Is_Active_Formula__c,LicenseAndAccount__r.Name,LicenseType__c from License_Information__c where LicenseAndAccount__c = :str];
+        Integer hasA = -1;
+        if(liList == null){
+            isOk = '缁忛攢鍟嗘棤杈愬皠璇佺収淇℃伅';
+        }else{
+            for (License_Information__c li : liList ) {
+                if(li.LicenseType__c == '杈愬皠瀹夊叏璁稿彲璇�' && li.Is_Active_Formula__c == true){
+                    if(li.IfQuantityCtrl__c){
+                        hasA = 1; 
+                    }else{
+                        hasA = 0;
+                        isOk = '0';
+                    }
+                }
+            }
+        }
+        if(hasA == -1){
+            isOk = '缁忛攢鍟嗚緪灏勮瘉鐓ф棤鏁�';
+        }
+        return isOk;
+    }
+
+
+    public static String LicenseCheckOly(){
+        String isOk = '1';
+        String str = System.label.Olympus_Id;
+        List<License_Information__c> liList= [select id, IfControl__c,Is_Active_Formula__c,LicenseAndAccount__r.Name,LicenseType__c from License_Information__c where LicenseAndAccount__c = :str];
+        System.debug('License_Information__c'+liList);
+        Integer hasA = -1;
+        if(liList == null){
+            isOk = '缁忛攢鍟嗘棤杈愬皠璇佺収淇℃伅';
+        }else{
+            for (License_Information__c li : liList ) {
+                if(li.LicenseType__c == '杈愬皠瀹夊叏璁稿彲璇�' && li.Is_Active_Formula__c == true){
+                    if(li.IfControl__c){
+                        hasA = 1; 
+                    }else{
+                        hasA = 0;
+                        isOk = '0';
+                    }
+                }
+            }
+        }
+        if(hasA == -1){
+            isOk = '缁忛攢鍟嗚緪灏勮瘉鐓ф棤鏁�';
+        }
+        System.debug(isOk);
+        return isOk;
+    }
+
+     public static Boolean AddressCheck(String str,String add){
+        Boolean isOk = false;
+        List<License_Information__c> liList= [select id,Is_Active_Formula__c,LicenseAndAccount__r.Name,LicenseType__c,StorageAddress__c from License_Information__c where LicenseAndAccount__c = :str and LicenseType__c = '绗簩绫诲尰鐤楀櫒姊扮粡钀ュ妗堝嚟璇�' and Is_Active_Formula__c = true];
+        if(liList != null && liList.size() >0 ){
+            License_Information__c li = liList[0];
+            //isOk = add.equals(li.StorageAddress__c);
+            //isOk = li.StorageAddress__c.contains(add);
+            List<String> addressList = new List<String>();
+            addressList = li.StorageAddress__c.split(';');
+            for (String str1 : addressList ) {
+                if(str1.equals(add)){
+                    isOk = true;
+                }
+            }
+        }
+        return isOk;
+    }
+
+    public static String LicenseCheck(String str1){
+        System.debug(str1);
+        String isOk = '1';
+        Boolean hasA = false;
+        Boolean hasB = false;
+        List<License_Information__c> liList= [select id,Is_Active_Formula__c,LicenseAndAccount__r.Name,LicenseType__c from License_Information__c where LicenseAndAccount__c = :str1];
+        System.debug('!@!@!@'+liList);
+        if(liList == null){
+            isOk = '浠g悊鍟嗘病鏈夎瘉鐓т俊鎭�';
+        }else{
+            for(License_Information__c li : liList){
+                if(li.LicenseType__c == '钀ヤ笟鎵х収' && li.Is_Active_Formula__c == true){
+                    hasA = true;
+                }
+                if(li.LicenseType__c == '绗簩绫诲尰鐤楀櫒姊扮粡钀ュ妗堝嚟璇�' && li.Is_Active_Formula__c == true){
+                    hasB = true;
+                }
+            }
+        }
+
+        if(hasA == false && hasB == false){
+            isOk = '浠g悊鍟嗚惀涓氭墽鐓у拰绗簩绫诲尰鐤楀櫒姊扮粡钀ュ妗堝嚟璇侀兘涓烘棤鏁�';
+        }else if(hasA == false && hasB == true){
+            isOk = '浠g悊鍟嗚惀涓氭墽鐓т负鏃犳晥';
+        }else if(hasA == true && hasB == false){
+            isOk = '浠g悊鍟嗙浜岀被鍖荤枟鍣ㄦ缁忚惀澶囨鍑瘉涓烘棤鏁�';
+        }
+
+        return isOk;
+    }
+
+    //鑱旂郴浜烘槸鍚︽槸濉啓鐨勫鎴蜂笅鐨勶紵
+    /*public static Boolean CustomerContactCheck(){
+        Boolean disPersed = false;
+        List<Order> ordList = new List<Order>();
+        ordList = [select id,name,SpecialDeliveryAccount__c,SpecialDeliveryContact2__c,SpecialDeliveryAccount_D__c,SpecialDeliveryContact2_D__c from Order];
+        for (Order ord : ordList) {
+            if(ord.SpecialDeliveryAccount__c != null && ord.SpecialDeliveryContact2__c != null && ord.SpecialDeliveryAccount__c != ord.SpecialDeliveryContact2__r.Name){
+                disPersed = true;
+            }else if(ord.SpecialDeliveryAccount_D__c != null && ord.SpecialDeliveryContact2_D__c != null && ord.SpecialDeliveryAccount_D__c != ord.SpecialDeliveryContact2_D__r.Name){
+                disPersed = true;
+            }
+        }
+
+        return disPersed;
+    }*/
+}
\ No newline at end of file
diff --git a/scr/classes/LicenseCheckUtil.cls-meta.xml b/scr/classes/LicenseCheckUtil.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/LicenseCheckUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LicenseCheckUtilTest.cls b/scr/classes/LicenseCheckUtilTest.cls
new file mode 100644
index 0000000..5fdf6f4
--- /dev/null
+++ b/scr/classes/LicenseCheckUtilTest.cls
@@ -0,0 +1,97 @@
+@isTest
+private class LicenseCheckUtilTest {
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        insert acc1;
+        License_Information__c li = new License_Information__c(
+        	name = 'test',
+        	LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�',
+        	ValidFrom__c = Date.today().addDays(-5),
+        	LicenseAndAccount__c = acc1.Id,
+        	ValidTo__c = Date.today().addDays(4)
+        );
+        insert li;
+        LicenseCheckUtil.LicenseCheck1(acc1.Id);
+        LicenseCheckUtil.LicenseCheck1('111');
+        li.ValidTo__c = Date.today().addDays(-3);
+        update li;
+        LicenseCheckUtil.LicenseCheck1(acc1.Id);
+
+    }
+
+    static testMethod void testMethod2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        insert acc1;
+        License_Information__c li = new License_Information__c(
+        	name = 'test',
+        	LicenseType__c = '绗簩绫诲尰鐤楀櫒姊扮粡钀ュ妗堝嚟璇�',
+        	ValidFrom__c = Date.today().addDays(-5),
+        	LicenseAndAccount__c = acc1.Id,
+        	StorageAddress__c = '1111',
+        	ValidTo__c = Date.today().addDays(4)
+        );
+        insert li;
+        LicenseCheckUtil.AddressCheck(acc1.Id,'1111');
+        LicenseCheckUtil.AddressCheck(acc1.Id,'111111');
+    }
+
+     static testMethod void testMethod3() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        insert acc1;
+        License_Information__c li = new License_Information__c(
+        	name = 'test',
+        	LicenseType__c = '绗簩绫诲尰鐤楀櫒姊扮粡钀ュ妗堝嚟璇�',
+        	ValidFrom__c = Date.today().addDays(-5),
+        	LicenseAndAccount__c = acc1.Id,
+        	StorageAddress__c = '1111',
+        	ValidTo__c = Date.today().addDays(4)
+        );
+        insert li;
+
+        License_Information__c li1 = new License_Information__c(
+        	name = 'test',
+        	LicenseType__c = '钀ヤ笟鎵х収',
+        	ValidFrom__c = Date.today().addDays(-5),
+        	LicenseAndAccount__c = acc1.Id,
+        	StorageAddress__c = '1111',
+        	ValidTo__c = Date.today().addDays(4)
+        );
+        insert li1;
+
+        LicenseCheckUtil.LicenseCheck(acc1.Id);
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LicenseCheckUtilTest.cls-meta.xml b/scr/classes/LicenseCheckUtilTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/LicenseCheckUtilTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerAppDetailTriggerHandler.cls b/scr/classes/LoanerAppDetailTriggerHandler.cls
new file mode 100644
index 0000000..a06dc1b
--- /dev/null
+++ b/scr/classes/LoanerAppDetailTriggerHandler.cls
@@ -0,0 +1,271 @@
+public without sharing class LoanerAppDetailTriggerHandler {
+	public static Boolean runTrigger = true;
+	//搴熷純
+	public static string upsertDiscarded(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		List<String> assetIdList = new List<String>();
+		List<string> ladcIdList = new List<string>();
+		loaner_application_detail__c old = null;
+		for(loaner_application_detail__c ladc : newList){
+			old = oldMap.get(ladc.Id);
+			if(old.RAESD_Status__c != ladc.RAESD_Status__c && ladc.RAESD_Status__c == '搴熷純'){
+				assetIdList.add(ladc.LOANER__c);
+				ladcIdList.add(ladc.id);			
+			}
+		}
+
+		if(ladcIdList.size() == 0){
+			return '';
+		}
+
+		List<loaner_application_detail__c> ladcList = [select id,Abandoned_Date__c from loaner_application_detail__c where id=:ladcIdList];
+		List<Asset> assetList = [select id,RecordType.Id from Asset where id=:assetIdList];
+
+		for(Asset asset : assetList){
+			if(asset.RecordType.Id == System.label.Asset_Record_Type1){
+            	asset.Status = '搴熷純';
+            	asset.Abandoned_date__c = Date.today();
+            }
+		}
+
+		for(loaner_application_detail__c la : ladcList){
+			la.Abandoned_Date__c = Date.today();
+		}
+		update(ladcList); 
+		update(assetList);
+		return '';
+	}
+	//娆犲搧纭
+	public static string upsertCheckLost(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		
+		List<Asset> assetList = new List<Asset>();
+		List<String> assetIdList = new List<string>();
+		List<string> ladcIdList = new List<string>();
+		Set<string> lacIdSet = new Set<string>();
+		loaner_application_detail__c old = null;
+		//鑾峰彇鏄庣粏鐘舵�佺敱'娆犲搧涓�'淇敼涓烘柊鐘舵�佺殑鏄庣粏id
+		for(loaner_application_detail__c ladc : newList){
+			old = oldMap.get(ladc.Id);
+			if(old.RAESD_Status__c != ladc.RAESD_Status__c && old.RAESD_Status__c == '娆犲搧涓�'){
+				ladcIdList.add(ladc.id);
+			}
+		}
+		//濡傛灉娌℃湁绗﹀悎鏉′欢鐨勬槑缁�,璺冲嚭
+		if(ladcIdList.size() == 0){
+			return '';
+		}
+
+		List<loaner_application_detail__c> ladcList = [select id,LOANER__c,RAESD_Status__c,loaner_application__c from loaner_application_detail__c where id=:ladcIdList];
+		
+
+		for(loaner_application_detail__c la : ladcList){
+			if(la.RAESD_Status__c == '涓㈠け'){
+				la.Lost_Date__c = Date.today();
+				la.inTime__c = Datetime.now();
+				assetIdList.add(la.LOANER__c);
+
+			}else if(la.RAESD_Status__c == '宸插洖鏀�'){
+				la.Received_loaner_Date__c = Date.today();
+				la.inTime__c = Datetime.now();
+				la.Check_lost_Item__c = 'ok';
+			}
+			la.Lost_item_check_Date__c = Date.today();
+			lacIdSet.add(la.loaner_application__c);
+		}
+
+		List<Asset> allAssetList = [select id,RecordType.Id from Asset where id=:assetIdList];
+		for(Asset asset : allAssetList){
+			if(asset.RecordType.Id == System.label.Asset_Record_Type1){
+				asset.Status = '涓㈠け';
+				asset.Lost_date__c = Date.today();
+				assetList.add(asset);
+			}
+		}
+
+		List<loaner_application__c> lacList = [select Id,Status__c,Equipment_Type__c from loaner_application__c where Id = :lacIdSet];
+		for(loaner_application__c lac: lacList){
+			if(lac.Status__c != '瀹屾瘯'){
+				lac.Status__c =  LoanerOrderState.getOrderStater(lac.Id);
+				if(lac.Status__c =='鍏ㄩ儴鍥炴敹'){
+                   lac.LoanerClosedDateAll__c =Date.today();
+                   if(lac.Equipment_Type__c == 'NDT' || lac.Equipment_Type__c == 'ANI'){
+                    	PrototypeToThaw.UserUnfreeze(lac.Id);
+                   }
+                }
+			}
+		}
+		update(assetList);
+		update(ladcList);
+		update(lacList);
+		return '';
+	}
+
+	//鍒犻櫎鍚庣姸鎬佹洿鏂�
+	public static void delStatusUp(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		Set<String> loanerAppSet = new Set<String>();
+		Set<String> loanerSet = new Set<String>();
+		for (loaner_application_detail__c local : oldList) {
+            loanerSet.add(local.LOANER__c);
+            loanerAppSet.add(local.loaner_application__c);
+        }
+        Map<String,Integer> resultsMap = new Map<String,Integer>();
+        //鐜嬮箯浼� 鏂板姞where鏉′欢  AND RAESD_Status_F__c != '鍙栨秷'
+        AggregateResult[] results = [select LOANER__c,Count(Id) LOANERNo
+                                 from  loaner_application_detail__c
+                                 where loaner_application__c not in :loanerAppSet
+                                 and LOANER__c in :loanerSet
+                                and (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null AND RAESD_Status_F__c != '鍙栨秷')
+                                AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
+                                 GROUP by LOANER__c];
+                                 System.debug('results +++++' + results);
+        for(AggregateResult ar: results){
+            resultsMap.put(String.valueOf(ar.get('LOANER__c')), Integer.valueOf(ar.get('LOANERNo')));
+        }
+        List<Asset> pss = [select Id,Status from Asset where RecordTypeId = :System.label.Asset_Record_Type1
+                                  AND Id in : loanerSet];
+        List<Asset> pssexit = new List<Asset>();
+        for(Asset lId : pss){
+        	if(!resultsMap.containsKey(lId.Id)){
+        		Asset p2s = new Asset();
+                p2s.Id =  lId.Id;
+                p2s.Status = '鍦ㄥ簱';
+                pssexit.add(p2s);
+        	}
+        }
+        System.debug('pss +++++' + pss);
+        if(pssexit.size() > 0){
+        	upsert pssexit;
+        }
+	}
+
+	//鎻掑叆鍚庣姸鎬佹洿鏂�
+	public static void insStatusUp(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		Set<String> loanerSet = new Set<String>();
+		for (loaner_application_detail__c local : newList) {
+            if(local.RAESD_Status__c == '宸插嚭搴撴寚绀�' || local.RAESD_Status__c == '宸叉壒鍑�' || local.RAESD_Status__c == '鐢宠涓�'){
+                loanerSet.add(local.LOANER__c);
+            }
+        }
+        List<Asset> tmpList = new List<Asset>();
+        for(Asset ass : [select Id,Status from Asset where Id in : loanerSet AND Status = '鍦ㄥ簱' AND RecordTypeId  = :System.label.Asset_Record_Type1]){
+            ass.Status = '鍐荤粨';
+            tmpList.add(ass);
+        }
+        List<loaner_application__c> laList = [select id,Status__c,Loaner_LendOrder__c from loaner_application__c where id = :loanerSet];
+        List<loaner_application_detail__c> ladList = new List<loaner_application_detail__c>();
+        for(loaner_application_detail__c local : newList){
+        	for(loaner_application__c temp : laList){
+        		if(temp.id == local.LOANER__c){
+        			if(temp.Status__c != '鑽夋涓�' && temp.Status__c != '宸叉彁浜�' && temp.Status__c != '鐢宠涓�' && temp.Loaner_LendOrder__c == true){
+        				loaner_application_detail__c lad = new loaner_application_detail__c();
+        				lad.RAESD_Status__c = '宸叉壒鍑�';
+        				ladList.add(lad);
+        			}
+        		}
+     		}
+        }
+        if(ladList.size() > 0) update ladList;
+        if(tmpList.size() > 0) update tmpList;
+	}
+
+	public static void setUser(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		List<String> ladIdList = new List<String>();
+		for(loaner_application_detail__c lad : newList){
+			if(lad.loaner_Manager__c == null){
+				ladIdList.add(lad.Id);
+			}
+		}
+
+		if(ladIdList.size()>0){
+			List<loaner_application_detail__c> ladList = [select id,loaner_application__r.loaner_Manager__c from loaner_application_detail__c where Id= : ladIdList];
+			List<loaner_application_detail__c> updateList = new List<loaner_application_detail__c>();
+			for(loaner_application_detail__c lad : ladList){
+				lad.loaner_Manager__c = lad.loaner_application__r.loaner_Manager__c;
+				updateList.add(lad);
+			}
+
+			update updateList;
+		} 
+	}
+
+	public static void notReceivingNum(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		Map<String,Integer> leIdMap = new Map<String,Integer>();
+		for(loaner_application_detail__c lad : newList){
+			loaner_application_detail__c old = oldMap.get(lad.id);
+			if(lad.RAESD_Status__c != old.RAESD_Status__c && lad.RAESD_Status__c == '鐢宠鑰呭凡鏀惰揣' && lad.Loaner_Express__c != null){
+				if(leIdMap.containsKey(lad.Loaner_Express__c)){
+					leIdMap.put(lad.Loaner_Express__c, (leIdMap.get(lad.Loaner_Express__c)+1));
+				}else{
+					leIdMap.put(lad.Loaner_Express__c,1);
+				}
+			}
+			if(lad.RAESD_Status__c != old.RAESD_Status__c && lad.RAESD_Status__c == '宸插洖鏀�' && lad.Return_Express__c != null){
+				if(leIdMap.containsKey(lad.Return_Express__c)){
+					leIdMap.put(lad.Return_Express__c, (leIdMap.get(lad.Return_Express__c)+1));
+				}else{
+					leIdMap.put(lad.Return_Express__c,1);
+				}
+			}
+		}
+		System.debug(leIdMap);
+		if(leIdMap.size() == 0){
+			return;
+		}
+		List<Loaner_Express__c> updateList = new List<Loaner_Express__c>();
+		List<Loaner_Express__c> leList = [select id,NotReceivingNum__c from Loaner_Express__c where id= :leIdMap.keySet()];
+		for(Loaner_Express__c le : leList){
+			if(le.NotReceivingNum__c != null){
+				le.NotReceivingNum__c = le.NotReceivingNum__c - leIdMap.get(le.id);
+			}
+			System.debug(le.NotReceivingNum__c);
+			updateList.add(le);
+		}
+
+		update updateList;
+	}
+
+	//鏄庣粏涓绠楄嚜鍔ㄦ敹璐ф棩鏈熷拰鏀惰揣鎻愰啋鏃ユ湡
+	public static void emailDate(List<loaner_application_detail__c> newList, Map<Id, loaner_application_detail__c> newMap, List<loaner_application_detail__c> oldList, Map<Id, loaner_application_detail__c> oldMap){
+		List<String> autoId = new List<String>();
+		List<String> remindId = new List<String>();
+
+		for(loaner_application_detail__c lad : newList){
+			loaner_application_detail__c old = oldMap.get(lad.id);
+			if(lad.Automatic_Received_Date__c == null && lad.Shipment_Request_Date__c != null){
+				autoId.add(lad.id);
+			}
+			if(lad.Automatic_Received_Date__c != old.Automatic_Received_Date__c){
+				remindId.add(lad.id);
+			}
+		}
+		Map<String,OlympusCalendar__c> oCalendar = calendarUtil.getCalendarMap(Date.today().addDays(-30),Date.today().addDays(240));
+		System.debug(oCalendar);
+		if(oCalendar == null){
+			return;
+		}
+		List<loaner_application_detail__c> autoList = new List<loaner_application_detail__c>();
+		
+		List<loaner_application_detail__c> remindList = new List<loaner_application_detail__c>();
+		
+		if(autoId.size()>0){
+			autoList = [select id,Shipment_Request_Date__c,Equipment_Type__c from loaner_application_detail__c where id= :autoId];
+			for(loaner_application_detail__c auto : autoList){
+				if(auto.Equipment_Type__c == 'NDT' || auto.Equipment_Type__c == 'ANI'){
+					auto.Automatic_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Shipment_Request_Date__c,3);
+					auto.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Automatic_Received_Date__c,-2);
+				}else{
+					auto.Automatic_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Shipment_Request_Date__c,5);
+					auto.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Automatic_Received_Date__c,-3);
+				}
+			}
+		}
+		if(remindId.size()>0){
+			remindList = [select id,Automatic_Received_Date__c from loaner_application_detail__c where id= :remindId];
+			for(loaner_application_detail__c remind : remindList){
+				remind.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Automatic_Received_Date__c,-3);
+			}
+		}
+		if(autoList.size()>0) update autoList;
+		if(remindList.size()>0) update remindList;
+
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerAppDetailTriggerHandler.cls-meta.xml b/scr/classes/LoanerAppDetailTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerAppDetailTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerAppDetailTriggerHandlerTest.cls b/scr/classes/LoanerAppDetailTriggerHandlerTest.cls
new file mode 100644
index 0000000..91a4490
--- /dev/null
+++ b/scr/classes/LoanerAppDetailTriggerHandlerTest.cls
@@ -0,0 +1,124 @@
+@isTest
+private class LoanerAppDetailTriggerHandlerTest {
+	
+	@isTest static void test_method_one() {
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+       	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner.Request_return_Date__c = Date.today().addDays(10);
+        loaner.Status__c = '閮ㄥ垎鍙戣揣';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        Loaner_Express__c le = new Loaner_Express__c(
+    	Name = 'test01',
+    	loaner_application__c = loaner.Id,
+    	NotReceivingNum__c = 3
+    	);
+
+        insert le;
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        detail.Loaner_Express__c = le.id;
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        detail.Loaner_Express__c = le.id;
+		//detail.Shipment_Request_Date__c = Date.today();
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '娆犲搧涓�';
+        detail.Loaner_Express__c = le.id;
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        In_detail[0].RAESD_Status__c = '搴熷純';
+
+        update In_detail;
+
+        In_detail[1].RAESD_Status__c = '宸插嚭搴撴寚绀�';
+        update In_detail;
+        System.Test.startTest();
+        In_detail[1].RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        update In_detail;
+        
+        In_detail[2].RAESD_Status__c = '涓㈠け';
+
+
+        In_detail[1].Shipment_Request_Date__c = Date.today().addDays(2);
+        update In_detail;
+        delete In_detail;
+        System.Test.stopTest();
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerAppDetailTriggerHandlerTest.cls-meta.xml b/scr/classes/LoanerAppDetailTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerAppDetailTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerApplicationFlowController.cls b/scr/classes/LoanerApplicationFlowController.cls
new file mode 100644
index 0000000..0168f45
--- /dev/null
+++ b/scr/classes/LoanerApplicationFlowController.cls
@@ -0,0 +1,146 @@
+public without sharing class LoanerApplicationFlowController {
+    // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerApplicationFlowController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c ';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'StockDown') {
+            sql_where += ' and RAESD_Status__c = \'宸插嚭搴撴寚绀篭'';
+        } else {
+            return null;
+        }
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtn() {
+        // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        for (DataLineBean dataLine : dataLines) {
+            if (dataLine.checkFlag == true) {
+                loaner_application_detail__c lad = dataLine.lad;
+                if (step == 'StockDown') {
+                    lad.StockDown__c = true;
+                    lad.StockDown_Date__c = Date.today();
+                    lad.RAESD_Status__c = '宸蹭笅鏋�';
+                }
+                updList.add(lad);
+            }
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            if (updList.size() > 0) update updList;
+
+            /*List<loaner_application_detail__c> checkList = [select id,
+                                                                   loaner_application__c,
+                                                                   loaner_application__r.Detail_count__c,
+                                                                   loaner_application__r.Status__c
+                                                              from loaner_application_detail__c
+                                                             where loaner_application__c = :laId
+                                                               and StockDown__c = true];
+            if (checkList.size() > 0) {
+                loaner_application_detail__c check = checkList[0];
+                if (check.loaner_application__r.Detail_count__c == checkList.size() &&
+                    check.loaner_application__r.Status__c == '宸插嚭搴撴寚绀�') {
+                    loaner_application__c upd = new loaner_application__c();
+                    upd.id = check.loaner_application__c;
+                    upd.Status__c = '宸蹭笅鏋�';
+                    update upd;
+                }
+            }*/
+            if(la.Status__c != '瀹屾瘯'){
+                la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                update la;
+            }
+            // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+            String url = baseUrl;
+            url += '\\' + laId;
+            return new Pagereference(url);
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+        }
+
+        return null;
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerApplicationFlowController.cls-meta.xml b/scr/classes/LoanerApplicationFlowController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LoanerApplicationFlowController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerApplicationStockUpCheckController.cls b/scr/classes/LoanerApplicationStockUpCheckController.cls
new file mode 100644
index 0000000..fdfef0d
--- /dev/null
+++ b/scr/classes/LoanerApplicationStockUpCheckController.cls
@@ -0,0 +1,210 @@
+public without sharing class LoanerApplicationStockUpCheckController {
+ // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerApplicationStockUpCheckController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,Status__c,Equipment_Type__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id,loaner_manage_place__c,StockUpRemark__c, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c , Inspection_result_after__c,RAESD_Status__c,LOANER__c,LOANER__r.RecordType.Id,LOANER__r.Name,LOANER__r.Remarks2__c';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'StockUpCheck') {
+            sql_where += ' and RAESD_Status__c in (\'宸插洖鏀禱',\'淇悊涓璡',\'寰呬笂鏋禱',\'寰呯Щ鑷虫姤搴熷尯\')';
+
+        } else {
+            return null;
+        }
+
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+  		         
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+
+        return null;
+    }
+
+ public PageReference saveBtn() {
+        // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        List<Asset> assList = new List<Asset>();
+        if(dataLines.size()>0){
+            for (DataLineBean dataLine : dataLines) {
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    Asset loa = new Asset(id = lad.LOANER__c);
+                    if (step == 'StockUpCheck') {
+                        lad.Inspection_result_after__c = dataLine.lad.Inspection_result_after__c;
+                        lad.After_Inspection_Date__c = Date.today();
+                        if('NG-淇悊' == dataLine.lad.Inspection_result_after__c){
+                            if(lad.StockUpRemark__c == null || lad.StockUpRemark__c == ''){
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐橬G-淇悊澶囨敞'));
+                                return null;
+                            }
+                        	lad.RAESD_Status__c = '寰呬慨鐞�';
+                            if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                        	   loa.status = '寰呬慨鐞�';
+                               if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'IE' || la.Equipment_Type__c == 'BS'){
+                                    loa.Rental_Customer__c = null;
+                                    loa.Rental_Start_Date__c = null;
+                                    loa.Rental_end_Date__c = null;
+                                    loa.Loaner__c = null;
+                                    if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' ){
+                                        loa.loaner_place__c = lad.loaner_manage_place__c;
+                                    }
+                                }
+                            }
+                        }else if('NG-搴熷純' == dataLine.lad.Inspection_result_after__c){
+                            if(lad.StockUpRemark__c == null || lad.StockUpRemark__c == ''){
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐橬G-搴熷純澶囨敞'));
+                                return null;
+                            }
+                            lad.StockUp__c = true;
+                            lad.Arrival_wh_Date__c = Date.today();
+                        	lad.RAESD_Status__c = '寰呭簾寮�';
+                            if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                        	   loa.status = '寰呭簾寮�';
+                               if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'IE' || la.Equipment_Type__c == 'BS'){
+                                    loa.Rental_Customer__c = null;
+                                    loa.Rental_Start_Date__c = null;
+                                    loa.Rental_end_Date__c = null;
+                                    loa.Loaner__c = null;
+                                    if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' ){
+                                        loa.loaner_place__c = lad.loaner_manage_place__c;
+                                    }
+                                }
+                            }
+                        }else if('Ok' == dataLine.lad.Inspection_result_after__c){
+                            lad.StockUp__c = true;
+                            lad.Arrival_wh_Date__c = Date.today();
+                        	lad.RAESD_Status__c = '宸插洖搴�';
+                            if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                                loa.status = '鍦ㄥ簱';
+                                if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'IE' || la.Equipment_Type__c == 'BS'){
+                                    loa.Rental_Customer__c = null;
+                                    loa.Rental_Start_Date__c = null;
+                                    loa.Rental_end_Date__c = null;
+                                    loa.Loaner__c = null;
+                                    if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' ){
+                                        loa.loaner_place__c = lad.loaner_manage_place__c;
+                                    }
+                                }
+                            }
+                        }else{
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨涓婃灦妫�鏌ョ姸鎬�'));
+                            return null;
+                        }
+                    }
+                    updList.add(lad);
+                    if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                        assList.add(loa);
+                    }
+                }
+
+
+
+            }
+            Savepoint sp = Database.setSavepoint();
+            try {
+               if (updList.size() > 0) {
+                	
+                    if(la.Status__c != '瀹屾瘯'/* && la.Status__c != '鍏ㄩ儴鍥炴敹'*/){
+                        System.debug(la.Status__c);
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        System.debug(la.Status__c);
+                        update la;
+                    }
+
+                    update updList;
+                    update assList;
+                }else{
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨涓婃灦妫�鏌ョ殑鏍锋満'));
+                    return null;
+                }
+
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+		}
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+        return null;
+    }
+
+     public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerApplicationStockUpCheckController.cls-meta.xml b/scr/classes/LoanerApplicationStockUpCheckController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerApplicationStockUpCheckController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls b/scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls
new file mode 100644
index 0000000..8fd295f
--- /dev/null
+++ b/scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls
@@ -0,0 +1,143 @@
+@isTest
+private class LoanerApplicationStockUpCheckCtrlTest {
+	static void setupTestData() {
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+    }
+	@isTest static void test_method_one() {
+                setupTestData();
+				// Implement test code
+				List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        
+                List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+                
+                // 鏂板缓澶囧搧鍊熷嚭鐢宠
+                loaner_application__c loaner = new loaner_application__c();
+                loaner.Name = 'TEST';
+                loaner.RecordTypeId = rectLo[0].id;
+                loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+                loaner.DEMO_PURPOSE__C = '婕旂ず';
+                loaner.Request_shipping_Date__c = Date.today();
+                loaner.Request_return_Date__c = Date.today();
+                loaner.Status__c = '宸插嚭搴撴寚绀�';
+                loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+                //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+                insert loaner;
+
+                // 鏂板缓 瀹㈡埛
+                Account acc = new Account();
+                acc.RecordTypeId = rectCo[0].Id;
+                acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+                acc.DivisionName__c = 'DivisionName__c';
+                acc.FacilityName__c = 'FacilityName__c';
+                acc.PostCode__c='000000';
+                insert acc;
+                 
+                // 鏂板缓 璧勪骇
+                List<Asset> In_asset = new List<Asset>();
+
+                Asset asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�1';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�2';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�3';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                insert In_asset;
+
+                // 鏂板缓 鍊熷嚭鏄庣粏
+                List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+                loaner_application_detail__c detail = new loaner_application_detail__c();
+
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[0].id;
+                detail.name = '000';
+                detail.RAESD_STATUS__C = '宸插洖鏀�';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[1].id;
+                detail.name = '111';
+                detail.RAESD_STATUS__C = '宸插洖鏀�';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[2].id;
+                detail.name = '222';
+                detail.RAESD_STATUS__C = '宸插洖鏀�';
+                detail.Inspection_result_after__c = 'OK';
+                In_detail.add(detail);
+
+                insert In_detail;
+
+                //
+                PageReference page = new PageReference('/apex/LoanerApplicationStockUpCheckController?Id=' + loaner.Id + '&step=StockUpCheck');
+                System.Test.setCurrentPage(page);
+                LoanerApplicationStockUpCheckController  controller = new LoanerApplicationStockUpCheckController();
+
+
+                controller.init();
+                
+                controller.dataLines[0].checkFlag = true;
+                controller.dataLines[0].lad.Inspection_result_after__c = 'NG-淇悊';
+                controller.dataLines[0].lad.StockUpRemark__c = '澶囨敞';
+                
+                controller.dataLines[1].checkFlag = true;
+                controller.dataLines[1].lad.Inspection_result_after__c = 'OK';
+
+                controller.dataLines[2].checkFlag = true;
+                controller.dataLines[2].lad.Inspection_result_after__c = 'NG-搴熷純';
+                controller.dataLines[2].lad.StockUpRemark__c = '澶囨敞';
+
+                controller.saveBtn();
+                //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+                controller.cancelBtn();
+                controller.getDatalineSize();
+
+                //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+                List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+                system.assertEquals('寰呬慨鐞�', updList[0].RAESD_Status__c);
+                system.assertEquals('宸插洖搴�', updList[1].RAESD_Status__c);
+                system.assertEquals('寰呭簾寮�', updList[2].RAESD_Status__c);
+
+
+                List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+                system.assertEquals('鍏ㄩ儴鍥炴敹', laList[0].Status__c);
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls-meta.xml b/scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerApplicationStockUpCheckCtrlTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerApplicationStockUpController.cls b/scr/classes/LoanerApplicationStockUpController.cls
new file mode 100644
index 0000000..2f8975a
--- /dev/null
+++ b/scr/classes/LoanerApplicationStockUpController.cls
@@ -0,0 +1,148 @@
+public without sharing class LoanerApplicationStockUpController {
+    // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerApplicationStockUpController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c ,RAESD_Status__c,LOANER__c,LOANER__r.RecordType.Id';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'StockUp') {
+            sql_where += ' and RAESD_Status__c in  (\'寰呬笂鏋禱',\'寰呯Щ鑷虫姤搴熷尯\')';
+        } else {
+            return null;
+        }
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtn() {
+        // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        List<Asset> assList = new List<Asset>();
+        if(dataLines.size() > 0 ){
+            for (DataLineBean dataLine : dataLines) {
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                   Asset loa = new Asset(id = lad.LOANER__c);
+                    if (step == 'StockUp') {
+                        lad.StockUp__c = true;
+                        lad.Arrival_wh_Date__c = Date.today();
+                       
+                        if(lad.RAESD_Status__c == '寰呬笂鏋�'){
+                            lad.RAESD_Status__c = '宸插洖搴�';
+                            //濡傛灉鏄釜浣撶鐞�,鍒欐敼鍙樻牱鏈虹姸鎬�
+                            if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                                loa.status = '鍦ㄥ簱';
+                            }
+                        }else if(lad.RAESD_Status__c == '寰呯Щ鑷虫姤搴熷尯'){
+                            lad.RAESD_Status__c = '寰呭簾寮�';
+                        } 
+                    }
+                    updList.add(lad);
+                    if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                        assList.add(loa);
+                    }
+                }
+            }
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                	update updList;
+                	update assList;
+                	/*if(){
+                		la.Status__c = '瀹屾瘯';
+                	}
+                	update la;*/
+                }else{ 
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨闇�瑕佷笂鏋剁殑鏍锋満'));
+                    return null;
+                }
+               
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+            }
+        }
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerApplicationStockUpController.cls-meta.xml b/scr/classes/LoanerApplicationStockUpController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerApplicationStockUpController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerApplicationWebService.cls b/scr/classes/LoanerApplicationWebService.cls
new file mode 100644
index 0000000..1e83f11
--- /dev/null
+++ b/scr/classes/LoanerApplicationWebService.cls
@@ -0,0 +1,1056 @@
+global class LoanerApplicationWebService {
+
+	webservice static String loanIndication(String laId){
+        List<loaner_application__c> laList = [select id, Status__c, Detail_count__c from loaner_application__c where id = :laId];
+        if (laList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+        loaner_application__c la = laList[0];
+        if (la.Status__c != '宸叉壒鍑�') {
+            return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛鍑哄簱鎸囩ず銆傜姸鎬侊細' + la.Status__c;
+        }
+        if (la.Detail_count__c == 0) {
+            return '鏍锋満鍊熷嚭鐢宠鏈垎閰嶆牱鏈恒��';
+        }
+
+        la.Status__c = '宸插嚭搴撴寚绀�';
+        la.Bollow_Date__c = Date.today();
+
+        List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '宸叉壒鍑�'];
+        for (loaner_application_detail__c lad : ladList) {
+            lad.RAESD_Status__c = '宸插嚭搴撴寚绀�';
+        }
+
+        try{
+            update ladList;
+            update la;
+        } catch(Exception ex) {
+            return ex.getMessage() + '|Line:' + ex.getLineNumber();
+        }
+		return '1';
+	}
+
+    webservice static String sendOutAll(String laId){
+         List<loaner_application__c> laList = [select id, Status__c, delivery_company__c, Tracking_Number__c, Return_to_wh_staff__c,pickup_time__c,Equipment_Type__c,Agent__c,Rental_Start_Date__c,Rental_end_Date__c,Owner.Name from loaner_application__c where id = :laId];
+        if (laList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+        loaner_application__c la = laList[0];
+        if(la.pickup_time__c != null && la.Status__c == '鍑哄簱鍓嶅凡妫�娴�'){
+            List<loaner_application_detail__c> ladList = [select id,Receipt_Date__c,Receipt_Status__c, LOANER__c, LOANER__r.RecordType.DeveloperName from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�'];
+            la.Status__c = '鐢宠鑰呭凡鏀惰揣';
+            la.Shipping_Finished_Date__c =  Date.today();
+            la.Shipping_Finished_Date_All__c = Date.today();
+
+            for (loaner_application_detail__c lad : ladList) {
+                lad.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                lad.Shipment_Request_Date__c =  Date.today();
+                lad.Receipt_Date__c =  Date.today();
+                lad.outTime__c = Datetime.now();
+                lad.Receipt_Status__c = 'OK';
+            }
+
+            List<Asset> astList = new List<Asset>();
+            for (loaner_application_detail__c lad : ladList) {
+                if (lad.LOANER__r.RecordType.DeveloperName == 'loaner_individual') {
+                    Asset ast = new Asset(Id = lad.LOANER__c);
+                    ast.Status = '鍑哄��';
+                    if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
+                        ast.Loaner__c = la.Owner.Name;
+                        ast.Rental_Customer__c = la.Agent__c;
+                        ast.Rental_Start_Date__c = la.Rental_Start_Date__c;
+                        ast.Rental_end_Date__c = la.Rental_end_Date__c;
+                    }
+                    astList.add(ast);
+                }
+            }
+
+            try{
+                update ladList;
+                update la;
+                update astList;
+            } catch(Exception ex) {
+                return ex.getMessage() + '|Line:' + ex.getLineNumber();
+            }
+
+            return '1';
+        }
+        
+        if (la.Status__c != '鍑哄簱鍓嶅凡妫�娴�' && la.Status__c != '閮ㄥ垎鍙戣揣') {
+            return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛鍏ㄩ儴鍙戣揣銆傜姸鎬侊細' + la.Status__c;
+        }
+        if (la.delivery_company__c == null || la.delivery_company__c == '' ||
+            la.Tracking_Number__c == null || la.Tracking_Number__c == '' ||
+            la.Return_to_wh_staff__c == null) {
+            return '鍙戣揣淇℃伅涓嶅畬鏁达紝璇峰~鍐欏彂璐т俊鎭��';
+        }
+
+        List<loaner_application_detail__c> ladList = [select id, LOANER__c, LOANER__r.RecordType.DeveloperName from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�'];
+        if (ladList.size() == 0) {
+            return '鏍锋満宸茬粡鍏ㄩ儴鍑哄簱銆�';
+        }
+
+        la.Status__c = '鍏ㄩ儴鍙戣揣';
+        la.Shipping_Finished_Date__c = Date.today();
+        la.Shipping_Finished_Date_All__c = Date.today();
+
+        Date temp = Date.today();
+        Loaner_Express__c le = new Loaner_Express__c();
+        le.loaner_application__c = laId;
+        le.Name = temp.day()+ '鏃ュ彂璐х墿娴佸崟';
+        insert le;
+
+        Integer count =0;
+
+        for (loaner_application_detail__c lad : ladList) {
+            lad.RAESD_Status__c = '宸插嚭搴�';
+            lad.Shipment_Request_Date__c = Date.today();
+            lad.delivery_company__c = la.delivery_company__c;
+            lad.Tracking_Number__c = la.Tracking_Number__c;
+            lad.Return_to_wh_staff__c = la.Return_to_wh_staff__c;
+            lad.outTime__c = Datetime.now();
+            count++;
+            lad.Loaner_Express__c = le.id;  
+        }
+
+        le.Consignor_LogisticsNumber__c = la.Tracking_Number__c;
+        le.Consignor_LogisticsCompany__c = la.delivery_company__c;
+        le.consignor__c = la.Return_to_wh_staff__c;
+        le.Shipment_Request_Date__c = Date.today();       
+        le.NotReceivingNum__c = count;
+
+        List<Asset> astList = new List<Asset>();
+        for (loaner_application_detail__c lad : ladList) {
+            if (lad.LOANER__r.RecordType.DeveloperName == 'loaner_individual') {
+                Asset ast = new Asset(Id = lad.LOANER__c);
+                ast.Status = '鍑哄��';
+                if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
+                    ast.Loaner__c = la.Owner.Name;
+                    ast.Rental_Customer__c = la.Agent__c;
+                    ast.Rental_Start_Date__c = la.Rental_Start_Date__c;
+                    ast.Rental_end_Date__c = la.Rental_end_Date__c;
+                }
+                astList.add(ast);
+            }
+        }
+
+        try{
+            update le;
+            update ladList;
+            update la;
+            update astList;
+        } catch(Exception ex) {
+            return ex.getMessage() + '|Line:' + ex.getLineNumber();
+        }
+
+        return '1';
+    }
+
+    webservice static String installConfirm(String laId){
+        List<loaner_application__c> laList = [select id, Status__c from loaner_application__c where id = :laId];
+        if (laList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+        loaner_application__c la = laList[0];
+        if (la.Status__c != '鐢宠鑰呭凡鏀惰揣') {
+            return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛瑁呮満纭銆傜姸鎬侊細' + la.Status__c;
+        }
+
+        List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣'];
+
+        la.Status__c = '鐢宠鑰呭凡瑁呮満纭';
+        la.HP_Received_Sign_Date__c = Date.today();
+
+        for (loaner_application_detail__c lad : ladList) {
+            lad.RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭';
+        }
+
+        try{
+            update ladList;
+            update la;
+        } catch(Exception ex) {
+            return ex.getMessage() + '|Line:' + ex.getLineNumber();
+        }
+
+        return '1';
+    }
+
+    webservice static String sendBackAll(String laId){
+        List<loaner_application__c> laList = [select id,loaner_request_number__c,loaner_manage_place__c,return_Number__c, Status__c, Return_Track_Company__c, Return_Track_Number__c, Return_Trake_Staff__c,Equipment_Type__c,loaner_return__c from loaner_application__c where id = :laId];
+        if (laList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+
+        loaner_application__c la = laList[0];
+        //String.contains(String str)
+        //Boolean isOK = true;
+        List<loaner_application__c> lappList = [select id,AllLead_OrderName__c,Equipment_Type__c  from loaner_application__c where  Status__c = '宸叉壒鍑�'];
+        if(lappList.size() > 0){
+            for(loaner_application__c lapp : lappList){
+                if(lapp.AllLead_OrderName__c != null){
+                    if(lapp.AllLead_OrderName__c.contains(la.loaner_request_number__c) && lapp.Equipment_Type__c == 'BS'){
+                        return '瀛樺湪宸叉壒鍑嗙殑杞�熺敵璇峰崟锛岃鐐瑰嚮 杞�熷彂璐�';
+                    }
+                }
+            }
+        }
+        /*if(lappList.size() > 0){
+            return '鏈夊凡鎵瑰噯鐨勮浆鍊熻鍊熺敤鍗曚腑鏍锋満鐨勫�熺敤鍗曪紝涓嶈兘鍏ㄩ儴鍥炲瘎';
+        }*/
+        
+        if (la.Status__c != '閮ㄥ垎鍙戣揣' && la.Status__c != '鍏ㄩ儴鍙戣揣' && la.Status__c != '鐢宠鑰呭凡鏀惰揣' && la.Status__c != '鐢宠鑰呭凡瑁呮満纭' && la.Status__c != '閮ㄥ垎鍥炲瘎') {
+            return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛鍏ㄩ儴鍥炲瘎銆傜姸鎬侊細' + la.Status__c;
+        }
+        if((la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI') && la.loaner_return__c == true){
+            system.debug('111');
+            /*if(la.Status__c != '鐢宠鑰呭凡瑁呮満纭'){
+                return '蹇呴』瑁呮満纭鎵嶅彲浠ュ洖瀵勬牱鏈�';
+            }*/
+            if(la.loaner_manage_place__c == null || la.loaner_manage_place__c == ''){
+                return '璇峰~鍐欐牱鏈虹鐞嗗湴';
+            }
+            if(la.Return_Trake_Staff__c == null || la.Return_Trake_Staff__c == ''){
+                return '璇峰~鍐欒繑鍝佷汉';
+            }
+            if(la.return_Number__c == null || la.return_Number__c == ''){
+                return '璇峰~鍐欒繑鍝佷汉鐢佃瘽';
+            }
+        }else{
+            if(la.Equipment_Type__c == 'BS' && la.Status__c != '鐢宠鑰呭凡瑁呮満纭'){
+                return '鏈鏈虹‘璁わ紝涓嶈兘鍏ㄩ儴鍥炲瘎銆�';
+            }
+            if (la.Return_Track_Company__c == null || la.Return_Track_Company__c == '' ||
+                la.Return_Track_Number__c == null || la.Return_Track_Number__c == '' ||
+                la.Return_Trake_Staff__c == null) {
+                return '鍥炲瘎淇℃伅涓嶅畬鏁达紝璇峰~鍐欏洖瀵勪俊鎭��';
+            }
+
+        }
+        system.debug('222222222');
+        List<loaner_application_detail__c> ladList = [select id, LOANER__c, LOANER__r.RecordType.DeveloperName from loaner_application_detail__c where loaner_application__c = :laId and (RAESD_Status__c = '宸插嚭搴�' or RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣' or RAESD_Status__c = '鐢宠鑰呮敹璐G' or RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭')];
+        if (ladList.size() == 0) {
+            return '鏍锋満宸茬粡鍏ㄩ儴鍥炲瘎銆�';
+        }
+        Loaner_Express__c le = new Loaner_Express__c();
+        system.debug(la.Equipment_Type__c+'++++++++'+la.loaner_return__c);
+        if((la.Equipment_Type__c != 'NDT' && la.Equipment_Type__c != 'ANI') || la.loaner_return__c == false || la.loaner_return__c == null){
+            system.debug('1');
+            la.Status__c = '鍏ㄩ儴鍥炲瘎';
+            la.Asset_Return_Date__c = Date.today();
+            la.Asset_Return_Date_All__c = Date.today();
+
+            Date temp = Date.today();
+           
+            le.loaner_application__c = laId;
+            le.Name = temp.day()+ '鏃ュ洖瀵勭墿娴佸崟';
+            le.IsDeliveryLogistics__c = false;
+            insert le;
+
+            Integer count = 0;
+
+            for (loaner_application_detail__c lad : ladList) {
+                lad.Return_Express__c = le.id;
+                lad.RAESD_Status__c = '宸插洖瀵�';
+                lad.Asset_Return_Date__c = Date.today();
+                lad.loaner_manage_place__c = la.loaner_manage_place__c;
+                lad.Return_Track_Company__c = la.Return_Track_Company__c;
+                lad.Return_Track_Number__c = la.Return_Track_Number__c;
+                lad.Return_Trake_Staff__c = la.Return_Trake_Staff__c;
+                lad.return_Number__c = la.return_Number__c;
+                //lad.inTime__c = Datetime.now();
+                count++;
+            }
+
+            le.Asset_Return_Date__c = Date.today();
+            le.Return_LogisticsCompany__c = la.Return_Track_Company__c;
+            le.Return_LogisticsNumber__c = la.Return_Track_Number__c;
+            le.Return_Sender__c = la.Return_Trake_Staff__c;
+            le.NotReceivingNum__c = count;
+            le.return_Number__c = la.return_Number__c;
+    /*        List<Asset> astList = new List<Asset>();
+            for (loaner_application_detail__c lad : ladList) {
+                if (lad.LOANER__r.RecordType.DeveloperName == 'loaner_individual') {
+                    Asset ast = new Asset(Id = lad.LOANER__c);
+                    ast.Status = '鍦ㄥ簱';
+                    astList.add(ast);
+                }
+            }*/
+        }else{
+            system.debug('2');
+            la.Status__c = '鍏ㄩ儴鍥炴敹';
+            la.Asset_Return_Date__c = Date.today();
+            la.Asset_Return_Date_All__c = Date.today();
+            la.LoanerClosedDateAll__c = Date.today();
+            for (loaner_application_detail__c lad : ladList) {
+                lad.RAESD_Status__c = '宸插洖鏀�';
+                lad.Asset_Return_Date__c = Date.today();
+                lad.loaner_manage_place__c = la.loaner_manage_place__c;
+                lad.Return_Track_Company__c = '鑷繁閫佽繕';
+                lad.Return_Track_Number__c = '鑷繁閫佽繕';
+                lad.Return_Trake_Staff__c = la.Return_Trake_Staff__c;
+                lad.Lost_item_check_Date__c = Date.today();
+                lad.Received_loaner_Date__c = Date.today();
+                lad.return_Number__c = la.return_Number__c;
+                //lad.inTime__c = Datetime.now();
+                lad.Check_lost_Item__c = 'ok';
+            }
+            le = null;
+        }
+        try{
+            if(le != null){
+                update le;
+            }
+
+            if(ladList != null){
+                update ladList;
+            }
+            if(la != null){
+                update la;
+            }
+            //update astList;
+        } catch(Exception ex) {
+            return ex.getMessage() + '|Line:' + ex.getLineNumber();
+        }
+
+        return '1';
+    }
+
+    webservice static String splitLoanerApplication(String laId){
+        test001();
+        List<loaner_application__c> laCheckList = [select id, Status__c, Equipment_Type__c from loaner_application__c where id = :laId];
+        if (laCheckList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+        loaner_application__c laCheck = laCheckList[0];
+
+        if (laCheck.Equipment_Type__c == 'IE') { 
+            if (laCheck.Status__c != '閿�鍞媴褰撴壒鍑�') {
+                return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛鍒嗗壊鐢宠銆傜姸鎬侊細' + laCheck.Status__c;
+            } 
+        }else if(laCheck.Equipment_Type__c == 'NDT' || laCheck.Equipment_Type__c == 'ANI'){
+            if(laCheck.Status__c != '宸叉壒鍑�'){
+                return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛鍒嗗壊鐢宠銆傜姸鎬侊細' + laCheck.Status__c;
+            }
+        }else{
+            return laCheck.Equipment_Type__c + '涓嶅彲浠ュ仛鍒嗗壊鐢宠銆�';    
+        }
+        
+        List<AggregateResult> checkList = [select LOANER__r.loaner_place__c lp
+                                             from loaner_application_detail__c
+                                            where loaner_application__c = :laId
+                                            group by LOANER__r.loaner_place__c
+                                            order by LOANER__r.loaner_place__c];
+        if (checkList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠娌℃湁鏄庣粏锛屼笉鑳藉仛鍒嗗壊鐢宠銆�';
+        }
+        if (checkList.size() == 1) {
+            return '鍊熷嚭鏍锋満鐨勫瓨鏀惧湴涓�鑷达紝涓嶉渶瑕佸仛鍒嗗壊鐢宠';
+        }
+
+        Schema.DescribeSobjectResult d_la = loaner_application__c.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_la_map = d_la.fields.getMap();
+        String soql_la = 'select ';
+        String fields_la = '';
+        for (String field : d_la_map.keySet()) {
+            if (fields_la.length() > 0) {
+                fields_la += ', ';
+            }
+            fields_la += field;
+        }
+        soql_la += fields_la;
+        soql_la += ' from loaner_application__c where Id = \'' + laId + '\'';
+        List<loaner_application__c> laList = Database.query(soql_la);
+
+        loaner_application__c la_org = laList[0];
+
+        Schema.DescribeSobjectResult d_lad = loaner_application_detail__c.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_lad_map = d_lad.fields.getMap();
+        String soql_lad = 'select ';
+        String fields_lad = '';
+        for (String field : d_lad_map.keySet()) {
+            if (fields_lad.length() > 0) {
+                fields_lad += ', ';
+            }
+            fields_lad += field;
+        }
+        soql_lad += fields_lad;
+        soql_lad += ' from loaner_application_detail__c where loaner_application__c = \'' + laId + '\'';
+        soql_lad += ' order by loaner_place__c';
+        List<loaner_application_detail__c> ladList = Database.query(soql_lad);
+
+        List<String> keyList = new List<String>();
+        Map<String, List<loaner_application_detail__c>> keyMap = new Map<String, List<loaner_application_detail__c>>();
+        String loaner_place_back = '*start*';
+
+        for (loaner_application_detail__c lad : ladList) {
+            if (lad.loaner_place__c != loaner_place_back) {
+                List<loaner_application_detail__c> temp = new List<loaner_application_detail__c>();
+                temp.add(lad);
+
+                keyList.add(lad.loaner_place__c);
+                keyMap.put(lad.loaner_place__c, temp);
+
+                loaner_place_back = lad.loaner_place__c;
+            } else {
+                List<loaner_application_detail__c> temp = keyMap.get(lad.loaner_place__c);
+                temp.add(lad);
+            }
+        }
+
+        try {
+            List<loaner_application__c> insList = new List<loaner_application__c>();
+            Map<String, loaner_application__c> insMap = new Map<String, loaner_application__c>();
+            String otherName = '';
+
+            for (Integer i = 1; i < keyList.size(); i++) {
+                String key = keyList[i];
+                loaner_application__c la_new = la_org.clone();
+                la_new.Id = null;
+               // la_new.IsSplitLoanerApplication__c = true;
+                la_new.Name = la_new.Name + '-' + ('00' + i).right(2);
+                otherName = otherName + la_new.Name + ' \r\n ';
+                la_new.loaner_place__c = key;
+                insList.add(la_new);
+                insMap.put(key, la_new);
+            }
+            insert insList;
+
+             if (keyList.size() > 0) {
+                la_org.loaner_place__c = keyList[0];
+                la_org.IsSplitLoanerApplication__c = true;
+                la_org.Other_Form__c = otherName;
+            }
+            update la_org;
+
+            List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+            for (Integer i = 1; i < keyList.size(); i++) {
+                String key = keyList[i];
+                for (loaner_application_detail__c lad : keyMap.get(key)) {
+                    lad.loaner_application__c = insMap.get(key).Id;
+                    updList.add(lad);
+                }
+            }
+            update updList;
+
+        } catch(Exception ex) {
+            return ex.getMessage() + '|Line:' + ex.getLineNumber();
+        }
+
+        return '1';
+    }
+
+    webservice static String cancelLoanerApplication(String laId){
+        List<loaner_application__c> laList = [select id, Status__c, Cancel_Reason__c from loaner_application__c where id = :laId];
+        if (laList.size() == 0) {
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+        loaner_application__c la = laList[0];
+        if (la.Status__c != '鑽夋涓�' && la.Status__c != '閿�鍞媴褰撴壒鍑�' && la.Status__c != '宸叉壒鍑�') {
+            return '鏍锋満鍊熷嚭鐢宠鐘舵�佷笉姝g‘锛屼笉鑳藉仛鍙栨秷銆傜姸鎬侊細' + la.Status__c;
+        }
+        if (la.Cancel_Reason__c == null || la.Cancel_Reason__c == '') {
+            return '璇疯緭鍏ュ彇娑堢悊鐢便��';
+        }
+
+        List<loaner_application_detail__c> ladList = [select id, LOANER__c, LOANER__r.RecordType.DeveloperName from loaner_application_detail__c where loaner_application__c = :laId];
+
+        la.Status__c = '鍙栨秷';
+        la.Cancel_Date__c = Date.today();
+
+        for (loaner_application_detail__c lad : ladList) {
+            lad.RAESD_Status__c = '鍙栨秷';
+            lad.Cancel_Date__c = Date.today();
+        }
+
+        List<Asset> astList = new List<Asset>();
+        for (loaner_application_detail__c lad : ladList) {
+            if (lad.LOANER__r.RecordType.DeveloperName == 'loaner_individual') {
+                Asset ast = new Asset(Id = lad.LOANER__c);
+                ast.Status = '鍦ㄥ簱';
+                astList.add(ast);
+            }
+        }
+
+        try{    
+            update ladList;
+            update la;
+            update astList;
+        } catch(Exception ex) {
+            return ex.getMessage() + '|Line:' + ex.getLineNumber();
+        }
+
+        return '1';
+    }
+    /*
+     *妫�鏌ユ墍鍒嗛厤涓綋绠$悊鏍锋満鏍锋満鏄惁閮藉湪搴擄紝 
+     *妫�鏌ユ墍鍒嗛厤鏁伴噺绠$悊鏍锋満鏄惁閮芥湁瓒冲鏁伴噺鐢ㄦ潵鍒嗛厤銆�
+    */
+    webservice static String haveFreeze(String laId){
+        if(laId == null || laId == ''){
+            return '鏍锋満鍊熷嚭鐢宠涓嶅瓨鍦ㄣ��';
+        }
+
+        loaner_application__c la = [select id,Loaner_LendOrder__c from loaner_application__c where id =: laId];
+
+        if(la.Loaner_LendOrder__c == true ){ 
+            return '1';
+        }
+        //鑾峰彇鏁伴噺绠$悊鍜屼釜浣撶鐞嗙殑鏄庣粏
+        List<loaner_application_detail__c> ladList = [select id,LOANER__r.Status,LOANER__r.Name from loaner_application_detail__c where LOANER__r.RecordType.DeveloperName = 'loaner_individual' and loaner_application__c = :laId];        
+        List<AggregateResult> ladList1 = [select LOANER__c,count(Id) LoanerNO from loaner_application_detail__c where LOANER__r.RecordType.DeveloperName = 'loaner_number' and loaner_application__c = :laId GROUP by LOANER__c];
+        //鏁伴噺绠$悊鍒ゆ柇
+        if(ladList1.size() > 0){
+            List<String> loanerIdList = new List<String>(); 
+            Map<String,Integer> loanerMap = new Map<String,Integer>();
+
+            for(AggregateResult ar:ladList1){
+                loanerIdList.add(String.valueOf(ar.get('LOANER__c')));
+                loanerMap.put(String.valueOf(ar.get('LOANER__c')), Integer.valueOf(ar.get('LoanerNO')));
+            }
+
+            List<Asset> assetList = [select id,Count_can_allocate_F__c,Name from Asset where Id = :loanerIdList];
+
+            for(Asset ass : assetList){
+                //濡傛灉鍒嗛厤鏁伴噺澶т簬鏍锋満鍙垎閰嶆暟閲忓垯鎻愮ず閿欒
+                if(loanerMap.get(ass.Id) > ass.Count_can_allocate_F__c){
+                    return '鎮ㄦ墍鍒嗛厤鐨勬牱鏈篭''+ass.Name+'\'搴撳瓨涓嶈冻锛岀幇浣�'+ass.Count_can_allocate_F__c+'涓紝璇疯皟鏁村垎閰嶅悗鍐嶆彁浜�.';
+                }
+            }
+
+        }
+        //涓綋绠$悊鍒ゆ柇
+        if(ladList.size() > 0){
+            for(loaner_application_detail__c lad : ladList){ 
+                //濡傛灉瀛樺湪鐘舵�佷笉鏄�'鍦ㄥ簱'鐨勬牱鏈哄垯鎻愮ず閿欒
+                if(lad.LOANER__r.Status != '鍦ㄥ簱'){
+                    return '鎮ㄦ墍鍒嗛厤鐨勬牱鏈篭''+lad.LOANER__r.Name+'\'宸插喕缁擄紝璇烽噸鏂板垎閰嶅湪搴撴牱鏈�.';
+                }
+            }
+        }
+        return '1';
+        
+    }
+
+
+
+
+
+
+    private static void test001(){
+        Integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerApplicationWebService.cls-meta.xml b/scr/classes/LoanerApplicationWebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LoanerApplicationWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerApplicationWebServiceTest.cls b/scr/classes/LoanerApplicationWebServiceTest.cls
new file mode 100644
index 0000000..f98ab58
--- /dev/null
+++ b/scr/classes/LoanerApplicationWebServiceTest.cls
@@ -0,0 +1,603 @@
+@isTest
+private class LoanerApplicationWebServiceTest {
+	static Product2 prd1;
+    static Product2 prd2;
+    static Account acc;
+    static Account dealer;
+    static Contact core;
+    static User testUser;
+    static Asset asset;
+	static void setupTestData() {
+
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+
+		List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'IE';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'IE';
+        acc.PostCode__c='000000';
+        insert acc;
+
+		// 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'IE';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'IE';
+        assetC1.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        insert new Asset[] {asset,assetC1};
+	}
+	//鍑哄簱鎸囩ず
+	@isTest static void loanIndicationTest() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+        LoanerApplicationWebService.loanIndication('111111111111111');
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.pickup_time__c = Date.today().addDays(2);
+        insert loanerApp;
+        LoanerApplicationWebService.loanIndication(loanerApp.Id);
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        update loanerApp;
+        LoanerApplicationWebService.loanIndication(loanerApp.Id);
+
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '宸叉壒鍑�';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+        LoanerApplicationWebService.loanIndication(loanerApp.Id);
+	}
+	@isTest static void sendOutAllTest01() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+        System.Test.startTest();
+        LoanerApplicationWebService.sendOutAll('111111111111111');
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        insert loanerApp;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+        loanerApp.Status__c = '宸插嚭搴撴寚绀�';
+       	update loanerApp;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+        loanerApp.Status__c = '鍑哄簱鍓嶅凡妫�娴�';
+        update loanerApp;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+        loanerApp.pickup_time__c = Date.today();
+        update loanerApp;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+        System.Test.stopTest();
+
+	}
+	@isTest static void sendOutAllTest02() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鍑哄簱鍓嶅凡妫�娴�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.delivery_company__c = '111111111';
+        loanerApp.Tracking_Number__c = '22222222';
+        loanerApp.Return_to_wh_staff__c = testUser.Id;
+        insert loanerApp;
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+        LoanerApplicationWebService.sendOutAll(loanerApp.Id);
+	}
+
+	@isTest static void installConfirmTest() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.delivery_company__c = '111111111';
+        loanerApp.Tracking_Number__c = '22222222';
+        loanerApp.Return_to_wh_staff__c = testUser.Id;
+        insert loanerApp;
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        LoanerApplicationWebService.installConfirm('111111111');
+        LoanerApplicationWebService.installConfirm(loanerApp.Id);
+        loanerApp.Status__c = '鐢宠鑰呭凡鏀惰揣';
+        update loanerApp;
+        LoanerApplicationWebService.installConfirm(loanerApp.Id);
+
+        LoanerApplicationWebService.sendBackAll(loanerApp.Id);
+	}
+
+	@isTest static void sendBackAllTest() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.delivery_company__c = '111111111';
+        loanerApp.Tracking_Number__c = '22222222';
+        loanerApp.Return_to_wh_staff__c = testUser.Id;
+        insert loanerApp;
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        LoanerApplicationWebService.sendBackAll('111111111');
+        LoanerApplicationWebService.sendBackAll(loanerApp.Id);
+        loanerApp.Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerApp.Return_Track_Company__c = '11111';
+        loanerApp.Return_Track_Number__c = '11111';
+        loanerApp.Return_Trake_Staff__c = '11111';
+        update loanerApp;
+        LoanerApplicationWebService.sendBackAll(loanerApp.Id);
+
+	}
+    @isTest static void sendBackAllTest1() {
+        setupTestData();
+
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'NDT'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'NDT';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'NDT';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '鍩硅';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.delivery_company__c = '111111111';
+        loanerApp.Tracking_Number__c = '22222222';
+        loanerApp.Return_to_wh_staff__c = testUser.Id;
+        insert loanerApp;
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        LoanerApplicationWebService.sendBackAll('111111111');
+        LoanerApplicationWebService.sendBackAll(loanerApp.Id);
+        loanerApp.Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerApp.Return_Track_Company__c = '11111';
+        loanerApp.Return_Track_Number__c = '11111';
+        loanerApp.Return_Trake_Staff__c = '11111';
+        loanerApp.loaner_manage_place__c = '鍖椾含閰掍粰妗�';
+        loanerApp.loaner_return__c = true;
+        update loanerApp;
+        LoanerApplicationWebService.sendBackAll(loanerApp.Id);
+
+    }
+
+	@isTest static void splitLoanerApplicationTest() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '宸叉壒鍑�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.delivery_company__c = '111111111';
+        loanerApp.Tracking_Number__c = '22222222';
+        loanerApp.Return_to_wh_staff__c = testUser.Id;
+        insert loanerApp;
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-02';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = asset.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+        System.Test.startTest();
+
+        LoanerApplicationWebService.splitLoanerApplication('111111111');
+        loanerApp.Status__c = '鐢宠鑰呭凡鏀惰揣';
+        update loanerApp;
+
+        LoanerApplicationWebService.splitLoanerApplication(loanerApp.Id);
+        loanerApp.Status__c = '閿�鍞媴褰撴壒鍑�';
+        update loanerApp;
+        LoanerApplicationWebService.splitLoanerApplication(loanerApp.Id);
+        System.Test.stopTest();
+
+	}
+
+	@isTest static void cancelLoanerApplicationTest() {
+		setupTestData();
+
+		List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd1.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC2.Remarks2__c = 'assetC2';
+        insert assetC2;
+		loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Rental_Start_Date__c = Date.today();
+        loanerApp.Rental_End_Date__c = Date.today();
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'IE';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '婕旂ず';
+        loanerApp.Request_shipping_Date__c = Date.today();
+        loanerApp.Request_return_Date__c = Date.today();
+        loanerApp.delivery_company__c = '111111111';
+        loanerApp.Tracking_Number__c = '22222222';
+        loanerApp.Return_to_wh_staff__c = testUser.Id;
+        loanerApp.pickup_time__c = Date.today().addDays(2);
+        insert loanerApp;
+        loaner_application_detail__c loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-01';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = assetC2.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        loanerAppDet = new loaner_application_detail__c();
+        loanerAppDet.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        loanerAppDet.Name = 'TESTYJ0001-02';
+        loanerAppDet.loaner_application__c = loanerApp.Id;
+        loanerAppDet.LOANER__c = asset.Id;
+        loanerAppDet.Allocate_Date__c = Date.today();
+        insert loanerAppDet;
+
+        LoanerApplicationWebService.cancelLoanerApplication('111111111');
+        LoanerApplicationWebService.cancelLoanerApplication(loanerApp.Id);
+        loanerApp.Status__c = '宸叉壒鍑�';
+        update loanerApp;
+        LoanerApplicationWebService.cancelLoanerApplication(loanerApp.Id);
+        loanerApp.Cancel_Reason__c = 'test';
+        update loanerApp;
+        LoanerApplicationWebService.cancelLoanerApplication(loanerApp.Id);
+
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerApplicationWebServiceTest.cls-meta.xml b/scr/classes/LoanerApplicationWebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LoanerApplicationWebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerExpressTriggerHandler.cls b/scr/classes/LoanerExpressTriggerHandler.cls
new file mode 100644
index 0000000..29ed9cf
--- /dev/null
+++ b/scr/classes/LoanerExpressTriggerHandler.cls
@@ -0,0 +1,178 @@
+public without sharing class LoanerExpressTriggerHandler {
+	
+	public static void updateExpress(List<Loaner_Express__c> newList, Map<Id, Loaner_Express__c> newMap, List<Loaner_Express__c> oldList, Map<Id, Loaner_Express__c> oldMap){
+		List<String> expressIDList = new List<String>();
+		List<String> returnIDList = new List<String>();
+		List<String> lendOrderList = new List<String>();
+		Loaner_Express__c old = null;
+		for(Loaner_Express__c express : newList){
+			old = oldMap.get(express.Id);
+			if(old.consignor__c != express.consignor__c || old.Consignor_LogisticsCompany__c != express.Consignor_LogisticsCompany__c || old.Consignor_LogisticsNumber__c != express.Consignor_LogisticsNumber__c){
+				expressIDList.add(express.Id);
+			}
+			if(old.Return_Sender__c != express.Return_Sender__c || old.Return_LogisticsCompany__c != express.Return_LogisticsCompany__c || old.Return_LogisticsNumber__c != express.Return_LogisticsNumber__c){
+				returnIDList.add(express.Id);
+				if(express.IsLendOrder__c && express.LendOrder__c != null){
+					lendOrderList.add(express.Id);
+				}
+			}
+		}
+		List<loaner_application_detail__c> updateList = new List<loaner_application_detail__c>();
+		if(expressIDList.size() != 0){
+			List<loaner_application_detail__c> ladList =[select id,Loaner_Express__c from loaner_application_detail__c where Loaner_Express__c = :expressIDList]; 
+			for(loaner_application_detail__c lad : ladList){
+				Loaner_Express__c express = newMap.get(lad.Loaner_Express__c);
+				if(express.IsDeliveryLogistics__c){
+					lad.Return_to_wh_staff__c = express.consignor__c;
+					lad.delivery_company__c = express.Consignor_LogisticsCompany__c;
+					lad.Tracking_Number__c = express.Consignor_LogisticsNumber__c;
+				}
+				updateList.add(lad);
+			}
+		}
+		if(returnIDList.size() != 0){
+			List<loaner_application_detail__c> ladList =[select id,Return_Express__c from loaner_application_detail__c where Return_Express__c = :returnIDList]; 
+			system.debug(ladList.size());
+			for(loaner_application_detail__c lad: ladList){
+				Loaner_Express__c express = newMap.get(lad.Return_Express__c);
+				if(!express.IsDeliveryLogistics__c){
+					lad.Return_Trake_Staff__c = express.Return_Sender__c;
+					lad.Return_Track_Company__c = express.Return_LogisticsCompany__c;
+					lad.Return_Track_Number__c = express.Return_LogisticsNumber__c;
+				}
+				updateList.add(lad);
+			}
+		}
+		List<Loaner_Express__c> upLeList = new List<Loaner_Express__c>();
+		if(lendOrderList.size()>0){
+			for(String leId:lendOrderList){
+				Loaner_Express__c temp = newMap.get(leId);
+				Loaner_Express__c le = new Loaner_Express__c();
+				le.Id = temp.LendOrder__c;
+				le.Consignor_LogisticsCompany__c = temp.Return_LogisticsCompany__c;
+				le.Consignor_LogisticsNumber__c = temp.Return_LogisticsNumber__c;
+				upLeList.add(le);
+			}
+		}
+		ControllerUtil.updateExpress(upLeList);
+		//update upLeList;
+		update updateList;
+	}
+
+	public static void emailDate(List<Loaner_Express__c> newList, Map<Id, Loaner_Express__c> newMap, List<Loaner_Express__c> oldList, Map<Id, Loaner_Express__c> oldMap){
+		List<String> autoId = new List<String>();
+		List<String> remindId = new List<String>();
+
+		for(Loaner_Express__c le : newList){
+			Loaner_Express__c old = oldMap.get(le.id);
+			system.debug('leName:'+le.Name+'------'+le.Automatic_Received_Date__c+'======'+le.Shipment_Request_Date__c);
+			if(le.Automatic_Received_Date__c == null && le.Shipment_Request_Date__c != null){
+				autoId.add(le.id);
+			}
+			if(le.Automatic_Received_Date__c != old.Automatic_Received_Date__c){
+				remindId.add(le.id);
+			}
+		}
+		system.debug(autoId.size());
+		Map<String,OlympusCalendar__c> oCalendar = calendarUtil.getCalendarMap(Date.today().addDays(-10),Date.today().addDays(240));
+		List<Loaner_Express__c> autoList = new List<Loaner_Express__c>();
+		List<Loaner_Express__c> remindList = new List<Loaner_Express__c>();
+		List<loaner_application_detail__c> ladList = new List<loaner_application_detail__c>();
+		if(autoId.size()>0){
+			autoList = [select id,Shipment_Request_Date__c,Loaner_type__c from Loaner_Express__c where id= :autoId];
+			for(Loaner_Express__c auto : autoList){
+				if(auto.Loaner_type__c == 'NDT' || auto.Loaner_type__c == 'ANI'){
+					auto.Automatic_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Shipment_Request_Date__c,3);
+					auto.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Automatic_Received_Date__c,-2);
+				}else{
+					auto.Automatic_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Shipment_Request_Date__c,5);
+					auto.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,auto.Automatic_Received_Date__c,-3);
+				}
+				
+			}
+		}
+		system.debug(autoList);
+		if(remindId.size()>0){
+			remindList = [select id,Automatic_Received_Date__c,Loaner_type__c from Loaner_Express__c where id= :remindId];
+			
+			for(Loaner_Express__c remind : remindList){
+				if(remind.Loaner_type__c == 'NDT' || remind.Loaner_type__c == 'ANI'){
+					remind.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Automatic_Received_Date__c,-2);
+				}else{
+					remind.Remind_Received_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Automatic_Received_Date__c,-3);
+				}
+			}
+			for(loaner_application_detail__c lad : [select id,Loaner_Express__c from loaner_application_detail__c where Loaner_Express__c= :remindId]){
+				lad.Automatic_Received_Date__c = newMap.get(lad.Loaner_Express__c).Automatic_Received_Date__c;
+
+				ladList.add(lad);
+			}
+		}
+		if(autoList.size()>0) update autoList;
+		if(remindList.size()>0) {
+			update remindList;
+			update ladList;
+		}
+	}
+
+	public static void getApprover(List<Loaner_Express__c> newList, Map<Id, Loaner_Express__c> newMap, List<Loaner_Express__c> oldList, Map<Id, Loaner_Express__c> oldMap){
+		List<Loaner_Express__c> leIdList = new List<Loaner_Express__c>();
+		for(Loaner_Express__c le : newList){
+			if(le.Approver__c == null){
+				leIdList.add(le);
+			}
+		}
+
+		if(leIdList.size() >0){
+			List<Loaner_Express__c> leList = new List<Loaner_Express__c>();
+			for(Loaner_Express__c le : [select id,loaner_application__r.loaner_Manager__c,loaner_application__r.Approver__c,loaner_application__r.OwnerId from Loaner_Express__c where id=:leIdList]){
+				le.Approver__c = le.loaner_application__r.loaner_Manager__c;
+				le.sales_User__c = le.loaner_application__r.Approver__c;
+				le.Loaner_Agent__c = le.loaner_application__r.OwnerId;
+				leList.add(le);
+			}
+			if(leList.size()>0){
+				update leList;
+			}
+		}
+	}
+
+	public static void updateName(List<Loaner_Express__c> newList, Map<Id, Loaner_Express__c> newMap, List<Loaner_Express__c> oldList, Map<Id, Loaner_Express__c> oldMap){
+		List<String> leList1 = new List<String>();
+		List<String> leList2 = new List<String>();
+		List<Loaner_Express__c> updateList = new List<Loaner_Express__c>();
+		for(Loaner_Express__c le : newList){
+			Loaner_Express__c old = oldMap.get(le.id);
+			if((le.Return_LogisticsNumber__c != old.Return_LogisticsNumber__c ||le.Return_LogisticsCompany__c != old.Return_LogisticsCompany__c) && le.IsDeliveryLogistics__c == false ){
+				leList1.add(le.id);
+			}
+
+			if(( le.Consignor_LogisticsNumber__c != old.Consignor_LogisticsNumber__c || le.Consignor_LogisticsCompany__c != old.Consignor_LogisticsCompany__c) && le.IsDeliveryLogistics__c == true){
+				leList2.add(le.id);
+ 
+			}
+		}
+		if(leList1.size()>0){
+			for(Loaner_Express__c le : [select id,Asset_Return_Date__c,Return_LogisticsNumber__c,IsLendOrder__c,LendOrder__c,Return_LogisticsCompany__c from Loaner_Express__c where id=:leList1]){
+				le.Name =le.Asset_Return_Date__c.day()+'鏃ュ洖瀵勭墿娴佸崟-'+ le.Return_LogisticsCompany__c+le.Return_LogisticsNumber__c;
+				updateList.add(le);
+				if(le.IsLendOrder__c && le.LendOrder__c != null){
+					Loaner_Express__c temp = new Loaner_Express__c();
+					temp.id = le.LendOrder__c;
+					temp.Name = le.Asset_Return_Date__c.day()+'鏃ュ彂璐ф祦鍗�-'+ le.Return_LogisticsCompany__c+le.Return_LogisticsNumber__c;
+					updateList.add(temp);
+				}
+			}
+		}
+		if(leList2.size()>0){
+			for(Loaner_Express__c le :  [select id,Shipment_Request_Date__c,Consignor_LogisticsNumber__c,Consignor_LogisticsCompany__c from Loaner_Express__c where id=:leList2]){
+				le.Name = le.Shipment_Request_Date__c.day()+'鏃ュ彂璐х墿娴佸崟-'+le.Consignor_LogisticsCompany__c+le.Consignor_LogisticsNumber__c;
+				updateList.add(le);
+			}
+			
+		}
+		if(updateList.size()>0) ControllerUtil.updateExpress(updateList);
+	}
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerExpressTriggerHandler.cls-meta.xml b/scr/classes/LoanerExpressTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerExpressTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerExpressTriggerHandlerTest.cls b/scr/classes/LoanerExpressTriggerHandlerTest.cls
new file mode 100644
index 0000000..2d889c7
--- /dev/null
+++ b/scr/classes/LoanerExpressTriggerHandlerTest.cls
@@ -0,0 +1,134 @@
+@isTest
+private class LoanerExpressTriggerHandlerTest {
+	
+	@isTest static void test_method_one() {
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+       	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner.Request_return_Date__c = Date.today().addDays(10);
+        loaner.Status__c = '閮ㄥ垎鍙戣揣';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插嚭搴�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+		//detail.Shipment_Request_Date__c = Date.today();
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        Loaner_Express__c le = new Loaner_Express__c(
+        	Name = 'test01',
+        	loaner_application__c = loaner.Id
+        	);
+
+        insert le;
+        In_detail[2].Loaner_Express__c = le.Id;
+       	le.Consignor_LogisticsNumber__c ='test123123';
+        le.Consignor_LogisticsCompany__c = 'testCompany';
+        le.Shipment_Request_Date__c = Date.today().addDays(3);       
+        le.NotReceivingNum__c = 1;
+        update le;
+        update In_detail;
+
+        le.Consignor_LogisticsNumber__c = '3232323';
+        update le;
+
+         Loaner_Express__c le1 = new Loaner_Express__c(
+        	Name = 'test01',
+        	loaner_application__c = loaner.Id
+        	);
+
+        insert le1;
+
+        In_detail[1].Return_Express__c = le1.Id;
+        update In_detail;
+       	le1.Return_LogisticsNumber__c ='test123123';
+        le1.Return_LogisticsCompany__c = 'testCompany';
+        le1.Asset_Return_Date__c = Date.today().addDays(3);       
+        le1.NotReceivingNum__c = 1;
+        le1.IsDeliveryLogistics__c = false;
+        update le1;
+        
+
+        le.Return_LogisticsNumber__c = '3232323';
+        update le;
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerExpressTriggerHandlerTest.cls-meta.xml b/scr/classes/LoanerExpressTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerExpressTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerLendDeliverController.cls b/scr/classes/LoanerLendDeliverController.cls
new file mode 100644
index 0000000..dfc92b2
--- /dev/null
+++ b/scr/classes/LoanerLendDeliverController.cls
@@ -0,0 +1,2237 @@
+public without sharing class LoanerLendDeliverController {
+         // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c lac {get;private set;}
+    public loaner_application__c la { get; private set; }
+
+    public Set<String> laSet {get; private set;}
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    public List<loaner_application_detail__c> lad1s {get; private set;}
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerLendDeliverController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,Return_Trake_Staff__c,Return_Track_Company__c,Return_Track_Number__c,Status__c,Equipment_Type__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        lac = new loaner_application__c();
+        User temp = [select id,Name from User where id = :UserInfo.getUserId()];
+        lac.Return_Trake_Staff__c = temp.Name;
+
+        List<String> benId = new List<String>();
+        
+
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id,loaner_application__c, SerialNumber__c, Receipt_Status__c,Internal_Asset_number__c, OTCODE__c, ECCode__c,LOANER__c,LOANER__r.RecordType.Id,loaner_application__r.Loaner_AgreementPDF__c,LOANER__r.Name,LOANER__r.Remarks2__c';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'LoanerLend') {
+            sql_where += ' and RAESD_Status__c in (\'鐢宠鑰呭凡鏀惰揣\',\'鐢宠鑰呭凡瑁呮満纭\')';
+        } else {
+            return null;
+        }
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        System.debug('========1========'+lads);
+        if (lads.size() == 0) {
+            return null;
+        }else{
+            for(loaner_application_detail__c loan : lads){
+                benId.add(loan.id);
+            }
+        }
+        //鑾峰彇璁板綍璇ヤ俊鎭殑鏄庣粏
+        lad1s = [select Id,loaner_Agent__c,loaner_application__r.loaner_request_number__c ,loaner_application__r.Owner.Name,LendPrimary_Name__c,SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c,LOANER__c,loaner_application__c,LOANER__r.RecordType.Id,loaner_application__r.Loaner_AgreementPDF__c,loaner_application__r.pickup_time__c,loaner_application__r.Agent__c,loaner_application__r.Rental_Start_Date__c,loaner_application__r.Rental_end_Date__c from loaner_application_detail__c where LendPrimary_Name__c = :benId  and RAESD_Status__c = '宸叉壒鍑�'];
+        List<loaner_application_detail__c> lad2s = new List<loaner_application_detail__c>();
+        System.debug('==========2======='+lad1s);
+        if(lad1s.size() == 0){
+            
+            return null;
+        }
+        Integer cnt = 0;
+        for(loaner_application_detail__c i : lad1s){
+            for(loaner_application_detail__c j : lads){
+                if(j.id == i.LendPrimary_Name__c){
+                    System.debug('==============3========='+i.LendPrimary_Name__c);
+                    lad2s.add(j);
+                    cnt += 1;
+                    System.debug('杞�熶唬鐞嗗晢锛�'+i.loaner_Agent__c);
+                    //DataLineBean dataLine = new DataLineBean(cnt, j,i.loaner_application__r.Loaner_AgreementPDF__c == true ? '宸蹭笂浼�' : '鏈笂浼�');
+                    DataLineBean dataLine = new DataLineBean(cnt, j,i.loaner_application__r.Loaner_AgreementPDF__c,i.loaner_Agent__c,i.loaner_application__r.loaner_request_number__c); 
+                    dataLines.add(dataLine);
+                }
+            }
+        }
+        // 鏄庣粏Bean浣滄垚
+       /* Integer cnt = 0;
+        for (loaner_application_detail__c lad : lad2s) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        } */
+       // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, String.valueOf(lad1s)));     
+        return null;
+    }
+
+     public PageReference saveBtn() {
+        laSet = new Set<String>();
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        List<Asset> assList = new List<Asset>();
+        Integer count = 0;
+        boolean pickupFalg = false;
+        if(dataLines.size() >0){
+            Loaner_Express__c le = this.createExpress('鍙戣揣');
+            Loaner_Express__c rle = this.createExpress('鍥炲瘎');
+            for (DataLineBean dataLine : dataLines) {   
+                if (dataLine.checkFlag == true) {
+                    if(dataLine.PDFflag == false){
+                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鍊熺敤鏂规湭涓婁紶鍊熺敤鍗忚锛屼笉鑳借繘琛岃浆鍊熷彂璐с��'));
+                        if(le != null ){
+                            delete le;
+                            le = null;
+                        }
+                        if(rle != null){
+                            delete rle;
+                            rle = null;
+                        }
+                        return null;
+                    }                    
+                    loaner_application_detail__c lad = dataLine.lad;
+                    
+                    if(lad.Receipt_Status__c != 'OK' && lad.Receipt_Status__c == null){
+                        lad.Receipt_Status__c = 'OK';
+                        lad.Receipt_Date__c = Date.today();
+                    }
+                    //鍙戣揣鏂规槑缁�
+                    //鏃ユ湡
+                    lad.Asset_Return_Date__c = Date.today();
+                    lad.Received_loaner_Date__c = Date.today();
+                    lad.After_Inspection_Date__c = Date.today();
+                    lad.Arrival_wh_Date__c = Date.today();
+                    lad.inTime__c = Datetime.now();
+                    lad.RAESD_Status__c = '宸插洖搴�';
+                    //涓婃灦妫�鏌�
+                    lad.StockUp__c = true;
+                    lad.Check_lost_Item__c = 'OK';
+                    lad.Inspection_result_after__c = 'OK';
+                    
+                    
+                    for(loaner_application_detail__c temp : lad1s){
+                        if(temp.LendPrimary_Name__c == lad.id){
+                            //鏀惰揣鏂规槑缁�
+                            temp.StockDown__c = true;
+                            temp.outTime__c = Datetime.now();
+                            temp.StockDown_Date__c = Date.today();
+                            temp.Shipment_Request_Date__c = Date.today();
+                            temp.Pre_inspection_Date__c = Date.today();
+                            
+                            
+                            temp.Inspection_result__c ='OK';
+                            
+                            if(temp.loaner_application__r.pickup_time__c == null){
+                                 if(lac.Return_Track_Company__c == null || lac.Return_Track_Company__c == ''){
+                                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欑墿娴佸叕鍙�'));
+                                     if(le != null ){
+                                        delete le;
+                                        le = null;
+                                    }
+                                    if(rle != null){
+                                        delete rle;
+                                        rle = null;
+                                    }
+                                    return null;
+                                }
+                                if(lac.Return_Trake_Staff__c == null || lac.Return_Trake_Staff__c == '' ){
+                                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欏彂璐т汉'));
+                                    if(le != null ){
+                                        delete le;
+                                        le = null;
+                                    }
+                                    if(rle != null){
+                                        delete rle;
+                                        rle = null;
+                                    }
+                                    return null;
+                                }
+
+                                temp.Loaner_Express__c = le.id;
+                                temp.delivery_company__c = lac.Return_Track_Company__c;
+                                temp.Tracking_Number__c = lac.Return_Track_Number__c;
+                                temp.RAESD_Status__c = '宸插嚭搴�';
+                                //鍙戣揣鏂规槑缁嗗洖瀵勭墿娴佷俊鎭�
+                                lad.Return_Trake_Staff__c = lac.Return_Trake_Staff__c;
+                                lad.Return_Track_Number__c = lac.Return_Track_Number__c;
+                                lad.Return_Track_Company__c = lac.Return_Track_Company__c;
+                                lad.Return_Express__c = rle.id;
+                                if(temp.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                                    if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
+                                        Asset loa = new Asset(id = lad.LOANER__c);
+                                        loa.Loaner__c = temp.loaner_application__r.Owner.Name;
+                                        loa.Rental_Customer__c = temp.loaner_application__r.Agent__c;
+                                        loa.Rental_Start_Date__c = temp.loaner_application__r.Rental_Start_Date__c;
+                                        loa.Rental_end_Date__c = temp.loaner_application__r.Rental_end_Date__c;
+                                        assList.add(loa);
+                                    }
+                                } 
+                                 if(laSet.size()>1){
+                                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鎮ㄩ�夋嫨鐨勬牱鏈轰笉鍙睘浜庝竴涓浆鍊熷崟'));
+                                     if(le != null ){
+                                        delete le;
+                                        le = null;
+                                    }
+                                    if(rle != null){
+                                        delete rle;
+                                        rle = null;
+                                    }
+                                    return null;
+                                }       
+                                updList.add(temp);
+                                updList.add(lad);
+                                laSet.add(temp.loaner_application__c);
+                                count++;
+                            }else{
+                                
+                                lad.Return_Trake_Staff__c = lac.Return_Trake_Staff__c;
+                                temp.Receipt_Status__c = 'OK';
+                                temp.Receipt_Date__c =  Date.today();
+                                temp.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                                
+                                if(temp.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                                    if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
+                                        Asset loa = new Asset(id = lad.LOANER__c);
+                                        loa.Rental_Customer__c = temp.loaner_application__r.Agent__c;
+                                        loa.Rental_Start_Date__c = temp.loaner_application__r.Rental_Start_Date__c;
+                                        loa.Rental_end_Date__c = temp.loaner_application__r.Rental_end_Date__c;
+                                        assList.add(loa);
+                                    }
+                                } 
+                                if(laSet.size()>1){
+                                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鎮ㄩ�夋嫨鐨勬牱鏈轰笉鍙睘浜庝竴涓浆鍊熷崟'));
+                                    if(le != null ){
+                                        delete le;
+                                        le = null;
+                                    }
+                                    if(rle != null){
+                                        delete rle;
+                                        rle = null;
+                                    }
+                                    return null;
+                                }     
+                                pickupFalg = true;
+                                updList.add(temp);
+                                updList.add(lad);
+                                laSet.add(temp.loaner_application__c);
+                                if(le != null ){
+                                    delete le;
+                                    le = null;
+                                }
+                                if(rle != null){
+                                    delete rle;
+                                    rle = null;
+                                }
+                            }
+                           
+                        }
+                    }
+                   
+                }
+            }
+            
+            if(!pickupFalg){
+                User temp = [select id,Name from User where id = :UserInfo.getUserId()];
+                rle.Return_Sender__c = lac.Return_Trake_Staff__c;
+                rle.Asset_Return_Date__c = Date.today();
+                rle.Return_LogisticsCompany__c = lac.Return_Track_Company__c;
+                rle.Return_LogisticsNumber__c =  lac.Return_Track_Number__c;
+                rle.LendOrder__c = le.id;
+                rle.IsLendOrder__c = true;
+                rle.loaner_application__c = dataLines[0].lad.loaner_application__c;
+
+                le.Consignor_LogisticsNumber__c = lac.Return_Track_Number__c;
+                le.Consignor_LogisticsCompany__c =lac.Return_Track_Company__c;
+                le.consignor__c = temp.id;
+                le.Shipment_Request_Date__c = Date.today();       
+                le.NotReceivingNum__c = count;
+                le.IsLendOrder__c = true;
+                le.loaner_application__c = lad1s[0].loaner_application__c;
+            }
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                    update updList;
+                    if(la.Status__c != '瀹屾瘯'){
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        if(la.Status__c == '鍏ㄩ儴鍥炲瘎')  la.Asset_Return_Date_All__c = Date.today();
+                        if(la.Status__c == '鍏ㄩ儴鍥炴敹'){   
+                            la.Asset_Return_Date_All__c = Date.today();
+                            la.LoanerClosedDateAll__c = Date.today();
+
+                            if (la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI') {
+                                PrototypeToThaw.UserUnfreeze(la.Id);
+                            }
+
+                        }
+                        la.Asset_Return_Date_All__c = Date.today();
+                        update la;
+                    }
+                    
+                    List<loaner_application__c> templa = new List<loaner_application__c>();
+
+                    for(String loanerId : laSet){
+                        loaner_application__c newla =  new loaner_application__c();
+                        newla.id = loanerId;
+                        newla.Status__c = LoanerOrderState.getOrderStater(loanerId);
+                        if(newla.Status__c == '閮ㄥ垎鍙戣揣') newla.Shipping_Finished_Date__c = Date.today();
+                        if(newla.Status__c == ' 鍏ㄩ儴鍙戣揣' || newla.Status__c == '鐢宠鑰呭凡鏀惰揣'){
+                            newla.Shipping_Finished_Date__c = Date.today();
+                            newla.Shipping_Finished_Date_All__c = Date.today();
+                        }
+                        templa.add(newla);
+                    }
+                    update templa;
+                    if(!pickupFalg){
+                        update le;
+                        update rle;
+                    }
+                    if(assList.size()>0){
+                        update assList;
+                    }
+
+                }else{
+                    if(le != null ){
+                        delete le;
+                        le = null;
+                    }
+                    if(rle != null){
+                        delete rle;
+                        rle = null;
+                    }
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨鍑哄簱鐨勬牱鏈�'));
+                    return null;
+                }
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                if(le != null ){
+                    delete le;
+                    le = null;
+                }
+                if(rle != null){
+                    delete rle;
+                    rle = null;
+                }
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+        }
+       //return null;
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public Loaner_Express__c createExpress(String str){
+        Date temp = Date.today();
+        Loaner_Express__c le = new Loaner_Express__c();
+        le.loaner_application__c = laId;
+        le.Name = temp.day()+ '鏃�'+str+'鐗╂祦鍗�';
+        if(str.equals('鍥炲瘎')) le.IsDeliveryLogistics__c = false;
+        try{
+            insert le;
+        }catch(Exception ex){
+             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+        }
+
+        return le;
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public class DataLineBean {
+        //杞�熷崟鍙�
+        public String num{get;set;}
+        //杞�熶唬鐞嗗晢
+        public String ltc{get;set;}
+        // public String PDFflag {get; set;}
+        public boolean PDFflag{get; set;}
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        //public DataLineBean(Integer in_no, loaner_application_detail__c in_lad,String in_PDFflag) {
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad,boolean in_PDFflag,String in_ltc,String in_num) {
+            PDFflag = in_PDFflag;
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+            ltc = in_ltc;
+            num = in_num;
+        }
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+public PageReference sos() {
+    Integer i=1;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerLendDeliverController.cls-meta.xml b/scr/classes/LoanerLendDeliverController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerLendDeliverController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerLendDeliverControllerTest.cls b/scr/classes/LoanerLendDeliverControllerTest.cls
new file mode 100644
index 0000000..4941346
--- /dev/null
+++ b/scr/classes/LoanerLendDeliverControllerTest.cls
@@ -0,0 +1,240 @@
+@isTest
+private class LoanerLendDeliverControllerTest {
+	
+
+	@isTest static void test_method_one() {
+      
+	OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+		
+        	List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'ANI'];
+        	    
+        	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+                
+        		// 鏂板缓澶囧搧鍊熷嚭鐢宠
+                loaner_application__c loaner = new loaner_application__c();
+                loaner.Name = 'TEST';
+                loaner.RecordTypeId = rectLo[0].id;
+                loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+                loaner.DEMO_PURPOSE__C = '鍩硅';
+        	loaner.Request_shipping_Date__c = Date.today();
+        	loaner.Request_return_Date__c = Date.today();
+        	loaner.Status__c = '宸插嚭搴撴寚绀�';
+                loaner.Return_Track_Company__c = 'Test';
+                loaner.Return_Trake_Staff__c = 'Test1';
+                loaner.pickup_time__c = Date.today();
+                loaner.Equipment_Type__c = 'ANI';
+                insert loaner;
+
+                // 鏂板缓 瀹㈡埛
+                Account acc = new Account();
+                acc.RecordTypeId = rectCo[0].Id;
+                acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+                acc.DivisionName__c = 'DivisionName__c';
+                acc.FacilityName__c = 'FacilityName__c';
+                acc.PostCode__c='000000';
+                insert acc;
+                 
+                // 鏂板缓 璧勪骇
+                List<Asset> In_asset = new List<Asset>();
+
+                Asset asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�1';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�2';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�3';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                insert In_asset;
+
+                // 鏂板缓 鍊熷嚭鏄庣粏
+                List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+                loaner_application_detail__c detail = new loaner_application_detail__c();
+
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[0].id;
+                detail.name = '000';
+                detail.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[1].id;
+                detail.name = '111';
+                detail.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+        	detail.Shipment_Request_Date__c = Date.today();
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[2].id;
+                detail.name = '222';
+                detail.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                In_detail.add(detail);
+
+                insert In_detail;
+                loaner_application_detail__c detail1 = new loaner_application_detail__c();
+                detail1 = new loaner_application_detail__c();
+                detail1.loaner_application__c = loaner.Id;
+                detail1.loaner__c = In_asset[2].id;
+                detail1.name = '222';
+                detail1.RAESD_Status__c = '宸叉壒鍑�';
+                detail1.LendPrimary_Name__c = detail.Id;
+                insert detail1;
+                PageReference page = new PageReference('/apex/LoanerLendDeliver?step=LoanerLend&id=' + loaner.Id );
+                System.Test.setCurrentPage(page);
+                LoanerLendDeliverController  controller = new LoanerLendDeliverController();
+
+                controller.init();
+                controller.dataLines[0].checkFlag = true;
+                controller.dataLines[0].PDFflag = true;
+                controller.saveBtn();
+	}
+
+        @isTest static void test_method_two() {
+      
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+                
+                List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'ANI'];
+                    
+                List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+                
+                        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+                loaner_application__c loaner = new loaner_application__c();
+                loaner.Name = 'TEST';
+                loaner.RecordTypeId = rectLo[0].id;
+                loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+                loaner.DEMO_PURPOSE__C = '鍩硅';
+                loaner.Request_shipping_Date__c = Date.today();
+                loaner.Request_return_Date__c = Date.today();
+                loaner.Status__c = '宸插嚭搴撴寚绀�';
+                loaner.Return_Track_Company__c = 'Test';
+                loaner.Return_Trake_Staff__c = 'Test1';
+                //loaner.pickup_time__c = Date.today();
+                loaner.Equipment_Type__c = 'ANI';
+                insert loaner;
+
+                // 鏂板缓 瀹㈡埛
+                Account acc = new Account();
+                acc.RecordTypeId = rectCo[0].Id;
+                acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+                acc.DivisionName__c = 'DivisionName__c';
+                acc.FacilityName__c = 'FacilityName__c';
+                acc.PostCode__c='000000';
+                insert acc;
+                 
+                // 鏂板缓 璧勪骇
+                List<Asset> In_asset = new List<Asset>();
+
+                Asset asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�1';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�2';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�3';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                insert In_asset;
+
+                // 鏂板缓 鍊熷嚭鏄庣粏
+                List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+                loaner_application_detail__c detail = new loaner_application_detail__c();
+
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[0].id;
+                detail.name = '000';
+                detail.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[1].id;
+                detail.name = '111';
+                detail.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                detail.Shipment_Request_Date__c = Date.today();
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[2].id;
+                detail.name = '222';
+                detail.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                In_detail.add(detail);
+
+                insert In_detail;
+                loaner_application_detail__c detail1 = new loaner_application_detail__c();
+                detail1 = new loaner_application_detail__c();
+                detail1.loaner_application__c = loaner.Id;
+                detail1.loaner__c = In_asset[2].id;
+                detail1.name = '222';
+                detail1.RAESD_Status__c = '宸叉壒鍑�';
+                detail1.LendPrimary_Name__c = detail.Id;
+                insert detail1;
+                PageReference page = new PageReference('/apex/LoanerLendDeliver?step=LoanerLend&id=' + loaner.Id );
+                System.Test.setCurrentPage(page);
+                LoanerLendDeliverController  controller = new LoanerLendDeliverController();
+
+                controller.init();
+                controller.dataLines[0].checkFlag = true;
+                controller.dataLines[0].PDFflag = true;
+                controller.saveBtn();
+                controller.sos();
+        }
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerLendDeliverControllerTest.cls-meta.xml b/scr/classes/LoanerLendDeliverControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerLendDeliverControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerOrderState.cls b/scr/classes/LoanerOrderState.cls
new file mode 100644
index 0000000..e6826d3
--- /dev/null
+++ b/scr/classes/LoanerOrderState.cls
@@ -0,0 +1,145 @@
+public without sharing class LoanerOrderState {
+
+	public static String getOrderStater(String laId){
+
+		Integer ngNum = [select count() from loaner_application_detail__c where loaner_application__c = :laId and Receipt_Status__c = 'NG' and Asset_Return_Date__c != null ];
+		loaner_application__c la = [select id,Count_ApplicantReceived__c,Count_Received__c,Count_NG_SendBack__c,Detail_count__c,Count_NG__c from loaner_application__c where id = :laId];
+		if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '宸叉壒鍑�'] > 0){
+			return '宸叉壒鍑�';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '宸插嚭搴撴寚绀�'] > 0){
+			return '宸插嚭搴撴寚绀�';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '宸蹭笅鏋�'] > 0){
+			return '宸蹭笅鏋�';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�'] > 0 
+			&& [select count() from loaner_application_detail__c where loaner_application__c = :laId and Shipment_Request_Date__c != null] ==  0){
+			return '鍑哄簱鍓嶅凡妫�娴�';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�'] > 0 
+			&& [select count() from loaner_application_detail__c where loaner_application__c = :laId and Shipment_Request_Date__c != null] > 0){
+			return '閮ㄥ垎鍙戣揣';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '宸插嚭搴�'] > 0 
+			&& [select count() from loaner_application_detail__c where loaner_application__c = :laId and Asset_Return_Date__c != null] == ngNum){
+			return '鍏ㄩ儴鍙戣揣';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣'] > 0 
+			&& [select count() from loaner_application_detail__c where loaner_application__c = :laId and Asset_Return_Date__c != null] == ngNum){
+			return '鐢宠鑰呭凡鏀惰揣';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭'] > 0 
+			&& [select count() from loaner_application_detail__c where loaner_application__c = :laId and Asset_Return_Date__c != null] == ngNum){
+			return '鐢宠鑰呭凡瑁呮満纭';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c in ('鐢宠鑰呭凡瑁呮満纭','鐢宠鑰呮敹璐G','宸插嚭搴�','鐢宠鑰呭凡鏀惰揣')] > 0 
+			&& [select count() from loaner_application_detail__c where loaner_application__c = :laId and Asset_Return_Date__c != null] > 0){
+			return '閮ㄥ垎鍥炲瘎';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '宸插洖瀵�'] > 0){
+			return '鍏ㄩ儴鍥炲瘎';
+		}else if([select count() from loaner_application_detail__c where loaner_application__c = :laId and RAESD_Status__c = '娆犲搧涓�'] > 0){
+			return '娆犲搧纭涓�';
+		}else{
+			system.debug(la);
+			system.debug(ngNum);
+			if(la.Detail_count__c == la.Count_NG__c){
+				if(la.Count_Received__c == la.Detail_count__c){
+
+				}else if(la.Count_NG_SendBack__c == la.Detail_count__c){
+					return '鍏ㄩ儴鍥炲瘎';
+				}else if(la.Count_ApplicantReceived__c == la.Detail_count__c && la.Count_NG_SendBack__c > 0){
+					return '閮ㄥ垎鍥炲瘎';
+				}else {
+					return '鐢宠鑰呭凡鏀惰揣';
+				}
+			}
+			return '鍏ㄩ儴鍥炴敹';
+		}
+	}
+
+	public static Map<String ,String> getOrderStater1(List<String> laIdList){
+		Map<String,List<loaner_application_detail__c>> laDatailMap = new Map<String,List<loaner_application_detail__c>>();
+		Map<String,String> laStatuMap = new Map<String,String>();
+		
+		List<loaner_application_detail__c> allLadList = [select id,loaner_application__c,RAESD_Status__c,Shipment_Request_Date__c,Asset_Return_Date__c,Receipt_Status__c from loaner_application_detail__c where loaner_application__c = :laIdList];
+
+		for(String laId : laIdList){
+			List<loaner_application_detail__c> ladList = new List<loaner_application_detail__c>();
+			for(loaner_application_detail__c lad : allLadList){
+				if(lad.loaner_application__c == laId){
+					ladList.add(lad);
+				}
+			}
+			laDatailMap.put(laId, ladList);
+		}
+
+		for(String laId : laIdList){
+			List<loaner_application_detail__c> ladList = laDatailMap.get(laId);
+			Integer returnNgNum = 0;	//鏀惰揣ng涓斿洖瀵�
+			Integer requestDateNum = 0;	//鍑哄簱鏃ユ湡
+			Integer returnDateNum = 0;	//鍥炲瘎鏃ユ湡
+
+			Integer indicateNum = 0;	//鍑哄簱鎸囩ず
+			Integer stockDownNum = 0; 	//涓嬫灦
+			Integer inspectionNum = 0;	//涓嬫灦妫�鏌�
+			Integer shipmentNum = 0;	//鍑哄簱
+			Integer receiptNum = 0;		//鏀惰揣
+			Integer receiptNgNum =0; 	//鏀惰揣Ng 
+			Integer confirmNum = 0;		//瑁呮満纭
+			Integer returnNum = 0;		//鍥炲瘎
+			Integer lostNum = 0;		//娆犲搧
+
+			for(loaner_application_detail__c lad : ladList){
+				if(lad.RAESD_Status__c == '宸插嚭搴撴寚绀�'){
+					indicateNum++;
+				}else if(lad.RAESD_Status__c == '宸蹭笅鏋�'){
+					stockDownNum++;
+				}else if(lad.RAESD_Status__c == '鍑哄簱鍓嶅凡妫�娴�'){
+					inspectionNum++;
+				}else if(lad.RAESD_Status__c == '宸插嚭搴�'){
+					shipmentNum++;
+				}else if(lad.RAESD_Status__c == '鐢宠鑰呭凡鏀惰揣'){
+					receiptNum++;
+				}else if(lad.RAESD_Status__c == '鐢宠鑰呮敹璐G'){
+					receiptNgNum++;
+				}else if(lad.RAESD_Status__c == '鐢宠鑰呭凡瑁呮満纭'){
+					confirmNum++;
+				}else if(lad.RAESD_Status__c == '宸插洖瀵�'){
+					returnNum++;
+				}else if(lad.RAESD_Status__c == '娆犲搧涓�'){
+					lostNum++;
+				}
+
+				if(lad.Shipment_Request_Date__c != null ){
+					requestDateNum++;
+				}
+
+				if(lad.Asset_Return_Date__c != null ){
+					returnDateNum++;
+					if(lad.Receipt_Status__c == 'NG'){
+						returnNgNum++;
+					}
+				}
+			}
+			if(indicateNum> 0){
+				laStatuMap.put(laId,'宸插嚭搴撴寚绀�');
+			}else if(stockDownNum > 0){
+				laStatuMap.put(laId, '宸蹭笅鏋�');
+			}else if(inspectionNum > 0 && requestDateNum ==  0){
+				laStatuMap.put(laId, '鍑哄簱鍓嶅凡妫�娴�') ;
+			}else if(inspectionNum > 0 && requestDateNum > 0){
+				laStatuMap.put(laId, '閮ㄥ垎鍙戣揣');
+			}else if(shipmentNum > 0 && returnDateNum == returnNgNum){
+				laStatuMap.put(laId, '鍏ㄩ儴鍙戣揣');
+			}else if(receiptNum > 0 && returnDateNum == returnNgNum){
+				laStatuMap.put(laId, '鐢宠鑰呭凡鏀惰揣');
+			}else if(confirmNum > 0 && returnDateNum == returnNgNum){
+				laStatuMap.put(laId, '鐢宠鑰呭凡瑁呮満纭');
+			}else if((confirmNum+receiptNgNum+shipmentNum+receiptNum) > 0 && returnDateNum > 0){
+				laStatuMap.put(laId, '閮ㄥ垎鍥炲瘎');
+			}else if(returnNum > 0){
+				laStatuMap.put(laId, '鍏ㄩ儴鍥炲瘎');
+			}else if(lostNum > 0){
+				laStatuMap.put(laId, '娆犲搧纭涓�');
+			}else{
+				laStatuMap.put(laId, '鍏ㄩ儴鍥炴敹');
+			}
+
+		}
+		system.debug(laStatuMap);
+		return laStatuMap;
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerOrderState.cls-meta.xml b/scr/classes/LoanerOrderState.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerOrderState.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerOrderStateTest.cls b/scr/classes/LoanerOrderStateTest.cls
new file mode 100644
index 0000000..4e26dd5
--- /dev/null
+++ b/scr/classes/LoanerOrderStateTest.cls
@@ -0,0 +1,325 @@
+@isTest
+private class LoanerOrderStateTest {
+	static void setupTestData() {
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+    }
+	@isTest static void test_method_one() {
+        setupTestData();
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸叉壒鍑�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+         
+        // 鏂板缓 璧勪骇
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸叉壒鍑�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸叉壒鍑�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '宸叉壒鍑�';
+        detail.Inspection_result_after__c = 'OK';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+        In_detail[0].RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        In_detail[1].RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        In_detail[2].RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        update In_detail;
+        loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+        In_detail[0].RAESD_STATUS__C = '宸蹭笅鏋�';
+        In_detail[1].RAESD_STATUS__C = '宸蹭笅鏋�';
+        In_detail[2].RAESD_STATUS__C = '宸蹭笅鏋�';
+        update In_detail;
+		loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+		In_detail[0].RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        In_detail[1].RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        In_detail[2].RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        update In_detail;
+		loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+        
+        
+		In_detail[0].RAESD_STATUS__C = '宸插嚭搴�';
+        In_detail[1].RAESD_STATUS__C = '宸插嚭搴�';
+        In_detail[2].RAESD_STATUS__C = '宸插嚭搴�';
+        update In_detail;
+		loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+		In_detail[0].RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        In_detail[1].RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        In_detail[2].RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        update In_detail;
+		loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+		system.debug('213123'+loaner.Status__c);
+        Test.startTest();
+
+		In_detail[0].RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        In_detail[1].RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        In_detail[2].RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        update In_detail;
+		loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+		In_detail[0].RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail[1].RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail[2].RAESD_STATUS__C = '宸插洖瀵�';
+        update In_detail;
+		loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+		In_detail[0].RAESD_STATUS__C = '娆犲搧涓�';
+        In_detail[1].RAESD_STATUS__C = '娆犲搧涓�';
+        In_detail[2].RAESD_STATUS__C = '娆犲搧涓�';
+        update In_detail;
+        Test.stopTest();
+		//loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+		//In_detail[0].RAESD_STATUS__C = '宸插洖鏀�';
+  //      In_detail[1].RAESD_STATUS__C = '宸插洖鏀�';
+  //      In_detail[2].RAESD_STATUS__C = '宸插洖鏀�';
+  //      update In_detail;
+		//loaner.Status__c = LoanerOrderState.getOrderStater(loaner.Id);
+
+
+
+
+
+	}
+	
+	@isTest static void test_method_two() {
+        setupTestData();
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸叉壒鍑�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+         
+        // 鏂板缓 璧勪骇
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸叉壒鍑�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸叉壒鍑�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '宸叉壒鍑�';
+        detail.Inspection_result_after__c = 'OK';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        List<String> loanerId = new List<String>();
+        loanerId.add(loaner.Id);
+        Map<String,String> statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+
+        In_detail[0].RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        In_detail[1].RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        In_detail[2].RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+
+        In_detail[0].RAESD_STATUS__C = '宸蹭笅鏋�';
+        In_detail[1].RAESD_STATUS__C = '宸蹭笅鏋�';
+        In_detail[2].RAESD_STATUS__C = '宸蹭笅鏋�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+
+        In_detail[0].RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        In_detail[1].RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        In_detail[2].RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+
+        In_detail[0].RAESD_STATUS__C = '宸插嚭搴�';
+        In_detail[1].RAESD_STATUS__C = '宸插嚭搴�';
+        In_detail[2].RAESD_STATUS__C = '宸插嚭搴�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+
+        In_detail[0].RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        In_detail[1].RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        In_detail[2].RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail[2].Asset_Return_Date__c = Date.today();
+        In_detail[2].Receipt_Status__c  = 'NG';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+
+        In_detail[0].RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        In_detail[1].RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        In_detail[2].RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug('===='+loaner.Status__c);
+
+        In_detail[0].RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail[1].RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail[2].RAESD_STATUS__C = '宸插洖瀵�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+         In_detail[0].RAESD_STATUS__C = '娆犲搧涓�';
+        In_detail[1].RAESD_STATUS__C = '娆犲搧涓�';
+        In_detail[2].RAESD_STATUS__C = '娆犲搧涓�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+         In_detail[0].RAESD_STATUS__C = '宸插洖鏀�';
+        In_detail[1].RAESD_STATUS__C = '宸插洖鏀�';
+        In_detail[2].RAESD_STATUS__C = '宸插洖鏀�';
+        update In_detail;
+        statu =LoanerOrderState.getOrderStater1(loanerId);
+        loaner.Status__c =statu.get(loaner.Id);
+        system.debug(loaner.Status__c);
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerOrderStateTest.cls-meta.xml b/scr/classes/LoanerOrderStateTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerOrderStateTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerPortionDeliverController.cls b/scr/classes/LoanerPortionDeliverController.cls
new file mode 100644
index 0000000..4ffa39f
--- /dev/null
+++ b/scr/classes/LoanerPortionDeliverController.cls
@@ -0,0 +1,402 @@
+public without sharing class LoanerPortionDeliverController {
+     // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c lac {get;private set;}
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerPortionDeliverController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,pickup_time__c,delivery_company__c,Return_to_wh_staff__c,Tracking_Number__c,Status__c,Agent__r.Name,Agent__c,Rental_Start_Date__c,Rental_End_Date__c,Equipment_Type__c,Owner.Name from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        System.debug(la.Owner.Name);
+        lac = new loaner_application__c();
+        lac.delivery_company__c = la.delivery_company__c;
+        lac.Tracking_Number__c = la.Tracking_Number__c;
+        if(la.Return_to_wh_staff__c != null){
+            lac.Return_to_wh_staff__c = la.Return_to_wh_staff__c;
+        }else{
+            lac.Return_to_wh_staff__c = UserInfo.getUserId();
+        }
+       
+
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c,LOANER__c,LOANER__r.RecordType.Id,LOANER__r.Name,LOANER__r.Remarks2__c ';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'LPortionDeliver') {
+            sql_where += ' and RAESD_Status__c = \'鍑哄簱鍓嶅凡妫�娴媆'';
+        } else {
+            return null;
+        }
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+        
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }      
+        return null;
+    }
+
+     public PageReference saveBtn() {
+             // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        List<Asset> assList = new List<Asset>();
+       
+        if(dataLines.size() >0){
+            Loaner_Express__c le = this.createExpress();
+            Integer count = 0;
+            for (DataLineBean dataLine : dataLines) {   
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    Asset loa = new Asset(id = lad.LOANER__c);
+                    if(la.pickup_time__c == null){
+                        if(lac.delivery_company__c == null || lac.delivery_company__c == ''){
+                            delete le;
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欑墿娴佸叕鍙�'));
+                            return null;
+                        }
+                        if(lac.Return_to_wh_staff__c == null ){
+                            delete le;
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欏彂璐т汉'));
+                            return null;
+                        }
+                        lad.Shipment_Request_Date__c = Date.today();
+                        lad.outTime__c = Datetime.now();
+                        lad.RAESD_Status__c = '宸插嚭搴�';
+                        //濡傛灉鏄釜浣撶鐞�,鍒欐敼鍙樻牱鏈虹姸鎬�
+                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                            loa.status = '鍑哄��';
+                            if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
+                                loa.Loaner__c = la.Owner.Name;
+                                loa.Rental_Customer__c = la.Agent__c;
+                                loa.Rental_Start_Date__c = la.Rental_Start_Date__c;
+                                loa.Rental_end_Date__c = la.Rental_end_Date__c;
+                            }
+                        }        
+                        lad.Loaner_Express__c = le.id;    
+                        lad.Return_to_wh_staff__c = lac.Return_to_wh_staff__c;
+                        lad.delivery_company__c = lac.delivery_company__c;
+                        lad.Tracking_Number__c = lac.Tracking_Number__c;
+                        updList.add(lad);
+                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                            assList.add(loa);
+                        }
+                        count++;
+                    }else{
+                        lad.Shipment_Request_Date__c = Date.today();
+                        lad.outTime__c = Datetime.now();
+                        lad.Receipt_Date__c = Date.today();
+                        lad.Receipt_Status__c = 'OK';
+                        lad.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                        //濡傛灉鏄釜浣撶鐞�,鍒欐敼鍙樻牱鏈虹姸鎬�
+                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                            loa.status = '鍑哄��';
+                            if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
+                                loa.Loaner__c = la.Owner.Name;
+                                loa.Rental_Customer__c = la.Agent__c;
+                                loa.Rental_Start_Date__c = la.Rental_Start_Date__c;
+                                loa.Rental_end_Date__c = la.Rental_end_Date__c;
+                            }
+                        }
+                        updList.add(lad); 
+                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                            assList.add(loa);
+                        }       
+                    }
+                }
+            }
+            if(la.pickup_time__c == null){
+                le.Consignor_LogisticsNumber__c = lac.Tracking_Number__c;
+                le.Consignor_LogisticsCompany__c = lac.delivery_company__c;
+                le.consignor__c =lac.Return_to_wh_staff__c;
+                le.Shipment_Request_Date__c = Date.today();       
+                le.NotReceivingNum__c = count;
+            }else{
+                delete le;
+            }
+
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                    if(la.pickup_time__c == null){
+                        update le;
+                    }
+                    update updList;
+                    update assList;
+                    if(la.Status__c != '瀹屾瘯'){
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        if(la.Status__c == '鍏ㄩ儴鍙戣揣')  la.Shipping_Finished_Date_All__c = Date.today();
+                        la.Shipping_Finished_Date__c = Date.today();
+                        update la;
+                    }
+                }else{
+                    delete le;
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨鍑哄簱鐨勬牱鏈�'));
+                    return null;
+                }
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                delete le;
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+        }
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public Loaner_Express__c createExpress(){
+        Date temp = Date.today();
+        Loaner_Express__c le = new Loaner_Express__c();
+        le.loaner_application__c = laId;
+        le.Name = temp.day()+ '鏃ュ彂璐х墿娴佸崟';
+        try{
+            insert le;
+        }catch(Exception ex){
+             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+        }
+
+        return le;
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+
+   
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+   public PageReference sos(){
+        Integer i=0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        return null;
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerPortionDeliverController.cls-meta.xml b/scr/classes/LoanerPortionDeliverController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerPortionDeliverController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerPortionDeliverControllerTest.cls b/scr/classes/LoanerPortionDeliverControllerTest.cls
new file mode 100644
index 0000000..6a1e93b
--- /dev/null
+++ b/scr/classes/LoanerPortionDeliverControllerTest.cls
@@ -0,0 +1,152 @@
+@isTest
+private class LoanerPortionDeliverControllerTest {
+	static void setupTestData() {
+                OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+                insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+            }
+	@isTest static void test_method_one() {
+        setupTestData();
+	List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+	    
+	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        //鐢ㄦ埛
+        User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'test@test.com';
+        user.Username = 'test111@test222.com';
+        user.CommunityNickname = 'test';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+
+	// 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+	loaner.Request_shipping_Date__c = Date.today();
+	loaner.Request_return_Date__c = Date.today();
+	loaner.Status__c = '宸插嚭搴撴寚绀�';
+	loaner.delivery_company__c = '鐗╂祦鍏徃';
+	loaner.Tracking_Number__c = '1234567';
+        insert loaner;
+
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+         
+        // 鏂板缓 璧勪骇
+        List<Asset> In_asset = new List<Asset>();
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '鍑哄簱鍓嶅凡妫�娴�';
+        detail.Return_to_wh_staff__c = user.id;
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+    
+        PageReference page = new PageReference('/apex/LoanerPortionDeliverController?Id=' + loaner.Id + '&step=LPortionDeliver');
+        System.Test.setCurrentPage(page);
+        LoanerPortionDeliverController  controller = new LoanerPortionDeliverController();
+
+        controller.init();
+        controller.cancelBtn();
+        controller.getDatalineSize();
+        controller.dataLines[0].checkFlag = true;
+        controller.saveBtn();
+        controller.sos();
+
+
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        // 鐗╂祦淇℃伅
+        List<Loaner_Express__c> leList = [select name, Consignor_LogisticsNumber__c, Consignor_LogisticsCompany__c, consignor__r.name, Shipment_Request_Date__c, NotReceivingNum__c from Loaner_Express__c];
+        //system.assertEquals('1234567', leList[0].Consignor_LogisticsNumber__c);
+        //system.assertEquals('鐗╂祦鍏徃', leList[0].Consignor_LogisticsCompany__c);
+        //system.assertEquals('test', leList[0].consignor__r.name);
+        //system.assertEquals(Date.today(), leList[0].Shipment_Request_Date__c);
+        //system.assertEquals(1, leList[0].NotReceivingNum__c);
+
+        List<loaner_application__c> laList = [select Return_to_wh_staff__c, Status__c, Shipping_Finished_Date_All__c, Shipping_Finished_Date__c from loaner_application__c];
+        //system.assertEquals('鍏ㄩ儴鍙戣揣', laList[0].Status__c);
+        //system.assertEquals(Date.today(), laList[0].Shipping_Finished_Date_All__c);
+        //system.assertEquals(Date.today(), laList[0].Shipping_Finished_Date__c);
+
+        List<loaner_application_detail__c> updList = [select RAESD_Status__c, Shipment_Request_Date__c, Return_to_wh_staff__c, delivery_company__c, Tracking_Number__c from loaner_application_detail__c order by name];
+        //system.assertEquals(Date.today(), updList[0].Shipment_Request_Date__c);
+        //system.assertEquals('宸插嚭搴�', updList[0].RAESD_Status__c);
+        //system.assertEquals(laList[0].Return_to_wh_staff__c, updList[0].Return_to_wh_staff__c);
+        //system.assertEquals('123', updList[0].Return_to_wh_staff__c);
+        //system.assertEquals('鐗╂祦鍏徃', updList[0].delivery_company__c);
+        //system.assertEquals('1234567', updList[0].Tracking_Number__c);
+
+        List<Asset> assList = [select status from Asset order by name];
+        //system.assertEquals('鍑哄��', assList[0].status);
+
+
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerPortionDeliverControllerTest.cls-meta.xml b/scr/classes/LoanerPortionDeliverControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerPortionDeliverControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerPortionReturnController.cls b/scr/classes/LoanerPortionReturnController.cls
new file mode 100644
index 0000000..dc45f15
--- /dev/null
+++ b/scr/classes/LoanerPortionReturnController.cls
@@ -0,0 +1,251 @@
+public without sharing class LoanerPortionReturnController {
+	 // 鍩虹Url
+    public String baseUrl { get; private set; }
+   // public Boolean isNDT {get;private set;}
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c lac {get; private set;}
+    public loaner_application__c la { get; private set; }
+    public boolean isOk {get; private set; }
+    public String step { get; private set; }
+
+    public String loanerType {get; private set; } 
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerPortionReturnController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,loaner_request_number__c,Return_Trake_Staff__c,Return_Track_Company__c,Return_Track_Number__c,Status__c,HP_Received_Sign_Date__c,RecordType.DeveloperName,loaner_manage_place__c,Equipment_Type__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        loanerType = la.Equipment_Type__c;
+        /*if(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI'){  
+            isNDT = true;
+        }else{
+            isNDT =false;
+        }*/
+        lac = new loaner_application__c();
+        lac.Return_Track_Company__c = la.Return_Track_Company__c;
+        lac.Return_Track_Number__c = la.Return_Track_Number__c;
+        lac.return_Number__c = '';
+        if(la.Return_Trake_Staff__c != null){
+            lac.Return_Trake_Staff__c = la.Return_Trake_Staff__c;
+        }else{
+            User temp = [select id,Name from User where id = :UserInfo.getUserId()];
+            lac.Return_Trake_Staff__c = temp.Name;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c,RAESD_Status__c,LOANER__r.Name,LOANER__r.Remarks2__c,LOANER__r.Description ';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'APortionDeliver') {
+            sql_where += ' and RAESD_Status__c in (\'鐢宠鑰呭凡瑁呮満纭\',\'鐢宠鑰呮敹璐G\',\'宸插嚭搴揬',\'鐢宠鑰呭凡鏀惰揣\')';
+        } else {
+            return null;
+        }
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+        
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+      
+        return null;
+    }
+
+     public PageReference saveBtn() {
+        // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        Boolean isOK = true;
+        List<loaner_application__c> lappList = [select id,AllLead_OrderName__c,Equipment_Type__c  from loaner_application__c where  Status__c = '宸叉壒鍑�'];
+        if(lappList.size() > 0){
+            for(loaner_application__c lapp : lappList){
+                if(lapp.AllLead_OrderName__c != null){
+                    if(lapp.AllLead_OrderName__c.contains(la.loaner_request_number__c) && lapp.Equipment_Type__c == 'BS'){
+                       ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '瀛樺湪宸叉壒鍑嗙殑杞�熺敵璇峰崟锛岃鐐瑰嚮 杞�熷彂璐�'));  
+                        return null;
+                    }
+                }
+            }
+        }
+            
+        
+        Integer count = 0;
+        if(dataLines.size() > 0 ){
+            Loaner_Express__c le = this.createExpress();
+            for (DataLineBean dataLine : dataLines) {	
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    if (step == 'APortionDeliver') {
+                        if( lac.Return_Track_Company__c == null || lac.Return_Track_Company__c =='' ){
+                            delete le;
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欑墿娴佸叕鍙�'));  
+                            return null;
+                        }
+                        if( lac.Return_Trake_Staff__c == null ){
+                            delete le;
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欒繑鍝佷汉'));  
+                            return null;
+                        }
+                        if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI'){
+
+                            if(lac.loaner_manage_place__c == null || lac.loaner_manage_place__c == ''){
+                                delete le;
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欐牱鏈虹鐞嗗湴'));  
+                                return null;
+                            }
+                            if(lac.return_Number__c == null || lac.return_Number__c == ''){
+                                delete le;
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欒繑鍝佷汉鐢佃瘽'));  
+                                return null;
+                            }
+
+
+                        }
+                        lad.Return_Express__c = le.id;
+                        lad.Asset_Return_Date__c = Date.today();
+                        lad.RAESD_Status__c = '宸插洖瀵�';
+                        lad.Return_Track_Company__c = lac.Return_Track_Company__c;
+                        lad.Return_Track_Number__c = lac.Return_Track_Number__c;
+                        lad.Return_Trake_Staff__c = lac.Return_Trake_Staff__c;
+                        lad.loaner_manage_place__c = lac.loaner_manage_place__c;
+                        lad.return_Number__c = lac.return_Number__c;
+                        //lad.inTime__c = Datetime.now();
+                        count++;
+                    }
+
+                    updList.add(lad);
+
+                }
+            }
+
+            le.Asset_Return_Date__c = Date.today();
+            le.Return_LogisticsCompany__c =lac.Return_Track_Company__c;
+            le.Return_LogisticsNumber__c = lac.Return_Track_Number__c;
+            le.Return_Sender__c = lac.Return_Trake_Staff__c;
+            le.return_Number__c = lac.return_Number__c;
+            le.NotReceivingNum__c = count;
+
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                	update updList;
+                    update le;
+                    if(la.Status__c != '瀹屾瘯'){
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        if(la.Status__c == '鍏ㄩ儴鍥炲瘎') la.Asset_Return_Date_All__c = Date.today();
+                        la.Asset_Return_Date__c = Date.today();
+                	   update la;
+                    }
+                }else{
+                    delete le;
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨闇�瑕佸洖瀵勭殑鏍锋満'));
+                    return null;
+                }
+               
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                delete le;
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+        }
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public Loaner_Express__c createExpress(){
+        Date temp = Date.today();
+        Loaner_Express__c le = new Loaner_Express__c();
+        le.loaner_application__c = laId;
+        le.IsDeliveryLogistics__c = false;
+        le.Name = temp.day()+ '鏃ュ洖瀵勭墿娴佸崟';
+        try{
+            insert le;
+        }catch(Exception ex){
+             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+        }
+
+        return le;
+    }
+    public Pagereference getIsOk(){
+        isOk = false;
+        if(la.RecordType.DeveloperName == 'RVI' || la.RecordType.DeveloperName == 'NDT' || la.RecordType.DeveloperName == 'ANI'){
+            return null;
+        }
+        if(dataLines.size() > 0 ){
+            for (DataLineBean dataLine : dataLines) {   
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    if(lad.RAESD_Status__c == '鐢宠鑰呭凡鏀惰揣' || lad.RAESD_Status__c == '宸插嚭搴�'){
+                        isOk = true;
+                        break;
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
+    
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+          	lad = in_lad;      	 
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerPortionReturnController.cls-meta.xml b/scr/classes/LoanerPortionReturnController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerPortionReturnController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerPortionReturnControllerTest.cls b/scr/classes/LoanerPortionReturnControllerTest.cls
new file mode 100644
index 0000000..632434f
--- /dev/null
+++ b/scr/classes/LoanerPortionReturnControllerTest.cls
@@ -0,0 +1,131 @@
+@isTest
+private class LoanerPortionReturnControllerTest {
+	static void setupTestData() {
+                OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+                insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+            }
+	@isTest static void test_method_one() {
+                setupTestData();
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+	    
+		List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+		// 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+		//loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+         
+        // 鏂板缓 璧勪骇
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '鐢宠鑰呭凡瑁呮満纭';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '鐢宠鑰呭凡鏀惰揣';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        //
+        PageReference page = new PageReference('/apex/LoanerPortionReturnController?Id=' + loaner.Id + '&step=APortionDeliver');
+        System.Test.setCurrentPage(page);
+        LoanerPortionReturnController  controller = new LoanerPortionReturnController();
+
+
+        controller.init();
+        
+        controller.dataLines[0].checkFlag = true;
+        controller.dataLines[0].lad.Receipt_Status__c = 'NG';
+        controller.dataLines[0].lad.ReceiptRemark__c = '澶囨敞';
+        
+        controller.dataLines[1].checkFlag = true;
+        controller.dataLines[1].lad.Receipt_Status__c = 'OK';
+
+		controller.getIsOk();
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.cancelBtn();
+        controller.getDatalineSize();
+
+        //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+        List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+        system.assertEquals('宸插洖瀵�', updList[0].RAESD_Status__c);
+        system.assertEquals('宸插洖瀵�', updList[1].RAESD_Status__c);
+
+
+        List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+        system.assertEquals('鍏ㄩ儴鍥炲瘎', laList[0].Status__c);
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerPortionReturnControllerTest.cls-meta.xml b/scr/classes/LoanerPortionReturnControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerPortionReturnControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerReceiveGoodsController.cls b/scr/classes/LoanerReceiveGoodsController.cls
new file mode 100644
index 0000000..40ea390
--- /dev/null
+++ b/scr/classes/LoanerReceiveGoodsController.cls
@@ -0,0 +1,152 @@
+public without sharing class LoanerReceiveGoodsController {
+ // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerReceiveGoodsController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id,ReceiptRemark__c, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c , Inspection_result__c,Receipt_Status__c,LOANER__r.Name,LOANER__r.Remarks2__c';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'ApplicantReceive') {
+            sql_where += ' and RAESD_Status__c = \'宸插嚭搴揬'';
+        } else {
+            return null;
+        }
+
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+  		
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+
+        return null;
+    }
+
+ public PageReference saveBtn() {
+        // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        if(dataLines.size() > 0){
+            for (DataLineBean dataLine : dataLines) {
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    if (step == 'ApplicantReceive') {
+
+                        if('NG' == dataLine.lad.Receipt_Status__c){
+                            if(lad.ReceiptRemark__c == null || lad.ReceiptRemark__c == ''){
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐欐敹璐G澶囨敞'));
+                                return null;
+                            }
+                        	lad.RAESD_Status__c = '鐢宠鑰呮敹璐G';
+                        }else if('OK' == dataLine.lad.Receipt_Status__c){
+                        	lad.RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣';
+                        }else{
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨鏀惰揣鐘舵��'));
+                            return null;
+                        }
+                        lad.Receipt_Status__c = dataLine.lad.Receipt_Status__c;
+                        lad.Receipt_Date__c = Date.today();
+                    }
+                    updList.add(lad);
+
+                }
+            }
+           
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                	update updList;
+                    if(la.Status__c != '瀹屾瘯'){
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        update la;
+                    }
+                }else{
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨闇�瑕佹敹璐х殑鏍锋満'));
+                    return null;
+                }
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+		}
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+}
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+        return null;
+    }
+
+     public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+    
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerReceiveGoodsController.cls-meta.xml b/scr/classes/LoanerReceiveGoodsController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerReceiveGoodsController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerReceiveGoodsControllerTest.cls b/scr/classes/LoanerReceiveGoodsControllerTest.cls
new file mode 100644
index 0000000..2d29a68
--- /dev/null
+++ b/scr/classes/LoanerReceiveGoodsControllerTest.cls
@@ -0,0 +1,127 @@
+@isTest
+private class LoanerReceiveGoodsControllerTest {
+	static void setupTestData() {
+                OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+                insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+            }
+	@isTest static void test_method_one() {
+                setupTestData();
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+	    
+		List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+		// 鏂板缓澶囧搧鍊熷嚭鐢宠
+                loaner_application__c loaner = new loaner_application__c();
+                loaner.Name = 'TEST';
+                loaner.RecordTypeId = rectLo[0].id;
+                loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+                loaner.DEMO_PURPOSE__C = '婕旂ず';
+	        loaner.Request_shipping_Date__c = Date.today();
+	        loaner.Request_return_Date__c = Date.today();
+		loaner.Status__c = '宸插嚭搴撴寚绀�';
+                insert loaner;
+
+                // 鏂板缓 瀹㈡埛
+                Account acc = new Account();
+                acc.RecordTypeId = rectCo[0].Id;
+                acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+                acc.DivisionName__c = 'DivisionName__c';
+                acc.FacilityName__c = 'FacilityName__c';
+                acc.PostCode__c='000000';
+                insert acc;
+         
+                // 鏂板缓 璧勪骇
+                List<Asset> In_asset = new List<Asset>();
+
+                Asset asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�1';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�2';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�3';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                insert In_asset;
+
+                // 鏂板缓 鍊熷嚭鏄庣粏
+                List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+                loaner_application_detail__c detail = new loaner_application_detail__c();
+
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[0].id;
+                detail.name = '000';
+                detail.RAESD_STATUS__C = '宸插嚭搴�';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[1].id;
+                detail.name = '111';
+                detail.RAESD_STATUS__C = '宸插嚭搴�';
+                In_detail.add(detail);
+
+                insert In_detail;
+
+                //
+                PageReference page = new PageReference('/apex/LoanerReceiveGoodsController?Id=' + loaner.Id + '&step=ApplicantReceive');
+                System.Test.setCurrentPage(page);
+                LoanerReceiveGoodsController  controller = new LoanerReceiveGoodsController();
+
+                controller.init();
+
+                controller.dataLines[0].checkFlag = true;
+                controller.dataLines[0].lad.Receipt_Status__c = 'NG';
+                controller.dataLines[0].lad.ReceiptRemark__c = '澶囨敞';
+                
+                controller.dataLines[1].checkFlag = true;
+                controller.dataLines[1].lad.Receipt_Status__c = 'OK';
+
+                controller.saveBtn();
+                //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+                controller.cancelBtn();
+                controller.getDatalineSize();
+
+                //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+                List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+                system.assertEquals('鐢宠鑰呮敹璐G', updList[0].RAESD_Status__c);
+                system.assertEquals('鐢宠鑰呭凡鏀惰揣', updList[1].RAESD_Status__c);
+
+
+                List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+                system.assertEquals('鐢宠鑰呭凡鏀惰揣', laList[0].Status__c);
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerReceiveGoodsControllerTest.cls-meta.xml b/scr/classes/LoanerReceiveGoodsControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerReceiveGoodsControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerStockDownCheckController.cls b/scr/classes/LoanerStockDownCheckController.cls
new file mode 100644
index 0000000..f0b9daa
--- /dev/null
+++ b/scr/classes/LoanerStockDownCheckController.cls
@@ -0,0 +1,171 @@
+public without sharing class LoanerStockDownCheckController {
+ // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerStockDownCheckController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+    public PageReference init() {
+
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id,StockDownRemark__c, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c , Inspection_result__c,LOANER__c,LOANER__r.RecordType.Id,LOANER__r.Name,LOANER__r.Remarks2__c';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'StockDownCheck') {
+            sql_where += ' and RAESD_Status__c in (\'宸蹭笅鏋禱',\'宸插嚭搴撴寚绀篭')';
+        } else {
+            return null;
+        }
+
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+  		
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+
+        return null;
+    }
+
+ public PageReference saveBtn() {
+       // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        List<Asset> assList = new List<Asset>();
+        if(dataLines.size() > 0){
+            for (DataLineBean dataLine : dataLines) {
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    Asset loa = new Asset(id = lad.LOANER__c);
+                    lad.StockDown__c = true;
+                    lad.StockDown_Date__c = Date.today();
+                    if (step == 'StockDownCheck') {
+                        lad.Inspection_result__c = dataLine.lad.Inspection_result__c;
+                        lad.Pre_inspection_Date__c = Date.today();
+                        if('NG-淇悊' == dataLine.lad.Inspection_result__c){
+                            if(lad.StockDownRemark__c == null || lad.StockDownRemark__c == ''){
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐橬G-淇悊澶囨敞'));
+                                return null;
+                            }
+                            lad.RAESD_Status__c = '寰呬慨鐞�';
+                            //濡傛灉鏄釜浣撶鐞�,鍒欐敼鍙樻牱鏈虹姸鎬�
+                            if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                                loa.status = '寰呬慨鐞�';
+                            }
+                        }else if('NG-搴熷純' == dataLine.lad.Inspection_result__c){
+                            if(lad.StockDownRemark__c == null || lad.StockDownRemark__c == ''){
+                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇峰~鍐橬G-搴熷純澶囨敞'));
+                                return null;
+                            }
+                            lad.RAESD_Status__c = '寰呭簾寮�';
+                            if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                                loa.status = '寰呭簾寮�';                            
+                            }
+                        }else if('OK' == dataLine.lad.Inspection_result__c){
+                            lad.RAESD_Status__c = '鍑哄簱鍓嶅凡妫�娴�';  
+                        }else{
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨涓嬫灦鐘舵��'));
+                            return null;
+                        }
+                    }
+                    updList.add(lad);
+                    if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
+                       assList.add(loa);
+                    }
+                }
+            }
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                    update updList;
+                    update assList;
+                    if(la.Status__c != '瀹屾瘯'){
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        update la;
+                    }
+                }else{
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鏈�夋嫨涓嬫灦妫�鏌ョ殑鏍锋満'));
+                    return null;
+                }
+               
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+        }
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+        return null;
+    }
+
+     public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerStockDownCheckController.cls-meta.xml b/scr/classes/LoanerStockDownCheckController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerStockDownCheckController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerStockDownCheckControllerTest.cls b/scr/classes/LoanerStockDownCheckControllerTest.cls
new file mode 100644
index 0000000..5054705
--- /dev/null
+++ b/scr/classes/LoanerStockDownCheckControllerTest.cls
@@ -0,0 +1,142 @@
+@isTest
+private class LoanerStockDownCheckControllerTest {
+	
+	@isTest static void test_method_one() {
+                OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+		
+        	List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        	    
+        	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+                
+        		// 鏂板缓澶囧搧鍊熷嚭鐢宠
+                loaner_application__c loaner = new loaner_application__c();
+                loaner.Name = 'TEST';
+                loaner.RecordTypeId = rectLo[0].id;
+                loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+                loaner.DEMO_PURPOSE__C = '婕旂ず';
+        	loaner.Request_shipping_Date__c = Date.today();
+        	loaner.Request_return_Date__c = Date.today();
+        	loaner.Status__c = '宸插嚭搴撴寚绀�';
+                insert loaner;
+
+                // 鏂板缓 瀹㈡埛
+                Account acc = new Account();
+                acc.RecordTypeId = rectCo[0].Id;
+                acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+                acc.DivisionName__c = 'DivisionName__c';
+                acc.FacilityName__c = 'FacilityName__c';
+                acc.PostCode__c='000000';
+                insert acc;
+                 
+                // 鏂板缓 璧勪骇
+                List<Asset> In_asset = new List<Asset>();
+
+                Asset asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�1';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�2';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�3';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                insert In_asset;
+
+                // 鏂板缓 鍊熷嚭鏄庣粏
+                List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+                loaner_application_detail__c detail = new loaner_application_detail__c();
+
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[0].id;
+                detail.name = '000';
+                detail.RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[1].id;
+                detail.name = '111';
+                detail.RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+        	detail.Shipment_Request_Date__c = Date.today();
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[2].id;
+                detail.name = '222';
+                detail.RAESD_STATUS__C = '宸插嚭搴撴寚绀�';
+                In_detail.add(detail);
+
+                insert In_detail;
+
+                //
+                PageReference page = new PageReference('/apex/LoanerStockDownCheckController?Id=' + loaner.Id + '&step=StockDownCheck');
+                System.Test.setCurrentPage(page);
+                LoanerStockDownCheckController  controller = new LoanerStockDownCheckController();
+
+                controller.init();
+
+                controller.dataLines[0].checkFlag = true;
+                controller.dataLines[0].lad.Inspection_result__c = 'NG-淇悊';
+                controller.dataLines[0].lad.StockDownRemark__c = '澶囨敞';
+
+                controller.dataLines[1].checkFlag = true;
+                controller.dataLines[1].lad.Inspection_result__c = 'OK';
+
+                controller.dataLines[2].checkFlag = true;
+                controller.dataLines[2].lad.Inspection_result__c = 'NG-搴熷純';
+                controller.dataLines[2].lad.StockDownRemark__c = '澶囨敞';
+
+                controller.saveBtn();
+                //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+                controller.cancelBtn();
+                controller.getDatalineSize();
+
+                //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+                List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+                system.assertEquals('寰呬慨鐞�', updList[0].RAESD_Status__c);
+                system.assertEquals('鍑哄簱鍓嶅凡妫�娴�', updList[1].RAESD_Status__c);
+                system.assertEquals('寰呭簾寮�', updList[2].RAESD_Status__c);
+
+                List<Asset> assList = [select status from Asset order by name];
+                system.assertEquals('寰呬慨鐞�', assList[0].status);
+                system.assertEquals('寰呭簾寮�', assList[2].status);
+
+                List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+                system.assertEquals('閮ㄥ垎鍙戣揣', laList[0].Status__c);
+
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerStockDownCheckControllerTest.cls-meta.xml b/scr/classes/LoanerStockDownCheckControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerStockDownCheckControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerTakeBackController.cls b/scr/classes/LoanerTakeBackController.cls
new file mode 100644
index 0000000..db1b087
--- /dev/null
+++ b/scr/classes/LoanerTakeBackController.cls
@@ -0,0 +1,166 @@
+public without sharing class LoanerTakeBackController {
+ // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏍锋満鍊熷嚭鐢宠ID
+    public String laId { get; private set; }
+    public loaner_application__c la { get; private set; }
+    /* 鐢婚潰姝ラ
+     * 涓嬫灦:StockDown
+     *
+     */
+    public String step { get; private set; }
+    // 鏄庣粏Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 鏄庣粏琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public LoanerTakeBackController() {
+        laId = System.currentPageReference().getParameters().get('id');
+        step = System.currentPageReference().getParameters().get('step');
+    }
+
+
+
+    public PageReference init() {
+
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 鏄庣粏Bean
+        dataLines = new List<DataLineBean>();
+
+        if (String.isBlank(laId) == true) {
+            return null;
+        }
+        if (String.isBlank(step) == true) {
+            return null;
+        }
+        // 鏍锋満鍊熷嚭鐢宠鍙栧緱
+        List<loaner_application__c> laList = [select Id,Status__c,Equipment_Type__c from loaner_application__c where Id = :laId];
+        if (laList.size() == 0) {
+            return null;
+        }
+        la = laList[0];
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏鍙栧緱
+        String sql_select = 'select Id,loaner_manage_place__c, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c , Check_lost_Item__c,LOANER__c,LOANER__r.RecordType.Id,LOANER__r.Name,LOANER__r.Remarks2__c';
+        String sql_where = ' where loaner_application__c = :laId ';
+        if (step == 'ReceivedLoaner') {
+            sql_where += ' and RAESD_Status__c = \'宸插洖瀵刓'';
+        } else {
+            return null;
+        }
+
+        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
+  		
+        List<loaner_application_detail__c> lads = Database.query(sql_full);
+        if (lads.size() == 0) {
+            return null;
+        }
+
+        // 鏄庣粏Bean浣滄垚
+        Integer cnt = 0;
+        for (loaner_application_detail__c lad : lads) {
+            cnt += 1;
+            DataLineBean dataLine = new DataLineBean(cnt, lad);
+            dataLines.add(dataLine);
+        }
+
+        return null;
+    }
+
+ public PageReference saveBtn() {
+        // 鏍规嵁step鏇存柊鏍锋満鍊熷嚭鐢宠鏄庣粏鐘舵��
+        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
+        List<Asset> assList = new List<Asset>();
+        if(dataLines.size() > 0){
+            for (DataLineBean dataLine : dataLines) {
+                if (dataLine.checkFlag == true) {
+                    loaner_application_detail__c lad = dataLine.lad;
+                    if (step == 'ReceivedLoaner') {
+                        lad.Check_lost_Item__c = dataLine.lad.Check_lost_Item__c;
+                        if('Ok' == dataLine.lad.Check_lost_Item__c){
+                        	lad.RAESD_Status__c = '宸插洖鏀�';
+                            lad.Received_loaner_Date__c = Date.today();
+                            lad.inTime__c = Datetime.now();
+                        }else if('娆犲搧' == dataLine.lad.Check_lost_Item__c){
+                        	lad.RAESD_Status__c = '娆犲搧涓�';
+                        }else if('娑堣��' == dataLine.lad.Check_lost_Item__c){
+                        	lad.RAESD_Status__c = '宸叉秷鑰�';
+                            lad.Consume_Date__c = Date.today();
+                            lad.Lost_item_check_Date__c = Date.today();
+                            lad.inTime__c = Datetime.now();
+                            if(lad.LOANER__r.RecordType.Id ==System.label.Asset_Record_Type1){
+                                Asset loa = new Asset(id = lad.LOANER__c);
+                                loa.status = '娑堣��';
+                                 assList.add(loa);
+                            }
+                        }else{
+                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨娆犲搧纭缁撴灉'));
+                            return null;
+                        }
+                    }
+                    updList.add(lad);
+                }
+            }
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (updList.size() > 0) {
+                	update updList;
+                	update assList;
+                    if(la.Status__c != '瀹屾瘯'){
+                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
+                        if(la.Status__c =='鍏ㄩ儴鍥炴敹'){
+                            la.LoanerClosedDateAll__c =Date.today();
+                            if (la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI') {
+                                PrototypeToThaw.UserUnfreeze(la.Id);
+                            }
+                        }
+                	   update la;
+                    }
+                }else{
+                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '璇烽�夋嫨鍥炴敹鐨勬牱鏈�'));
+                    return null;
+                }
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+            }
+		}
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+        return null;
+    }
+
+     public class DataLineBean {
+        // 鏄惁閫夋嫨
+        public boolean checkFlag { get; set; }
+        // 琛屽彿
+        public Integer lineNo { get; private set; }
+        // 鏍锋満鍊熷嚭鐢宠鏄庣粏
+        public loaner_application_detail__c lad { get; set; }
+
+        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
+            checkFlag = false;
+            lineNo = in_no;
+            lad = in_lad;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerTakeBackController.cls-meta.xml b/scr/classes/LoanerTakeBackController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerTakeBackController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LoanerTakeBackControllerTest.cls b/scr/classes/LoanerTakeBackControllerTest.cls
new file mode 100644
index 0000000..8cbd681
--- /dev/null
+++ b/scr/classes/LoanerTakeBackControllerTest.cls
@@ -0,0 +1,495 @@
+@isTest
+private class LoanerTakeBackControllerTest {
+	static void setupTestData() {
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+    }
+	@isTest static void test_method_one() {
+                setupTestData();
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        
+                List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+                
+                // 鏂板缓澶囧搧鍊熷嚭鐢宠
+                loaner_application__c loaner = new loaner_application__c();
+                loaner.Name = 'TEST';
+                loaner.RecordTypeId = rectLo[0].id;
+                loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+                loaner.DEMO_PURPOSE__C = '婕旂ず';
+                loaner.Request_shipping_Date__c = Date.today();
+                loaner.Request_return_Date__c = Date.today();
+                loaner.Status__c = '宸插嚭搴撴寚绀�';
+                loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+                //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+                insert loaner;
+
+                // 鏂板缓 瀹㈡埛
+                Account acc = new Account();
+                acc.RecordTypeId = rectCo[0].Id;
+                acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+                acc.DivisionName__c = 'DivisionName__c';
+                acc.FacilityName__c = 'FacilityName__c';
+                acc.PostCode__c='000000';
+                insert acc;
+                 
+                // 鏂板缓 璧勪骇
+                List<Asset> In_asset = new List<Asset>();
+
+                Asset asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�1';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�2';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                asset = new Asset();
+                asset.Name = '銉嗐偣銉堟鍣�3';
+                asset.AccountId = acc.Id;
+                asset.SerialNumber = 'testserial';
+                In_asset.add(asset);
+
+                insert In_asset;
+
+                // 鏂板缓 鍊熷嚭鏄庣粏
+                List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+                loaner_application_detail__c detail = new loaner_application_detail__c();
+
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[0].id;
+                detail.name = '000';
+                detail.RAESD_STATUS__C = '宸插洖瀵�';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[1].id;
+                detail.name = '111';
+                detail.RAESD_STATUS__C = '宸插洖瀵�';
+                In_detail.add(detail);
+
+                detail = new loaner_application_detail__c();
+                detail.loaner_application__c = loaner.Id;
+                detail.loaner__c = In_asset[2].id;
+                detail.name = '222';
+                detail.RAESD_STATUS__C = '宸插洖瀵�';
+                In_detail.add(detail);
+
+                insert In_detail;
+
+                //
+                PageReference page = new PageReference('/apex/LoanerTakeBackController?Id=' + loaner.Id + '&step=ReceivedLoaner');
+                System.Test.setCurrentPage(page);
+                LoanerTakeBackController  controller = new LoanerTakeBackController();
+
+
+                controller.init();
+                
+                controller.dataLines[0].checkFlag = true;
+                controller.dataLines[0].lad.Check_lost_Item__c = '娆犲搧';
+                controller.dataLines[0].lad.ReceiptRemark__c = '澶囨敞';
+                
+                controller.dataLines[1].checkFlag = true;
+                controller.dataLines[1].lad.Check_lost_Item__c = 'OK';
+
+                controller.dataLines[2].checkFlag = true;
+                controller.dataLines[2].lad.Check_lost_Item__c = '娑堣��';
+
+                controller.saveBtn();
+                //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+                controller.cancelBtn();
+                controller.getDatalineSize();
+
+                //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+                List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+                system.assertEquals('娆犲搧涓�', updList[0].RAESD_Status__c);
+                system.assertEquals('宸插洖鏀�', updList[1].RAESD_Status__c);
+                system.assertEquals('宸叉秷鑰�', updList[2].RAESD_Status__c);
+
+
+                List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+                system.assertEquals('娆犲搧纭涓�', laList[0].Status__c);
+	}
+	
+    @isTest static void test_method_two() {
+        // Implement test code
+        setupTestData();
+        // Implement test code
+        List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'ANI'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE2';
+        loaner.DEMO_PURPOSE__C = '鍩硅';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+
+        loaner_application__c loaner2 = new loaner_application__c();
+        loaner2.Name = 'TEST';
+        loaner2.RecordTypeId = rectLo[0].id;
+        loaner2.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE2';
+        loaner2.DEMO_PURPOSE__C = '鍩硅';
+        loaner2.Request_shipping_Date__c = Date.today();
+        loaner2.Request_return_Date__c = Date.today();
+        loaner2.Status__c = '宸插嚭搴撴寚绀�';
+        loaner2.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner2;
+
+        loaner_application__c loaner3 = new loaner_application__c();
+        loaner3.Name = 'TEST';
+        loaner3.RecordTypeId = rectLo[0].id;
+        loaner3.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE2';
+        loaner3.DEMO_PURPOSE__C = '鍩硅';
+        loaner3.Request_shipping_Date__c = Date.today();
+        loaner3.Request_return_Date__c = Date.today();
+        loaner3.Status__c = '宸插嚭搴撴寚绀�';
+        loaner3.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner3;
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name = 'SSBG DEALER ANI'];
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c = '000000';
+        insert dealer;
+        Contact core = new Contact(email = 'jplumber@salesforce.com', firstname = 'Joe', lastname = 'Plumber', accountid = dealer.id);
+        insert core;
+        User testUser = New User(ContactId = core.id,ViolationsID__c = loaner.Id ,Alias = 'newUser', Email = 'newuser@testorg.com', EmailEncodingKey = 'UTF-8', LastName = 'TestUser', LanguageLocaleKey = 'zh_CN', LocaleSidKey = 'zh_CN', ProfileId = prof.Id, TimeZoneSidKey = 'Asia/Shanghai', UserName = 'testUser01@prectech.com');
+        insert testUser;
+
+        User_Violations__c uv = new User_Violations__c();
+        uv.Is_locking__c = true;
+        uv.Is_effective__c = true;
+        uv.Locking_Start_Date__c = Date.today();
+        uv.Violations_User__c = testUser.Id;
+        uv.Violations_Loaner__c = loaner.id;
+        uv.Violations_reason__c = '瓒呮湡鏈綊杩�';
+        insert uv;
+
+        User_Violations__c uv2 = new User_Violations__c();
+        uv2.Is_locking__c = true;
+        uv2.Is_effective__c = true;
+        uv2.Locking_Start_Date__c = Date.today();
+        uv2.Violations_User__c = testUser.Id;
+        uv2.Violations_Loaner__c = loaner2.id;
+        uv2.Violations_reason__c = '绯荤粺鑷姩鏀惰揣';
+        insert uv2;
+
+        User_Violations__c uv3 = new User_Violations__c();
+        uv3.Is_locking__c = true;
+        uv3.Is_effective__c = true;
+        uv3.Locking_Start_Date__c = Date.today();
+        uv3.Violations_User__c = testUser.Id;
+        uv3.Violations_Loaner__c = loaner3.id;
+        uv3.Violations_reason__c = '绯荤粺鑷姩鏀惰揣';
+        insert uv3;
+
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c = '000000';
+        insert acc;
+
+        // 鏂板缓 璧勪骇
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        //
+        PageReference page = new PageReference('/apex/LoanerTakeBackController?Id=' + loaner.Id + '&step=ReceivedLoaner');
+        System.Test.setCurrentPage(page);
+        LoanerTakeBackController  controller = new LoanerTakeBackController();
+
+
+        controller.init();
+
+        controller.dataLines[0].checkFlag = true;
+        controller.dataLines[0].lad.Check_lost_Item__c = 'OK';
+        //controller.dataLines[0].lad.ReceiptRemark__c = '澶囨敞';
+
+        controller.dataLines[1].checkFlag = true;
+        controller.dataLines[1].lad.Check_lost_Item__c = 'OK';
+
+        controller.dataLines[2].checkFlag = true;
+        controller.dataLines[2].lad.Check_lost_Item__c = 'OK';
+
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.cancelBtn();
+        controller.getDatalineSize();
+
+        //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+        List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+        //system.assertEquals('娆犲搧涓�', updList[0].RAESD_Status__c);
+        //system.assertEquals('宸插洖鏀�', updList[1].RAESD_Status__c);
+        //system.assertEquals('宸叉秷鑰�', updList[2].RAESD_Status__c);
+
+
+        List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+        //system.assertEquals('鍏ㄩ儴鍥炴敹', laList[0].Status__c);
+    }
+
+    @isTest static void test_method_three() {
+        // Implement test code
+        setupTestData();
+        // Implement test code
+        List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'ANI'];
+
+        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE2';
+        loaner.DEMO_PURPOSE__C = '鍩硅';
+        loaner.Request_shipping_Date__c = Date.today();
+        loaner.Request_return_Date__c = Date.today();
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+
+        loaner_application__c loaner2 = new loaner_application__c();
+        loaner2.Name = 'TEST';
+        loaner2.RecordTypeId = rectLo[0].id;
+        loaner2.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE2';
+        loaner2.DEMO_PURPOSE__C = '鍩硅';
+        loaner2.Request_shipping_Date__c = Date.today();
+        loaner2.Request_return_Date__c = Date.today();
+        loaner2.Status__c = '宸插嚭搴撴寚绀�';
+        loaner2.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner2;
+
+        loaner_application__c loaner3 = new loaner_application__c();
+        loaner3.Name = 'TEST';
+        loaner3.RecordTypeId = rectLo[0].id;
+        loaner3.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE2';
+        loaner3.DEMO_PURPOSE__C = '鍩硅';
+        loaner3.Request_shipping_Date__c = Date.today();
+        loaner3.Request_return_Date__c = Date.today();
+        loaner3.Status__c = '宸插嚭搴撴寚绀�';
+        loaner3.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner3;
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name = 'SSBG DEALER ANI'];
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c = '000000';
+        insert dealer;
+        Contact core = new Contact(email = 'jplumber@salesforce.com', firstname = 'Joe', lastname = 'Plumber', accountid = dealer.id);
+        insert core;
+        User testUser = New User(ContactId = core.id,ViolationsID__c = loaner.Id ,Alias = 'newUser', Email = 'newuser@testorg.com', EmailEncodingKey = 'UTF-8', LastName = 'TestUser', LanguageLocaleKey = 'zh_CN', LocaleSidKey = 'zh_CN', ProfileId = prof.Id, TimeZoneSidKey = 'Asia/Shanghai', UserName = 'testUser01@prectech.com');
+        insert testUser;
+
+        User_Violations__c uv = new User_Violations__c();
+        uv.Is_locking__c = true;
+        uv.Is_effective__c = true;
+        uv.Locking_Start_Date__c = Date.today();
+        uv.Violations_User__c = testUser.Id;
+        uv.Violations_Loaner__c = loaner.id;
+        uv.Violations_reason__c = '瓒呮湡鏈綊杩�';
+        insert uv;
+
+        //User_Violations__c uv2 = new User_Violations__c();
+        //uv2.Is_locking__c = true;
+        //uv2.Is_effective__c = true;
+        //uv2.Locking_Start_Date__c = Date.today();
+        //uv2.Violations_User__c = testUser.Id;
+        //uv2.Violations_Loaner__c = loaner2.id;
+        //uv2.Violations_reason__c = '绯荤粺鑷姩鏀惰揣';
+        //insert uv2;
+
+        //User_Violations__c uv3 = new User_Violations__c();
+        //uv3.Is_locking__c = true;
+        //uv3.Is_effective__c = true;
+        //uv3.Locking_Start_Date__c = Date.today();
+        //uv3.Violations_User__c = testUser.Id;
+        //uv3.Violations_Loaner__c = loaner3.id;
+        //uv3.Violations_reason__c = '绯荤粺鑷姩鏀惰揣';
+        //insert uv3;
+
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c = '000000';
+        insert acc;
+
+        // 鏂板缓 璧勪骇
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '宸插洖瀵�';
+        In_detail.add(detail);
+
+        insert In_detail;
+
+        //
+        PageReference page = new PageReference('/apex/LoanerTakeBackController?Id=' + loaner.Id + '&step=ReceivedLoaner');
+        System.Test.setCurrentPage(page);
+        LoanerTakeBackController  controller = new LoanerTakeBackController();
+
+
+        controller.init();
+
+        controller.dataLines[0].checkFlag = true;
+        controller.dataLines[0].lad.Check_lost_Item__c = 'OK';
+        //controller.dataLines[0].lad.ReceiptRemark__c = '澶囨敞';
+
+        controller.dataLines[1].checkFlag = true;
+        controller.dataLines[1].lad.Check_lost_Item__c = 'OK';
+
+        controller.dataLines[2].checkFlag = true;
+        controller.dataLines[2].lad.Check_lost_Item__c = 'OK';
+
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.cancelBtn();
+        controller.getDatalineSize();
+
+        //List<loaner_application__c> laList = [select Id,Status__c from loaner_application__c where Id = :laId];
+        List<loaner_application_detail__c> updList = [select name, RAESD_Status__c from loaner_application_detail__c order by name];
+        //system.assertEquals('娆犲搧涓�', updList[0].RAESD_Status__c);
+        //system.assertEquals('宸插洖鏀�', updList[1].RAESD_Status__c);
+        //system.assertEquals('宸叉秷鑰�', updList[2].RAESD_Status__c);
+
+
+        List<loaner_application__c> laList = [select Status__c from loaner_application__c];
+        //system.assertEquals('鍏ㄩ儴鍥炴敹', laList[0].Status__c);
+    }
+	
+}
\ No newline at end of file
diff --git a/scr/classes/LoanerTakeBackControllerTest.cls-meta.xml b/scr/classes/LoanerTakeBackControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/LoanerTakeBackControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendBatch.cls b/scr/classes/LogAutoSendBatch.cls
new file mode 100644
index 0000000..903b5f4
--- /dev/null
+++ b/scr/classes/LogAutoSendBatch.cls
@@ -0,0 +1,106 @@
+global class LogAutoSendBatch implements Database.Batchable<sObject> {
+	/**
+     * 銈炽兂銈广偪銉炽儓
+     */
+    private String typeNFM;
+    private String  messageGroupNumber;
+    private Datetime times;
+
+    global LogAutoSendBatch() {}	 
+    global LogAutoSendBatch(String type, String message, Datetime times) {
+        this.typeNFM = type;
+        this.messageGroupNumber = message;
+        this.times = times;
+    }
+    /**
+     * start銇伅銆乹uery銈掑疅琛屻�佸鍝佺敵璇峰�熷嚭鍘嗗彶銈掓绱�
+     */
+    
+
+    global Database.QueryLocator start(Database.BatchableContext BC) {
+        Integer max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        if (String.isNotBlank(typeNFM) && String.isNotBlank(messageGroupNumber) && times != null) {
+            return Database.getQueryLocator(
+                [SELECT Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                        Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,Type__c,
+                        retry_cnt__c
+                   FROM BatchIF_Log__c
+                  WHERE RowDataFlg__c = true
+                    AND Type__c = :typeNFM AND CreatedDate >= :times  AND MessageGroupNumber__c >= :messageGroupNumber
+                    order by MessageGroupNumber__c asc  ]
+            );
+        } else if (new_profileId == System.Label.SystemAdmin || new_profileId == System.Label.SystemAdmin2) {
+            return Database.getQueryLocator(
+                [SELECT Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                        Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,Type__c,
+                        retry_cnt__c
+                   FROM BatchIF_Log__c
+                  WHERE RowDataFlg__c = true
+                    AND (Type__c = 'SBGITMRestNew'  OR Type__c = 'SBG010' OR Type__c = 'SBG017' OR Type__c = 'SBG027' OR
+                        Type__c = 'SBG004'  OR Type__c = 'SBG005' OR Type__c = 'SBG203' OR Type__c = 'SBG204' OR Type__c = 'SBG018' OR Type__c = 'SBG001' OR Type__c = 'SBG007') 
+                    AND retry_cnt__c != null AND retry_cnt__c > 0 AND retry_cnt__c < :max_cnt 
+                ]
+            );
+        } else {
+            return Database.getQueryLocator(
+                [SELECT Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                        Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,Type__c,
+                        retry_cnt__c
+                   FROM BatchIF_Log__c
+                  WHERE RowDataFlg__c = true
+                    AND retry_cnt__c != null AND retry_cnt__c > 0 AND retry_cnt__c < :max_cnt 
+                    AND (Type__c = 'SBGITMRestNew'  OR Type__c = 'SBG010' OR Type__c = 'SBG017' OR Type__c = 'SBG027' OR
+                        Type__c = 'SBG004'  OR Type__c = 'SBG005' OR Type__c = 'SBG203' OR Type__c = 'SBG204' OR Type__c = 'SBG018' OR Type__c = 'SBG001' OR Type__c = 'SBG007')  AND ownerId = : UserInfo.getUserId()]
+            );    
+        }
+        /*
+        return Database.getQueryLocator(
+            [SELECT Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                    Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,Type__c,
+                    retry_cnt__c
+               FROM BatchIF_Log__c
+              WHERE RowDataFlg__c = true
+                AND retry_cnt__c != null AND retry_cnt__c > 0 AND retry_cnt__c < :max_cnt 
+                AND (Type__c = 'SBGITMRestNew'  OR Type__c = 'SBG010' OR Type__c = 'SBG017' OR Type__c = 'SBG027' OR
+                    Type__c = 'SBG004'  OR Type__c = 'SBG005' OR Type__c = 'SBG203' OR Type__c = 'SBG204' OR Type__c = 'SBG018' OR Type__c = 'SBG001' OR Type__c = 'SBG007') ]
+        );
+        */
+    }
+
+    global void execute(Database.BatchableContext BC, List<BatchIF_Log__c> rowDataList) {
+        String strType_c = null;
+        for (BatchIF_Log__c rowData:rowDataList){
+            strType_c= String.valueOf(rowData.get('Type__c'));
+            if (strType_c == 'SBGITMRestNew'){
+                // SBGITMWebService.execute(rowData.Id);
+                SBGITMRestNew.main(rowData.Id);
+            }
+            else if(strType_c == 'SBG010'){
+                SBG010Rest.main(rowData.Id);
+            }
+            else if(strType_c == 'SBG017'){
+                SBG017Rest.main(rowData.Id);
+            }else if(strType_c == 'SBG027'){
+                SBG027Controller.execute2(rowData.Id);
+            }else if(strType_c == 'SBG004'){
+                SBG004Rest.main(rowData.Id);
+            }else if(strType_c == 'SBG005'){
+                SBG005Rest.main(rowData.Id);
+            }else if(strType_c == 'SBG203'){
+                SBG203Rest.main(rowData.Id);
+            }else if(strType_c == 'SBG204'){
+                SBG204Rest.main(rowData.Id);
+            }else if(strType_c == 'SBG018'){
+                SBG018Rest.main(rowData.Id);
+            }else if(strType_c == 'SBG001'){
+                SBG001TriggerHandler.execute2(rowData.Id);
+            }
+
+        }
+    }
+
+    global void finish(Database.BatchableContext BC) {
+        // 浠婂洖銇倓銈嬨亾銇ㄣ仾銇勩仹銇�
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendBatch.cls-meta.xml b/scr/classes/LogAutoSendBatch.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendBatchProduct.cls b/scr/classes/LogAutoSendBatchProduct.cls
new file mode 100644
index 0000000..bf22a67
--- /dev/null
+++ b/scr/classes/LogAutoSendBatchProduct.cls
@@ -0,0 +1,40 @@
+global class LogAutoSendBatchProduct implements Database.Batchable<sObject> {
+
+	  global LogAutoSendBatchProduct() {}
+
+
+	      global Database.QueryLocator start(Database.BatchableContext BC) {
+    	Integer max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+
+        return Database.getQueryLocator(
+            [SELECT Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                    Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,Type__c,
+                    retry_cnt__c
+               FROM BatchIF_Log__c
+              WHERE RowDataFlg__c = true
+                AND retry_cnt__c != null AND retry_cnt__c > 0 AND retry_cnt__c < :max_cnt AND (Type__c = 'SBG004' OR Type__c = 'SBG005')]
+        );
+    }
+
+    global void execute(Database.BatchableContext BC, List<BatchIF_Log__c> rowDataList) {
+    	String strType_c = null;
+    	for (BatchIF_Log__c rowData:rowDataList){
+    		strType_c= String.valueOf(rowData.get('Type__c'));
+            if (strType_c == 'SBG004'){
+                // SBG004WebService.execute(BC,rowDataList);
+                SBG004Rest.main(rowData.Id);
+            }
+            if (strType_c == 'SBG005'){
+                // SBG005WebService.execute(BC,rowDataList);
+                SBG005Rest.main(rowData.Id);
+            }
+            
+        }
+    }
+
+    global void finish(Database.BatchableContext BC) {
+        // 浠婂洖銇倓銈嬨亾銇ㄣ仾銇勩仹銇�
+    }
+
+	  
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendBatchProduct.cls-meta.xml b/scr/classes/LogAutoSendBatchProduct.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendBatchProduct.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendBatchProductTest.cls b/scr/classes/LogAutoSendBatchProductTest.cls
new file mode 100644
index 0000000..157953f
--- /dev/null
+++ b/scr/classes/LogAutoSendBatchProductTest.cls
@@ -0,0 +1,141 @@
+@isTest
+private class LogAutoSendBatchProductTest {
+	 static Product2 testSBG004Init() {
+        // 銉嗐偣銉堛儑銉笺偪
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        insert prd;  
+        //Pricebook2 prdbook     = new Pricebook2();
+
+        Pricebook2 prdbook1 = new Pricebook2( 
+            Name = 'testSBG004',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2( 
+            Name = 'testSBG004',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+        return prd;
+        
+    }
+	@isTest 
+    static void test_LogAutoSendBatchProduct_SBG004() {
+		testSBG004Init();
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.ProductCode  = 'testSBG004X';
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        //System.Test.startTest();
+        SBG004Rest.main(rowData.Id);
+        
+        //SBGITMRest.main(rowData.Id);
+        BatchIF_Log__c[] logs =[Select Id,
+                                    Name,
+                                    Log__c,
+                                    ErrorLog__c,
+                                    Log2__c,
+                                    Log3__c,
+                                    Log4__c,
+                                    Log5__c,
+                                    Log6__c,
+                                    Log7__c,
+                                    Log8__c,
+                                    Log9__c,
+                                    Log10__c,
+                                    Log11__c,
+                                    Log12__c,
+                                    MessageGroupNumber__c,
+                                    retry_cnt__c
+                                from BatchIF_Log__c
+                                where RowDataFlg__c = true
+                                and Type__c = 'SBG004'
+                                order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c=1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatchProduct(), 1);
+	    //System.Test.stopTest();
+    }
+    @isTest 
+    static void test_LogAutoSendBatchProduct_SBG005() {
+        testSBG004Init();
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.ProductCode  = 'testSBG005X';
+         BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        //System.Test.startTest();
+        SBG005Rest.main(rowData.Id);
+        
+        BatchIF_Log__c[] logs =[Select Id,
+                            Name,
+                            Log__c,
+                            ErrorLog__c,
+                            Log2__c,
+                            Log3__c,
+                            Log4__c,
+                            Log5__c,
+                            Log6__c,
+                            Log7__c,
+                            Log8__c,
+                            Log9__c,
+                            Log10__c,
+                            Log11__c,
+                            Log12__c,
+                            MessageGroupNumber__c,
+                            retry_cnt__c
+                        from BatchIF_Log__c
+                        where RowDataFlg__c = true
+                        and Type__c = 'SBG005'
+                        order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c=1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatchProduct(), 1);
+        //System.Test.stopTest();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendBatchProductTest.cls-meta.xml b/scr/classes/LogAutoSendBatchProductTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendBatchProductTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendBatchTest.cls b/scr/classes/LogAutoSendBatchTest.cls
new file mode 100644
index 0000000..1e7e265
--- /dev/null
+++ b/scr/classes/LogAutoSendBatchTest.cls
@@ -0,0 +1,296 @@
+@isTest
+private class LogAutoSendBatchTest {
+
+    @isTest
+    static void test_LogAutoSendBatch_SBGITM() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        // SBGITMRest.SBGITM(GeDatas);
+        //
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRest.main(rowData.Id);
+        BatchIF_Log__c[] logs = [Select Id,
+                                 Name,
+                                 Log__c,
+                                 ErrorLog__c,
+                                 Log2__c,
+                                 Log3__c,
+                                 Log4__c,
+                                 Log5__c,
+                                 Log6__c,
+                                 Log7__c,
+                                 Log8__c,
+                                 Log9__c,
+                                 Log10__c,
+                                 Log11__c,
+                                 Log12__c,
+                                 MessageGroupNumber__c,
+                                 retry_cnt__c
+                                 from BatchIF_Log__c
+                                 where RowDataFlg__c = true
+                                         and Type__c = 'SBGITM'
+                                                 order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c = 1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 1);
+
+    }
+    @isTest
+    static void test_LogAutoSendBatch_SBG010() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        // SBGITMRest.SBGITM(GeDatas);
+        //
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG010', GeDatas.GeData);
+        SBG010WebService.execute(rowData.Id);
+        BatchIF_Log__c[] logs = [Select Id,
+                                 Name,
+                                 Log__c,
+                                 ErrorLog__c,
+                                 Log2__c,
+                                 Log3__c,
+                                 Log4__c,
+                                 Log5__c,
+                                 Log6__c,
+                                 Log7__c,
+                                 Log8__c,
+                                 Log9__c,
+                                 Log10__c,
+                                 Log11__c,
+                                 Log12__c,
+                                 MessageGroupNumber__c,
+                                 retry_cnt__c
+                                 from BatchIF_Log__c
+                                 where RowDataFlg__c = true
+                                         and Type__c = 'SBG010'
+                                                 order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c = 1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 1);
+
+    }
+
+    @isTest
+    static void test_LogAutoSendBatch_SBG017() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        // SBGITMRest.SBGITM(GeDatas);
+        //
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG017', GeDatas.GeData);
+        SBG017Rest.main(rowData.Id);
+        BatchIF_Log__c[] logs = [Select Id,
+                                 Name,
+                                 Log__c,
+                                 ErrorLog__c,
+                                 Log2__c,
+                                 Log3__c,
+                                 Log4__c,
+                                 Log5__c,
+                                 Log6__c,
+                                 Log7__c,
+                                 Log8__c,
+                                 Log9__c,
+                                 Log10__c,
+                                 Log11__c,
+                                 Log12__c,
+                                 MessageGroupNumber__c,
+                                 retry_cnt__c
+                                 from BatchIF_Log__c
+                                 where RowDataFlg__c = true
+                                         and Type__c = 'SBG017'
+                                                 order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c = 1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 1);
+
+    }
+
+    @isTest
+    static void test_LogAutoSendBatch_SBG203() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        // SBGITMRest.SBGITM(GeDatas);
+        //
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG203', GeDatas.GeData);
+        SBG203Rest.main(rowData.Id);
+        BatchIF_Log__c[] logs = [Select Id,
+                                 Name,
+                                 Log__c,
+                                 ErrorLog__c,
+                                 Log2__c,
+                                 Log3__c,
+                                 Log4__c,
+                                 Log5__c,
+                                 Log6__c,
+                                 Log7__c,
+                                 Log8__c,
+                                 Log9__c,
+                                 Log10__c,
+                                 Log11__c,
+                                 Log12__c,
+                                 MessageGroupNumber__c,
+                                 retry_cnt__c
+                                 from BatchIF_Log__c
+                                 where RowDataFlg__c = true
+                                         and Type__c = 'SBG203'
+                                                 order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c = 1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 1);
+
+    }
+
+    @isTest
+    static void test_LogAutoSendBatch_SBG204() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        // SBGITMRest.SBGITM(GeDatas);
+        //
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG204', GeDatas.GeData);
+        SBG204Rest.main(rowData.Id);
+        BatchIF_Log__c[] logs = [Select Id,
+                                 Name,
+                                 Log__c,
+                                 ErrorLog__c,
+                                 Log2__c,
+                                 Log3__c,
+                                 Log4__c,
+                                 Log5__c,
+                                 Log6__c,
+                                 Log7__c,
+                                 Log8__c,
+                                 Log9__c,
+                                 Log10__c,
+                                 Log11__c,
+                                 Log12__c,
+                                 MessageGroupNumber__c,
+                                 retry_cnt__c
+                                 from BatchIF_Log__c
+                                 where RowDataFlg__c = true
+                                         and Type__c = 'SBG204'
+                                                 order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c = 1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 1);
+
+    }
+
+    @isTest
+    static void test_LogAutoSendBatch_SBG018() {
+        SBG018Rest.GeData GeData = new SBG018Rest.GeData();
+        SBG018Rest.GeDatas GeDatas = new SBG018Rest.GeDatas();
+        GeDatas.GeData = new SBG018Rest.GeData[] { GeData };
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        SBG018Rest.GeDataDetails GeDataDetail01 = new  SBG018Rest.GeDataDetails();
+        SBG018Rest.GeDataDetails GeDataDetail02 = new  SBG018Rest.GeDataDetails();
+        GeData.GeDataDetails = new  SBG018Rest.GeDataDetails[] {GeDataDetail01, GeDataDetail02};
+        GeData.Status = 'Z5';
+        GeData.TransforDate = String.valueOf(Date.today());//'20210113';
+        GeDataDetail01.ProductCode = 'testSBG018';
+        GeDataDetail01.Plant = 'CCTV';
+        GeDataDetail01.Department = 'LS';
+        GeDataDetail01.FGSP = 'SP';
+        GeDataDetail01.Qty = '11';
+        GeDataDetail01.TradeType = 'Taxation';
+        GeDataDetail02.ProductCode = 'testSBG018';
+        // 鐢ㄤ簬瑙﹀彂寮傚父 杩涘叆Catch
+        GeDataDetail02.Plant = 'CC31';
+
+        GeDataDetail02.Department = 'LS';
+        GeDataDetail02.FGSP = 'FG';
+        GeDataDetail02.Qty = '11';
+        GeDataDetail02.TradeType = 'Taxation';
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG018', GeDatas.GeData);
+        SBG018Rest.main(rowData.Id);
+        
+        BatchIF_Log__c[] logs =[Select Id,
+                                    Name,
+                                    Log__c,
+                                    Type__c,
+                                    ErrorLog__c,
+                                    Log2__c,
+                                    Log3__c,
+                                    Log4__c,
+                                    Log5__c,
+                                    Log6__c,
+                                    Log7__c,
+                                    Log8__c,
+                                    Log9__c,
+                                    Log10__c,
+                                    Log11__c,
+                                    Log12__c,
+                                    MessageGroupNumber__c,
+                                    CreatedDate,
+                                    retry_cnt__c
+                                from BatchIF_Log__c
+                                where RowDataFlg__c = true
+                                and Type__c = 'SBG018'
+                                order by CreatedDate desc ];
+
+        logs[0].retry_cnt__c=1;
+        update logs;
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 5);
+        Database.executeBatch(new LogAutoSendBatch(logs[0].Type__c,logs[0].MessageGroupNumber__c,logs[0].CreatedDate), 1);
+
+
+    }
+
+
+
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendBatchTest.cls-meta.xml b/scr/classes/LogAutoSendBatchTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendSchedule.cls b/scr/classes/LogAutoSendSchedule.cls
new file mode 100644
index 0000000..a824752
--- /dev/null
+++ b/scr/classes/LogAutoSendSchedule.cls
@@ -0,0 +1,20 @@
+global class LogAutoSendSchedule implements Schedulable {
+
+    global void execute(SchedulableContext SC) {
+        Id execBTId = Database.executeBatch(new LogAutoSendBatch(), 1);
+    }
+
+    public static void assignOneMinute() {
+        // delete 瀹熻娓堛伩
+        Datetime addOneM = System.now().addMinutes(2);
+        String CRON_EXP = '0 ' + addOneM.minute() + ' ' + addOneM.hour() + ' ' + addOneM.day() + ' ' + addOneM.month() + ' ? ' + addOneM.year();
+        List<CronTrigger> oldcron = [select Id from CronTrigger where CronExpression = :CRON_EXP and CronJobDetail.Name like 'LogAutoSendSBG%'];
+        if (oldcron.size() == 0) {
+            System.schedule('LogAutoSendSBG' + CRON_EXP, CRON_EXP, new LogAutoSendSchedule());
+        }
+        for (CronTrigger ct :
+                [SELECT Id FROM CronTrigger WHERE State = 'DELETED' and CronJobDetail.Name like 'LogAutoSendSBG%']) {
+            System.abortJob(ct.id);
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendSchedule.cls-meta.xml b/scr/classes/LogAutoSendSchedule.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendSchedule.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendScheduleProduct.cls b/scr/classes/LogAutoSendScheduleProduct.cls
new file mode 100644
index 0000000..2af92af
--- /dev/null
+++ b/scr/classes/LogAutoSendScheduleProduct.cls
@@ -0,0 +1,19 @@
+global class LogAutoSendScheduleProduct implements Schedulable {
+	global void execute(SchedulableContext SC) {
+        Id execBTId = Database.executeBatch(new LogAutoSendBatchProduct(), 1);
+    }
+
+    public static void assignOneMinute() {
+        // delete 瀹熻娓堛伩
+        Datetime addOneM = System.now().addMinutes(2);
+        String CRON_EXP = '0 ' + addOneM.minute() + ' ' + addOneM.hour() + ' ' + addOneM.day() + ' ' + addOneM.month() + ' ? ' + addOneM.year();
+        List<CronTrigger> oldcron = [select Id from CronTrigger where CronExpression = :CRON_EXP and CronJobDetail.Name like 'LogAutoSendProduct%'];
+        if (oldcron.size() == 0) {
+            System.schedule('LogAutoSendProduct' + CRON_EXP, CRON_EXP, new LogAutoSendScheduleProduct());
+        }
+        for (CronTrigger ct :
+                [SELECT Id FROM CronTrigger WHERE State = 'DELETED' and CronJobDetail.Name like 'LogAutoSendProduct%']) {
+            System.abortJob(ct.id);
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendScheduleProduct.cls-meta.xml b/scr/classes/LogAutoSendScheduleProduct.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendScheduleProduct.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendScheduleProductTest.cls b/scr/classes/LogAutoSendScheduleProductTest.cls
new file mode 100644
index 0000000..551f325
--- /dev/null
+++ b/scr/classes/LogAutoSendScheduleProductTest.cls
@@ -0,0 +1,13 @@
+@isTest
+private class LogAutoSendScheduleProductTest {
+	
+	@isTest static void test_LogAutoSendScheduleProduct() {
+		Datetime addOneM = System.now().addMinutes(2);
+		String CRON_EXP = '0 ' + addOneM.minute() + ' ' + addOneM.hour() + ' ' + addOneM.day() + ' ' + addOneM.month() + ' ? ' + addOneM.year();
+        LogAutoSendScheduleProduct.assignOneMinute();
+		CronTrigger oldcron = [select Id, CronJobDetail.Name from CronTrigger where CronExpression = :CRON_EXP and CronJobDetail.Name like 'LogAutoSendProduct%'];
+        // Verify the next time the job will run
+        System.assertEquals('LogAutoSendProduct' + CRON_EXP, oldcron.CronJobDetail.Name);
+
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendScheduleProductTest.cls-meta.xml b/scr/classes/LogAutoSendScheduleProductTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendScheduleProductTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/LogAutoSendScheduleTest.cls b/scr/classes/LogAutoSendScheduleTest.cls
new file mode 100644
index 0000000..bcdb578
--- /dev/null
+++ b/scr/classes/LogAutoSendScheduleTest.cls
@@ -0,0 +1,13 @@
+@isTest
+private class LogAutoSendScheduleTest {
+	
+	@isTest static void test_assignOneMinute() {
+		Datetime addOneM = System.now().addMinutes(2);
+		String CRON_EXP = '0 ' + addOneM.minute() + ' ' + addOneM.hour() + ' ' + addOneM.day() + ' ' + addOneM.month() + ' ? ' + addOneM.year();
+        LogAutoSendSchedule.assignOneMinute();
+		CronTrigger oldcron = [select Id, CronJobDetail.Name from CronTrigger where CronExpression = :CRON_EXP and CronJobDetail.Name like 'LogAutoSendSBG%'];
+        // Verify the next time the job will run
+        System.assertEquals('LogAutoSendSBG' + CRON_EXP, oldcron.CronJobDetail.Name);
+
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/LogAutoSendScheduleTest.cls-meta.xml b/scr/classes/LogAutoSendScheduleTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/LogAutoSendScheduleTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/MessageBoardController.cls b/scr/classes/MessageBoardController.cls
new file mode 100644
index 0000000..0b306ae
--- /dev/null
+++ b/scr/classes/MessageBoardController.cls
@@ -0,0 +1,89 @@
+public with sharing class MessageBoardController {
+    String oldResponse;
+    // 璇环
+    public User_FaultInfo__c userfaultInfo { get; set; }
+    public User_FaultInfo__c userfaultInfoPoPuP { get; set; }
+    // CaseId
+    public Id caseId { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    public String usertype { get; private set; }
+    
+
+    public MessageBoardController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        caseId = ApexPages.currentPage().getParameters().get('caseId');
+    }
+
+    public MessageBoardController(ApexPages.StandardController stdController) {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        caseId = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        userfaultInfo = new User_FaultInfo__c();
+        // cc = new User_FaultInfo__c();
+        usertype = UserInfo.getUserType();
+        List<User_FaultInfo__c> raList = [select Id, Name, MessageBoard__c from User_FaultInfo__c where Id = :caseId];
+        if (raList.size() > 0) {
+            userfaultInfo = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        userfaultInfoPoPuP = new User_FaultInfo__c();
+        List<User_FaultInfo__c> ra1List = [select Id, Name, MessageBoard__c from User_FaultInfo__c where Id = :caseId];
+        if (ra1List.size() > 0) {
+            userfaultInfoPoPuP = ra1List[0];
+        }
+        oldResponse = userfaultInfoPoPuP.MessageBoard__c;
+        userfaultInfoPoPuP.MessageBoard__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = userfaultInfoPoPuP.MessageBoard__c;
+        if (response == null || response.trim().length() == 0) {
+            userfaultInfoPoPuP.MessageBoard__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += userfaultInfoPoPuP.MessageBoard__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+   
+            userfaultInfoPoPuP.MessageBoard__c = temp;
+
+            update userfaultInfoPoPuP;
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/MessageBoardController.cls-meta.xml b/scr/classes/MessageBoardController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/MessageBoardController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/MessageBoardControllerTest.cls b/scr/classes/MessageBoardControllerTest.cls
new file mode 100644
index 0000000..a89070c
--- /dev/null
+++ b/scr/classes/MessageBoardControllerTest.cls
@@ -0,0 +1,21 @@
+@isTest
+private class MessageBoardControllerTest {
+	static testMethod void testMethod1() {
+		User_FaultInfo__c uf = new User_FaultInfo__c();
+		uf.MessageBoard__c = 'Test';
+		insert uf;
+
+
+		PageReference page = new PageReference('/apex/MessageBoardPoPup?caseId=' + uf.Id);
+		System.Test.setCurrentPage(page);
+		MessageBoardController controller = new MessageBoardController();
+		controller.init();
+		controller.init1();
+		controller.userfaultInfoPoPuP.MessageBoard__c = 'TEST02';
+		controller.saveBtn();
+		MessageBoardController controller2 = new MessageBoardController(new ApexPages.StandardController(uf));
+		controller2.init();
+		//controller2.userfaultInfoPoPuP.MessageBoard__c = '';
+		//controller2.saveBtn();
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/MessageBoardControllerTest.cls-meta.xml b/scr/classes/MessageBoardControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/MessageBoardControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/MicrobatchSelfRegController.cls b/scr/classes/MicrobatchSelfRegController.cls
new file mode 100644
index 0000000..e848951
--- /dev/null
+++ b/scr/classes/MicrobatchSelfRegController.cls
@@ -0,0 +1,57 @@
+public class MicrobatchSelfRegController {
+    public String firstName {get; set;}
+    public String lastName {get; set;}
+    public String email {get; set;}
+    public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
+
+    public MicrobatchSelfRegController() {
+        String expid = ApexPages.currentPage().getParameters().get('expid');
+        if (expId != null) {
+            Site.setExperienceId(expId);
+        }
+    }
+
+    public PageReference registerUser() {
+        String userName = email;
+        String accountName; // to be filled by customer
+        String contactName; //to be filled by customer
+        String profileId = null; //to be filled by customer
+        String UUID;
+
+        User u = new User();
+        u.Username = userName;
+        u.Email = email;
+        u.FirstName = firstName;
+        u.LastName = lastName;
+        u.CommunityNickname = communityNickname;
+        u.ProfileId = profileId;
+        u.LocaleSidKey = 'en_US';
+        u.TimeZoneSidKey = 'GMT';
+        u.LanguageLocaleKey = 'en_US';
+        u.EmailEncodingKey = 'UTF-8';
+
+        Account acc = new Account();
+        acc.Name = 'Account for ' + lastName;
+        Contact c = new Contact();
+        c.lastName = lastName;
+
+        try {
+            UUID =  Network.createExternalUserAsync(u, c,acc);
+        } catch(Site.ExternalUserCreateException ex) {
+            List<String> errors = ex.getDisplayMessages();
+            for (String error : errors)  {
+                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, error));
+            }
+
+            // This message is used for debugging. Do not display this in the UI to the end user.
+            // It has the information around why the user creation failed.
+            System.debug(ex.getMessage());
+        }
+        if (UUID != null) {
+           PageReference page = System.Page.CommunitiesSelfRegConfirm;
+           page.setRedirect(true);
+           return page;
+        }
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/MicrobatchSelfRegController.cls-meta.xml b/scr/classes/MicrobatchSelfRegController.cls-meta.xml
new file mode 100644
index 0000000..40d6793
--- /dev/null
+++ b/scr/classes/MicrobatchSelfRegController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>54.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/MicrobatchSelfRegControllerTest.cls b/scr/classes/MicrobatchSelfRegControllerTest.cls
new file mode 100644
index 0000000..b6b8365
--- /dev/null
+++ b/scr/classes/MicrobatchSelfRegControllerTest.cls
@@ -0,0 +1,14 @@
+@IsTest
+ public with sharing class MicrobatchSelfRegControllerTest {
+      @IsTest(SeeAllData=true)
+     public static void testMicrobatchSelfRegController() {
+         MicrobatchSelfRegController controller = new MicrobatchSelfRegController();
+         controller.firstName = 'FirstName';
+         controller.lastName = 'LastName';
+         controller.email = 'test@force.com';
+         controller.communityNickname = 'test';
+
+         // registerUser will always return null when the page isn't accessed as a guest user
+         System.assert(controller.registerUser() == null);
+     }
+ }
\ No newline at end of file
diff --git a/scr/classes/MicrobatchSelfRegControllerTest.cls-meta.xml b/scr/classes/MicrobatchSelfRegControllerTest.cls-meta.xml
new file mode 100644
index 0000000..40d6793
--- /dev/null
+++ b/scr/classes/MicrobatchSelfRegControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>54.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/MyProfilePageController.cls b/scr/classes/MyProfilePageController.cls
new file mode 100644
index 0000000..0d49e6a
--- /dev/null
+++ b/scr/classes/MyProfilePageController.cls
@@ -0,0 +1,75 @@
+/**
+ * An apex class that keeps updates of a portal user in sync with its corresponding contact.
+   Guest users are never able to access this page.
+ */
+public with sharing class MyProfilePageController {
+
+    private User user;
+    private boolean isEdit = false;
+
+    public User getUser() {
+        return user;
+    }
+
+    public MyProfilePageController() {
+        user = [SELECT id, email, username, usertype, communitynickname, timezonesidkey, languagelocalekey, firstname, lastname, phone, title,
+                street, city, country, postalcode, state, localesidkey, mobilephone, extension, fax, contact.email
+                FROM User
+                WHERE id = :UserInfo.getUserId()];
+        // guest users should never be able to access this page
+        if (user.usertype == 'GUEST') {
+            throw new NoAccessException();
+        }
+    }
+
+    public Boolean getIsEdit() {
+        return isEdit;
+    }
+
+    public void edit() {
+        isEdit=true;
+    }
+
+    public void save() {
+        if (user.contact != null) {
+            setContactFields(user.contact, user);
+        }
+
+        try {
+            update user;
+            if (user.contact != null) {
+                update user.contact;
+            }
+            isEdit=false;
+        } catch(DmlException e) {
+            ApexPages.addMessages(e);
+        }
+    }
+
+    public PageReference changePassword() {
+        return Page.ChangePassword;
+    }
+
+    public void cancel() {
+        isEdit=false;
+        user = [SELECT id, email, username, communitynickname, timezonesidkey, languagelocalekey, firstname, lastname, phone, title,
+                street, city, country, postalcode, state, localesidkey, mobilephone, extension, fax, contact.email
+                FROM User
+                WHERE id = :UserInfo.getUserId()];
+    }
+
+    public static void setContactFields(Contact c, User u) {
+        c.title = u.title;
+        c.firstname = u.firstname;
+        c.lastname = u.lastname;
+        c.email = u.email;
+        c.phone = u.phone;
+        c.mobilephone = u.mobilephone;
+        c.fax = u.fax;
+        c.mailingstreet = u.street;
+        c.mailingcity = u.city;
+        c.mailingstate = u.state;
+        c.mailingpostalcode = u.postalcode;
+        c.mailingcountry = u.country;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/MyProfilePageController.cls-meta.xml b/scr/classes/MyProfilePageController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/MyProfilePageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/MyProfilePageControllerTest.cls b/scr/classes/MyProfilePageControllerTest.cls
new file mode 100644
index 0000000..2f6c63e
--- /dev/null
+++ b/scr/classes/MyProfilePageControllerTest.cls
@@ -0,0 +1,76 @@
+/**
+ * An apex class that keeps updates of a portal user in sync with its corresponding contact.
+   Guest users are never able to access this page.
+ */
+@IsTest public with sharing class MyProfilePageControllerTest {
+    @IsTest(SeeAllData=true) static void testSetContactFields() {
+        User u = [select title, firstname, lastname, email, phone, mobilephone, fax, street, city, state, postalcode, country
+                           FROM User WHERE id =: UserInfo.getUserId()];
+
+        Contact c = new Contact();
+
+        MyProfilePageController.setContactFields(c, u);
+        System.assertEquals(c.firstname, u.firstname, 'firstname should have been set as the firstname of the user for the contact');
+        System.assertEquals(c.lastname, u.lastname, 'lastname should have been set as the lastname of the user for the contact');
+    }
+
+    @IsTest(SeeAllData=true) static void testSave() {
+        // Modify the test to query for a portal user that exists in your org
+        List<User> existingPortalUsers = [SELECT id, profileId, userRoleId FROM User WHERE UserRoleId <> null AND UserType='CustomerSuccess'];
+
+        if (existingPortalUsers.isEmpty()) {
+            User currentUser = [select id, title, firstname, lastname, email, phone, mobilephone, fax, street, city, state, postalcode, country
+                                FROM User WHERE id =: UserInfo.getUserId()];
+            MyProfilePageController controller = new MyProfilePageController();
+            System.assertEquals(currentUser.Id, controller.getUser().Id, 'Did not successfully load the current user');
+            System.assert(controller.getIsEdit() == false, 'isEdit should default to false');
+            controller.edit();
+            System.assert(controller.getIsEdit() == true);
+            controller.cancel();
+            System.assert(controller.getIsEdit() == false);
+
+            Contact c = new Contact();
+            c.LastName = 'TestContact';
+            c.Phone = '11112222';
+            insert c;
+
+            c.title = currentUser.title;
+            c.firstname = currentUser.firstname;
+            c.lastname = currentUser.lastname;
+            c.email = currentUser.email;
+            c.phone = currentUser.phone;
+            c.mobilephone = currentUser.mobilephone;
+            c.fax = currentUser.fax;
+            c.mailingstreet = currentUser.street;
+            c.mailingcity = currentUser.city;
+            c.mailingstate = currentUser.state;
+            c.mailingpostalcode = currentUser.postalcode;
+            c.mailingcountry = currentUser.country;
+            controller.save();
+            System.assert(Page.ChangePassword.getUrl().equals(controller.changePassword().getUrl()));
+        } else {
+            User existingPortalUser = existingPortalUsers[0];
+            String randFax = Math.rint(Math.random() * 1000) + '5551234';
+
+            System.runAs(existingPortalUser) {
+                MyProfilePageController controller = new MyProfilePageController();
+                System.assertEquals(existingPortalUser.Id, controller.getUser().Id, 'Did not successfully load the current user');
+                System.assert(controller.getIsEdit() == false, 'isEdit should default to false');
+                controller.edit();
+                System.assert(controller.getIsEdit() == true);
+
+                controller.cancel();
+                System.assert(controller.getIsEdit() == false);
+
+                controller.getUser().Fax = randFax;
+                controller.save();
+                System.assert(controller.getIsEdit() == false);
+            }
+
+            // verify that the user and contact were updated
+            existingPortalUser = [Select id, fax, Contact.Fax from User where id =: existingPortalUser.Id];
+            System.assert(existingPortalUser.fax == randFax);
+            System.assert(existingPortalUser.Contact.fax == randFax);
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/MyProfilePageControllerTest.cls-meta.xml b/scr/classes/MyProfilePageControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/MyProfilePageControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NEWCreateSWOQuoteController.cls b/scr/classes/NEWCreateSWOQuoteController.cls
new file mode 100644
index 0000000..68b31b0
--- /dev/null
+++ b/scr/classes/NEWCreateSWOQuoteController.cls
@@ -0,0 +1,745 @@
+public without sharing class NEWCreateSWOQuoteController {
+    public Integer quoteEntryMaxLine {get; private set;}
+
+    public List<Product2> product2List { get; set; }
+    public List<QuotesItemInfo> productInfoList { get; set; }
+    public Quotes__c QuotesPage { get; set; }
+
+    public QuotesItemInfo QuotesItemInfo;
+    public Integer ProductInfoListSize {get; set;}
+    public String swoId { get; private set; }
+    public String Id {get; set;}
+
+    public List<EmailInfo> mailList {get; set;}
+
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public Map<String, Product2> specialProductMap;
+
+
+    public String Messages01 { get; set; }
+    public String Messages02 { get; set; }
+    public String Messages03 { get; set; }
+    public String Messages04 { get; set; }
+    public String Messages05 { get; set; }
+    public String Messages06 { get; set; }
+    public String Messages07 { get; set; }
+
+    public Boolean aftORbef { get; set; }
+    public Boolean aftORbef1 { get; set; }
+    public NEWCreateSWOQuoteController() {
+        swoId = System.currentPageReference().getParameters().get('swoId');
+        Id = System.currentPageReference().getParameters().get('Id');
+        quoteEntryMaxLine = Integer.valueOf(System.Label.QuoteEntryMaxLine);
+
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+    }
+
+    public NEWCreateSWOQuoteController(ApexPages.StandardController controller) {
+        this();
+    }
+
+    public void init () {
+        ProductInfoListSize = 1;
+        productInfoList = new  List<QuotesItemInfo>();
+        QuotesPage = new Quotes__c();
+        QuotesPage.CURRENCY__c = 'Chinese Yuan';
+        mailList = new List<EmailInfo>();
+        // 鑾峰彇鐗规畩浜у搧 Start
+        specialProductMap = new Map<String, Product2>();
+        List<Product2> specialProductList = [Select Id, Name, ProductCode, Description, PART_NUMBER__c from Product2 where SpecialProduct__c = true];
+        if (specialProductList.size() > 0) {
+
+            for (Product2  product : specialProductList) {
+                specialProductMap.put(product.ProductCode, product);
+            }
+        }
+        // 鑾峰彇鐗规畩浜у搧 End
+
+        // SWO鐨処d涓嶄负绌猴紝涓轰粠SWO鍒涘缓鐨勬姤浠�
+        if (String.isNotBlank(swoId)) {
+            QuotesPage.QuotesType__c = '缁翠慨鎶ヤ环鍗�';
+
+            // select Id,Name,SpecialProduct__c from Product2 where ProductCode In ('Service Quote Labour','DESCRIPTION','Service Quote Subtotal','OnsiteSupportFee','Transportation','Payment Info')
+
+            List<SWO__c> swoList = [SELECT Id, Name, COMPANY__c, CONTACT__c, ITEM__c, ITEM__r.ProductCode , QUANTITY__c, CONTACT__r.Address1D__c, ESTIMATED_LABOUR_HOURS__c, LABOUR_RATE__c, COMPANY__r.Name, CONTACT__r.Name, COMPANY__r.Address1__c, COMPANY__r.Address1D__c, DESCRIPTION_F__c, SERIAL__c, CONTACT__r.MobilePhoneD__c, CONTACT__r.PhoneD__c, CONTACT__r.Phone, CONTACT__r.MobilePhone  FROM SWO__c WHERE Id = :swoId limit 1];
+            if (swoList.size() > 0) {
+                String productId = swoList[0].ITEM__c;
+                Product2 product = [Select Id, Name, ProductCode, Description, PART_NUMBER__c from Product2 where id = :productId limit 1];
+                // 灏� DESCRIPTION 鐗规畩浜у搧鏀惧湪 绗竴琛� Start
+                if (specialProductMap.containsKey('DESCRIPTION')) {
+                    Product2 productDes = specialProductMap.get('DESCRIPTION');
+
+                    Quotes_item__c quotesItemDes = new Quotes_item__c();
+                    if (String.isNotBlank(swoList[0].DESCRIPTION_F__c) && String.isNotBlank(swoList[0].SERIAL__c)) {
+
+                        quotesItemDes.DESCRIPTION__c = swoList[0].DESCRIPTION_F__c + ' ' + swoList[0].SERIAL__c;
+                    } else if (String.isNotBlank(swoList[0].SERIAL__c)) {
+                        quotesItemDes.DESCRIPTION__c = swoList[0].SERIAL__c;
+                    } else if (String.isNotBlank(swoList[0].DESCRIPTION_F__c)) {
+                        quotesItemDes.DESCRIPTION__c = swoList[0].DESCRIPTION_F__c;
+                    }
+
+                    quotesItemDes.QUANTITY__c = 1;
+                    quotesItemDes.RATE__c = 0;
+                    productInfoList.add(new QuotesItemInfo(ProductInfoListSize, productDes, 1, QuotesPage, quotesItemDes));
+                    ProductInfoListSize++;
+                }
+                // 灏� DESCRIPTION 鐗规畩浜у搧鏀惧湪 绗竴琛� End
+
+                // Integer quantity = Integer.valueof(swoList[0].QUANTITY__c);
+                // Quotes_item__c quotesItem = new Quotes_item__c();
+                // // quotesItem.DESCRIPTION__c = product.Description;
+                // if (String.isNotBlank(swoList[0].DESCRIPTION_F__c) && String.isNotBlank(swoList[0].SERIAL__c)) {
+
+                //     quotesItem.DESCRIPTION__c = swoList[0].DESCRIPTION_F__c + ' ' + swoList[0].SERIAL__c;
+                // } else if (String.isNotBlank(swoList[0].SERIAL__c)) {
+                //     quotesItem.DESCRIPTION__c = swoList[0].SERIAL__c;
+                // } else if (String.isNotBlank(swoList[0].DESCRIPTION_F__c)) {
+                //     quotesItem.DESCRIPTION__c = swoList[0].DESCRIPTION_F__c;
+                // }
+                // quotesItem.QUANTITY__c = Decimal.valueof(quantity);
+
+                // productInfoList.add(new QuotesItemInfo(ProductInfoListSize, product, quantity, QuotesPage, quotesItem));
+                // ProductInfoListSize++;
+            }
+
+            // 鑾峰彇SWO涓嬩慨鐞嗕笂浜у搧鐨処d
+            Map<String, Integer> rpProductQuantityMap = new Map<String, Integer>();
+            List<RepairPart__c> repairPartList = [Select Id, Name, Product__c, QUANTITY__c From RepairPart__c where SWO_ID__c = :swoId];
+            List<String> repairPartProductIdList = new List<String>();
+            if (repairPartList.size() > 0) {
+
+                for (RepairPart__c repairpart : repairPartList) {
+                    repairPartProductIdList.add(repairpart.Product__c);
+                    Integer quantity = Integer.valueOf(repairpart.QUANTITY__c);
+                    rpProductQuantityMap.put(repairpart.Product__c, quantity);
+                }
+
+            }
+            // 鑾峰彇淇悊浜у搧鐨勭浉鍏充俊鎭�
+            if (repairPartProductIdList.size() > 0) {
+                product2List = [Select Id, Name, ProductCode, Description, PART_NUMBER__c from Product2 where Id IN :repairPartProductIdList];
+
+                if (product2List.size() > 0) {
+                    for (Product2 product : product2List) {
+                        Quotes_item__c quotesItem = new Quotes_item__c();
+                        Integer rpProductQuantity = rpProductQuantityMap.get(product.Id);
+                        quotesItem.DESCRIPTION__c = product.Description;
+                        quotesItem.QUANTITY__c = rpProductQuantityMap.get(product.Id);
+                        productInfoList.add(new QuotesItemInfo(ProductInfoListSize, product, rpProductQuantity, QuotesPage, quotesItem));
+                        ProductInfoListSize++;
+                    }
+                }
+
+            }
+
+            // 鑾峰彇 SWO 涓婂鎴蜂笌鑱旂郴浜虹殑淇℃伅
+            Boolean labour = false;
+            if (swoList[0].ESTIMATED_LABOUR_HOURS__c != null && swoList[0].ESTIMATED_LABOUR_HOURS__c != 0) {
+                labour = true;
+            }
+
+            if (swoList[0].LABOUR_RATE__c != null && swoList[0].LABOUR_RATE__c != 0) {
+                labour = true;
+            }
+
+            if (specialProductMap.containsKey('Service Quote Labour')) {
+                Product2 productLabour = specialProductMap.get('Service Quote Labour');
+                Quotes_item__c quotesItem = new Quotes_item__c();
+                Integer quantity =  Integer.valueOf(swoList[0].ESTIMATED_LABOUR_HOURS__c);
+                if (quantity == null) {
+                    quantity = 1;
+                }
+                quotesItem.QUANTITY__c = quantity;
+                quotesItem.RATE__c = swoList[0].LABOUR_RATE__c;
+                quotesItem.CURRENCY__c = QuotesPage.CURRENCY__c;
+                productInfoList.add(new QuotesItemInfo(ProductInfoListSize, productLabour, quantity, QuotesPage, quotesItem));
+                ProductInfoListSize++;
+
+
+            }
+
+            if (specialProductMap.containsKey('Service Quote Subtotal')) {
+                Product2 productSubtotal = specialProductMap.get('Service Quote Subtotal');
+                Quotes_item__c quotesItem = new Quotes_item__c();
+                Integer quantity1 =  1;
+                quotesItem.QUANTITY__c = 1;
+                quotesItem.RATE__c = 0;
+                quotesItem.CURRENCY__c = QuotesPage.CURRENCY__c;
+                quotesItem.DESCRIPTION__c = 'Service Quote Subtotal:' + swoList[0].Name;
+                productInfoList.add(new QuotesItemInfo(ProductInfoListSize, productSubtotal, quantity1, QuotesPage, quotesItem));
+                ProductInfoListSize++;
+            }
+
+            // 鏁版嵁鎷兼帴 BILL TO/BILL TO Start
+            // 瀹㈡埛鍚嶇О
+            // QuotesPage.BILL_TO__c = swoList[0].COMPANY__r.Name + '\n';
+            // QuotesPage.SHIP_TO__c = swoList[0].COMPANY__r.Name + '\n';
+            if (String.isNotBlank(swoList[0].COMPANY__r.Name)) {
+                QuotesPage.BILL_TO__c = swoList[0].COMPANY__r.Name + '\n';
+                QuotesPage.SHIP_TO__c = swoList[0].COMPANY__r.Name + '\n';
+            }
+            // 瀹㈡埛鍦板潃
+            if (String.isNotBlank(swoList[0].COMPANY__r.Address1D__c)) {
+                QuotesPage.BILL_TO__c +=  swoList[0].COMPANY__r.Address1D__c + '\n';
+                QuotesPage.SHIP_TO__c +=  swoList[0].COMPANY__r.Address1D__c + '\n';
+            } else if (String.isNotBlank(swoList[0].COMPANY__r.Address1__c)) {
+                QuotesPage.BILL_TO__c +=  swoList[0].COMPANY__r.Address1__c + '\n';
+                QuotesPage.SHIP_TO__c +=  swoList[0].COMPANY__r.Address1__c + '\n';
+            }
+            // 鑱旂郴浜哄悕绉�
+
+            if (String.isNotBlank(swoList[0].CONTACT__r.Name)) {
+                QuotesPage.BILL_TO__c += swoList[0].CONTACT__r.Name + '\n';
+                QuotesPage.SHIP_TO__c += swoList[0].CONTACT__r.Name + '\n';
+            }
+            // 鑱旂郴浜烘墜鏈�
+            if (String.isNotBlank(swoList[0].CONTACT__r.MobilePhoneD__c)) {
+                QuotesPage.BILL_TO__c +=  swoList[0].CONTACT__r.MobilePhoneD__c + '\n';
+                QuotesPage.SHIP_TO__c +=  swoList[0].CONTACT__r.MobilePhoneD__c + '\n';
+            } else if (String.isNotBlank(swoList[0].CONTACT__r.MobilePhone)) {
+                QuotesPage.BILL_TO__c +=  swoList[0].CONTACT__r.MobilePhone + '\n';
+                QuotesPage.SHIP_TO__c +=  swoList[0].CONTACT__r.MobilePhone + '\n';
+            }
+            // 鑱旂郴浜虹數璇�
+            if (String.isNotBlank(swoList[0].CONTACT__r.PhoneD__c)) {
+                QuotesPage.BILL_TO__c +=  swoList[0].CONTACT__r.PhoneD__c + '\n';
+                QuotesPage.SHIP_TO__c +=  swoList[0].CONTACT__r.PhoneD__c + '\n';
+            } else if (String.isNotBlank(swoList[0].CONTACT__r.Phone)) {
+                QuotesPage.BILL_TO__c +=  swoList[0].CONTACT__r.Phone + '\n';
+                QuotesPage.SHIP_TO__c +=  swoList[0].CONTACT__r.Phone + '\n';
+            }
+            // 鏁版嵁鎷兼帴  BILL TO/BILL TO End
+
+            QuotesPage.CONTACT_NAME__c =  swoList[0].CONTACT__c;
+            QuotesPage.CONTACT_PHONE__c = swoList[0].CONTACT__r.PhoneD__c;
+            QuotesPage.COMPANY__c = swoList[0].COMPANY__c;
+            QuotesPage.DATE__c = Date.today();
+            QuotesPage.STATUS__c = 'Qualifying';
+            QuotesPage.PROBABILITY__c = 25;
+        }
+
+        if (String.isNotBlank(Id)) {
+
+            List<Quotes__c> quotesList = new List<Quotes__c>();
+            quotesList = [SELECT  Id, Name, BILLING_SCHEDULE__c, BILL_TO__c, SHIP_TO__c, BILL_TO_SELECT__c, CATEGORY_1_INDUSTRY_SO__c, CATEGORY_2_USE_SO__c, COLLECTION_STATUS__c, CONTACT_EMAIL__c, CONTACT_FAX__c, CONTACT_NAME__c, CONTACT_PHONE__c, CONTRACT_NAME__c, CURRENCY__c, DATE__c, DISCOUNT_ITEM__c, DISCOUNT_ITEM_F__c, DISCOUNT_WORKFLOW_TYPE__c, EST_EXTENDED_COST__c, EST_GROSS_PROFIT__c, EST_GROSS_PROFIT_PERCENT__c, ESTIMATE__c, EXP_CLOSE__c, EXPIRES__c, FDA_REPORT_COMPLETE__c, GOVERNMENT_ORDER__c, GSA_ORDER__c, INCOTERM__c, INITIATE_APPROVAL_ROUTING__c, INVOICE_MESSAGING__c, IS_SELLER_IMPORTER_OF_RECORD__c, LEAD_SOURCE__c, LEAD_TIME__c, LOCATION__c, NO_CHARGE_TYPE__c, notSaveEmail__c, NSN__c, ONLINE_BILLING__c, ONLINE_BILLING_ADDRESS__c, OPPORTUNITY__c, ORDER_TYPE__c, PKMS_PO_FOR_RECEIPT__c, PO__c, PROBABILITY__c, PRODUCT_SEGMENT__c, QUOTE_TITLE__c, RATE__c, RepairPart__c, REVISION_NEEDED__c, RMA_NOTES__c, COMPANY__c, SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE__c, SALES_TEAM_AUTO_ASSIGN_ON_SAVE__c, SELECT_MESSAGE__c, SHIPPING_CARRIER__c, SHIPPING_COST__c, SHIPPING_TAX_CODE__c, SHIPPING_TAX_RATE__c, SHIP_TO_ENTITY_USE_CODE__c, SHIP_TO_SELECT__c, SHIP_VIA__c, STATUS__c, SUBSIDIARY__c, SUBTOTAL__c, SWO__c, SWOName__c, SWO_NUMBER__c, SWO_PART_NUMBERS__c, SWO_SERIAL__c, SWOStatus__c, TAX_ID__c, TAX_OVERRIDE__c, TERMS__c, TERMS_OVERRIDE__c, THROW_MESSAGE__c, TOTAL_TRANSACTION_ITEM_WEIGHT_KGS__c, VERTICAL_MARKET_SEGMENT_SO__c, QuotesType__c, CUSTOMER_MESSAGE__c, TOTAL__c, BILL_TO_ENTITY_USE_CODE__c, COMPANYId__c, COMPANYName__c, DISCOUNT_STATUS__c, DISCOUNT_STATUS_ROUTING__c, TAX_CODE__c, TAX_RATE__c, TAX__c, DISCOUNT__c, SWOStatusMark__c  FROM Quotes__c WHERE Id = :Id];
+            if (quotesList.size() > 0) {
+                QuotesPage = quotesList[0];
+            }
+            List<Quotes_item__c> quotesItemList = new List<Quotes_item__c>();
+            quotesItemList = [SELECT Id, Name, QuotesItemName__c, PART_NUMBERNew__c, ON_HAND__c,
+                              QUANTITY__c , QuotesItemProduct__c,ProductDESCRIPTION__c, PRICE_LEVEL__c, RATE__c, AMOUNT__c ,
+                              PRE_APPROVED_DISCOUNT__c, DISCOUNTED_RATE__c, EST_COST__c ,
+                              EST_GROSS_MARGIN__c, TAX_CODE__c, TAX_RATE__c, TAX_AMT__c , GROSS_AMT__c,
+                              LOCATION__c, OPTIONS__c, EXPECTED_SHIP_DATE__c , ITEM_NOTE__c, SERIALIZED__c, ITEM_WEIGHT__c,
+                              SWOName__c, RE_INVOICE_CREDIT_AMOUNT__c , DISCOUNTED_RATE_USD__c, ITEM_TYPE__c,
+                              NIS__c, CQP_AD_HOC_PRODUCT__c ,  ESTIMATED_TOTAL_WEIGHT__c,
+                              SHIP_TO_ENTITY_USE_CODE__c , EQ_NUMBER__c, HUNT_PRICE_VARIANCE__c,
+                              BASE_PRICE_FOR_HUNT__c , TRANSACTION_RESTRICTED_ITEM__c,
+                              TRANSACTION_RESTRICTED_ITEM_OVERRIDE__c , SERVICE_WORK_ORDER__c,
+                              productName__c, ProductOTcode__c, DESCRIPTION__c, QuotesItemProduct__r.SpecialProduct__c, QUOTE__c,LineNumber__c FROM Quotes_item__c WHERE QUOTE__c = :Id];
+            if (quotesItemList.size() > 0 ) {
+                Boolean specialQuotesItemFlag = false;
+                Map<String, Quotes_item__c> specialProductMap = new Map<String, Quotes_item__c>();
+                for (Quotes_item__c quotesItem : quotesItemList) {
+                    String quotesItemName = quotesItem.ProductOTcode__c;
+
+                    if (quotesItem.QuotesItemProduct__r.SpecialProduct__c && !'DESCRIPTION'.equals(quotesItemName)) {
+                        specialQuotesItemFlag = true;
+                        specialProductMap.put(quotesItem.Id, quotesItem);
+                        continue;
+                    }
+                    productInfoList.add(new QuotesItemInfo(ProductInfoListSize, quotesItem, QuotesPage));
+                    ProductInfoListSize++;
+                }
+                // 鍏朵綑 鐗规畩浜у搧鏀剧疆鍦ㄦ渶涓嬮潰
+                List<Quotes_item__c> subtotalList = new List<Quotes_item__c>();
+                if (specialQuotesItemFlag) {
+                    for (String quotesItemId : specialProductMap.keySet()) {
+
+                        Quotes_item__c quotesItem = specialProductMap.get(quotesItemId);
+                        String quotesItemName = quotesItem.ProductOTcode__c;
+                        if ('Service Quote Subtotal'.equals(quotesItemName)) {
+                            subtotalList.add(quotesItem);
+                            continue;
+                        }
+                        productInfoList.add(new QuotesItemInfo(ProductInfoListSize, quotesItem, QuotesPage));
+                        ProductInfoListSize++;
+                    }
+                }
+                // Service Quote Subtotal 鐗规畩浜у搧 鏀剧疆鍦ㄦ渶鍚�
+                if (subtotalList.size() > 0) {
+                    for (Quotes_item__c quotesItem : subtotalList) {
+                        productInfoList.add(new QuotesItemInfo(ProductInfoListSize, quotesItem, QuotesPage));
+                        ProductInfoListSize++;
+                    }
+                }
+                // 鍏朵綑 鐗规畩浜у搧鏀剧疆鍦ㄦ渶涓嬮潰
+
+            }
+            // Mail 椤甸潰鍒濆鍖� Start
+            List<String> mailIdList = new List<String>();
+
+            List<Attachment> attList = new List<Attachment>();
+            Map<String, List<Attachment>> attMap = new Map<String, List<Attachment>>();
+
+            Map<String, Mail_Merge__c> mailMap = new Map<String, Mail_Merge__c>([select id, FROM__c, ccName__c, SUBJECT__c, MESSAGE__c, DATE__c, toName__c, EMAIL_SENT__c from Mail_Merge__c where Quotes__c = :Id order by id]);
+
+
+            if (mailMap != null) {
+                mailIdList.addAll(mailMap.keySet());
+
+                attList =  [select id, Name, ParentId from Attachment where ParentId in :mailIdList order by ParentId, id];
+                if (attList.size() > 0) {
+                    for (Attachment att : attList) {
+                        if (attMap.containsKey(att.ParentId)) {
+                            attMap.get(att.ParentId).add(att);
+                        } else {
+                            List<Attachment> a = new List<Attachment>();
+                            a.add(att);
+                            attMap.put(att.ParentId, a);
+                        }
+                    }
+                }
+
+                for (String id : mailMap.keySet()) {
+                    if (attMap.containsKey(id)) {
+                        mailList.add(new EmailInfo(mailMap.get(id), attMap.get(id)));
+                    } else {
+                        mailList.add(new EmailInfo(mailMap.get(id), null));
+                    }
+                }
+            }
+            // Mail 椤甸潰鍒濆鍖� End
+
+        }
+        //棣栧厛鏄粠swo鍒涘缓quotes锛屾湁浜唖woid,灏辨槸鐢ㄦ柊鐨勯潤鎬佽祫婧愭樉绀虹殑鍏嶈矗鐢虫槑銆�
+        //涔嬪悗锛岀紪杈戝凡缁忓垱寤哄畬浜嗙殑quotes锛�15鍙蜂箣鍓嶅垱寤虹殑锛屾樉绀虹殑鏄棫鐨勩�傛棫鐨勫氨鏄痑ftORbef==false銆�
+        //褰撶劧锛宎ftORbef==false鍏蜂綋鎸囩殑鏄棫鐨勪篃鍙互鎸囨煡涓嶅埌鐨�(杩樻病鏈夊瓨鍏ユ暟鎹簱鐨勶紝鍒涘缓鏃�)銆�
+        if (String.isNotBlank(swoId)) {
+            aftORbef1 = true;
+        }else{
+            aftORbef1 = false;
+        }
+        System.debug('aftORbef1='+aftORbef1);
+        //濡傛灉2121骞�11鏈�15鍙蜂互鍙婁箣鍚庡垱寤虹殑quotes锛岀敤鏂扮殑鍏嶈矗鐢虫槑銆�
+        //鐢ㄤ簬灞曠ず椤甸潰NEWCreateSWOQuoteReadOnly鐨勬煡鐪嬪拰缂栬緫椤甸潰NEWCreateSWOQuote(url涓篿d)鐨勭紪杈戙��
+        List<Quotes__c> quotescreateList = new List<Quotes__c>();
+        quotescreateList = [select 
+                            Id 
+                            FROM Quotes__c 
+                            WHERE Id = :Id and CreatedDate >= 2021-11-15T00:00:00.000+0000]; 
+        if(quotescreateList.size() > 0){
+            aftORbef = true;
+        }else{
+            aftORbef = false;
+        }
+        System.debug('aftORbef='+aftORbef);
+        // Message妯℃澘 Start
+        getmessageTemplate(QuotesPage);
+        // Message妯℃澘 End
+
+        // 褰撴姤浠疯椤圭洰灏忎簬50涓椂锛岀敤绌鸿杩涜濉ˉ Start
+        if (productInfoList.size() < 50) {
+            for (Integer i = ProductInfoListSize; i <= 50; i++) {
+                Quotes_item__c quotesItem = new Quotes_item__c();
+                productInfoList.add(new QuotesItemInfo(i, quotesItem));
+            }
+        }
+        // 褰撴姤浠疯椤圭洰灏忎簬50涓椂锛岀敤绌鸿杩涜濉ˉ End
+    }
+
+    public void getmessageTemplate(Quotes__c quotes) {
+        if ('缁翠慨鎶ヤ环鍗�'.equals(QuotesPage.QuotesType__c)) {
+            QuotesPage.CUSTOMER_MESSAGE__c = '';
+            //鏃ユ湡2121骞�11鏈�15鍙蜂箣鍚庣殑,鐢ㄦ柊鐨勫厤璐g敵鏄庛��
+           if (aftORbef == true) {
+                QuotesPage.CUSTOMER_MESSAGE__c += '-缁翠慨璐ㄤ繚鍙兜鐩栦簬鏈缁翠慨鐨勯厤浠讹紝缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿�俓n';
+                Messages01 = '-缁翠慨璐ㄤ繚鍙兜鐩栦簬鏈缁翠慨鐨勯厤浠讹紝缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿��';
+            }else{
+                QuotesPage.CUSTOMER_MESSAGE__c += '-缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿�俓n';
+                Messages01 = '-缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿��';
+            } 
+            QuotesPage.CUSTOMER_MESSAGE__c += '-濡傛偍纭姝ゆ姤浠峰苟鍚屾剰缁翠慨锛屾暚璇锋偍鍦�90澶╀箣鍐呭畬鎴愪粯娆俱�傚惁鍒欐偍鐨勪华鍣ㄨ灏嗚涓烘斁寮冪淮淇紝鎴戜滑浼氫互杩愯垂鍒颁粯鐨勬柟寮忔妸 \n';
+            QuotesPage.CUSTOMER_MESSAGE__c += '浠櫒缁欐偍瀵勫洖,骞跺悜鎮ㄦ敹鍙�1000鍏冪殑妫�娴嬭垂鐢ㄣ�俓n';
+            Messages02 = '-濡傛偍纭姝ゆ姤浠峰苟鍚屾剰缁翠慨锛屾暚璇锋偍鍦�90澶╀箣鍐呭畬鎴愪粯娆俱�傚惁鍒欐偍鐨勪华鍣ㄨ灏嗚涓烘斁寮冪淮淇紝鎴戜滑浼氫互杩愯垂鍒颁粯鐨勬柟寮忔妸浠櫒缁欐偍瀵勫洖,骞跺悜鎮ㄦ敹鍙�1000鍏冪殑妫�娴嬭垂鐢ㄣ��';
+            QuotesPage.CUSTOMER_MESSAGE__c += '-鐢ㄦ埛鍦ㄦ纭鍚屾剰姝ゆ缁翠慨鎶ヤ环锛� \n';
+            Messages03 = '-鐢ㄦ埛鍦ㄦ纭鍚屾剰姝ゆ缁翠慨鎶ヤ环锛�';
+            QuotesPage.CUSTOMER_MESSAGE__c += '瀹㈡埛绛惧瓧鎴栫洊绔狅細\n';
+            Messages04 = '瀹㈡埛绛惧瓧鎴栫洊绔狅細';
+            QuotesPage.CUSTOMER_MESSAGE__c += '鏃ユ湡锛�';
+            Messages05 = '鏃ユ湡锛�';
+        } else if ('闆朵欢鎶ヤ环鍗�'.equals(QuotesPage.QuotesType__c)) {
+            QuotesPage.CUSTOMER_MESSAGE__c = '';
+            QuotesPage.CUSTOMER_MESSAGE__c += '-濂ユ灄宸存柉鏈嶅姟閮ㄥ敭鍑虹殑缁翠慨閰嶄欢纭繚涓鸿川閲忕鍚堝ゥ鏋楀反鏂弬鏁版寚鏍囩殑鏂板搧锛屽ゥ鏋楀反鏂鍞嚭鐨勭淮淇厤浠朵笉鎻愪緵淇濅慨鏈嶅姟锛屽悓鏃朵篃涓嶆彁渚涢��銆佹崲璐ф湇鍔°�傛暚璇锋偍璋ㄦ厧璐拱銆俓n';
+            Messages01 = '-濂ユ灄宸存柉鏈嶅姟閮ㄥ敭鍑虹殑缁翠慨閰嶄欢纭繚涓鸿川閲忕鍚堝ゥ鏋楀反鏂弬鏁版寚鏍囩殑鏂板搧锛屽ゥ鏋楀反鏂鍞嚭鐨勭淮淇厤浠朵笉鎻愪緵淇濅慨鏈嶅姟锛屽悓鏃朵篃涓嶆彁渚涢��銆佹崲璐ф湇鍔°�傛暚璇锋偍璋ㄦ厧璐拱銆�';
+            QuotesPage.CUSTOMER_MESSAGE__c += '-鐢ㄦ埛鍦ㄦ纭姝ゆ鎶ヤ环锛屽喅瀹氳喘涔帮細\n';
+            Messages02 = '-鐢ㄦ埛鍦ㄦ纭姝ゆ鎶ヤ环锛屽喅瀹氳喘涔帮細';
+            QuotesPage.CUSTOMER_MESSAGE__c += '瀹㈡埛绛惧瓧鎴栫洊绔狅細\n';
+            Messages03 = '瀹㈡埛绛惧瓧鎴栫洊绔狅細';
+            QuotesPage.CUSTOMER_MESSAGE__c += '鏃ユ湡锛�';
+            Messages04 = '鏃ユ湡锛�';
+        }
+    }
+
+    public PageReference Save() {
+        System.debug('QuotesPage----->' + QuotesPage);
+
+        if (String.isNotBlank(swoId)) {
+            QuotesPage.SWO__c = swoId;
+            //鏃ユ湡2121骞�11鏈�15鍙蜂箣鍚庣殑,鐢ㄦ柊鐨勫厤璐g敵鏄庛��
+            aftORbef = true;
+        }
+        if (!'Cancel'.equals(QuotesPage.STATUS__c)) {
+            // 蹇呭~瀛楁楠岃瘉
+            if (!QuotesDataCheck()) {
+                return null;
+            }
+        }
+
+        getmessageTemplate(QuotesPage);
+        Savepoint sp = Database.setSavepoint();
+        try {
+            QuotesPage.CURRENCY__c = 'Chinese Yuan';
+            if ( String.isNotBlank(QuotesPage.STATUS__c) && 'Cancel'.equals(QuotesPage.STATUS__c)) {
+                QuotesPage.InvalidData__c = true;
+            } else {
+                QuotesPage.InvalidData__c = false;
+            }
+            upsert QuotesPage;
+            Id = QuotesPage.Id;
+            // 鏂板鎴栧彉鏇存姤浠疯椤圭洰
+            List<Quotes_item__c> upsertQuotesItemList = new List<Quotes_item__c>();
+            List<String> productIdList = new List<String>();
+            Decimal quotesSUBTOTAL = 0;
+            Decimal tAX_AMTSUBTOTAL = 0;
+            Decimal tAX_AMTSUBTOTAL1 = 0;
+            Decimal tAX_RATE = 0 ;
+            Map<String, Quotes_item__c> specialMap = new Map<String, Quotes_item__c>();
+            Quotes_item__c subtotalQuotesItem = new Quotes_item__c();
+
+            List<Quotes_item__c> delectQuotesItemList = new List<Quotes_item__c>();
+            
+            delectQuotesItemList = [SELECT Id, Name,LineNumber__c FROM Quotes_item__c WHERE QUOTE__c = :Id];
+
+            Integer lineNumber = 1;
+            System.debug('productInfoList--->' + productInfoList);
+            for (QuotesItemInfo QuotesItemInfo : productInfoList) {
+                // 浜у搧鍚嶇О 涓虹┖ 骞朵笖 鎶ヤ环琛岄」鐩甀d 涓嶄负绌猴紝鍒犻櫎
+                if (String.isBlank(QuotesItemInfo.productName) && String.isNotBlank(QuotesItemInfo.quotesItemId)) {
+                    continue;
+                }
+
+                if (String.isBlank(QuotesItemInfo.productName)) {
+                    continue;
+                }
+
+                if (String.isNotBlank(QuotesItemInfo.productName) &&
+                        (String.isBlank(QuotesItemInfo.quotesItemId) && String.isBlank(QuotesItemInfo.productId))) {
+                    continue;
+                }
+
+                Quotes_item__c quotesItem = new Quotes_item__c();
+                
+                quotesItem = QuotesItemInfo.quotesItemINFO;
+                quotesItem.Id = null;//QuotesItemInfo.quotesItemId;
+                quotesItem.LineNumber__c = QuotesItemInfo.lineNumber;
+                // 浜у搧鍚嶇О 涓嶄负绌� 骞朵笖 浜у搧Id 涓嶄负绌� 鏂板锛�
+                if (String.isNotBlank(QuotesItemInfo.productId)) {
+                    quotesItem.QuotesItemProduct__c = QuotesItemInfo.productId;
+                    quotesItem.QUOTE__c = Id;
+
+                }
+                
+
+                if ('Service Quote Subtotal'.equals(QuotesItemInfo.productName)) {
+                    subtotalQuotesItem = quotesItem;
+
+                    continue;
+                }
+
+                upsertQuotesItemList.add(quotesItem);
+                if (specialProductMap.containsKey(QuotesItemInfo.productName) && !'Service Quote Labour'.equals(QuotesItemInfo.productName)) {
+                    quotesItem.AMOUNT__c = 0;
+                    continue;
+                }
+
+
+
+                quotesItem.CURRENCY__c = QuotesPage.CURRENCY__c;
+                quotesItem.AMOUNT__c =  QuotesItemInfo.quotesItemINFO.RATE__c  *  QuotesItemInfo.quotesItemINFO.QUANTITY__c;
+                quotesSUBTOTAL += quotesItem.AMOUNT__c;
+                if (QuotesPage.RATE__c == -500) {
+                    tAX_AMTSUBTOTAL += quotesItem.TAX_AMT__c + (-500 * QuotesItemInfo.quotesItemINFO.TAX_RATE__c) / 100;
+                } else {
+                    tAX_AMTSUBTOTAL += quotesItem.TAX_AMT__c;
+                }
+                tAX_AMTSUBTOTAL1 += quotesItem.TAX_AMT__c;
+            }
+
+            if (delectQuotesItemList.size() >0) {
+                delete delectQuotesItemList;
+            }
+
+            // 鏂板鎴栧彉鏇存姤浠疯椤圭洰
+            if (upsertQuotesItemList.size() > 0 ) {
+                Quotes__c updateQuotes = new Quotes__c();
+                updateQuotes.Id = Id;
+                updateQuotes.SUBTOTAL__c = quotesSUBTOTAL;
+
+                if (QuotesPage.RATE__c != -500) {
+                    updateQuotes.TAX__c = tAX_AMTSUBTOTAL * (100 + QuotesPage.RATE__c) / 100;
+                    updateQuotes.DISCOUNT__c = (quotesSUBTOTAL * QuotesPage.RATE__c) / 100;
+                } else {
+                    updateQuotes.DISCOUNT__c = -500;
+                    updateQuotes.TAX__c = tAX_AMTSUBTOTAL; //+ (-500 * tAX_RATE)/100;
+                }
+
+                updateQuotes.TOTAL__c = updateQuotes.SUBTOTAL__c + updateQuotes.DISCOUNT__c + updateQuotes.TAX__c ;
+                if (String.isNotBlank(subtotalQuotesItem.QUOTE__c)) {
+                    subtotalQuotesItem.AMOUNT__c = quotesSUBTOTAL;
+                    subtotalQuotesItem.TAX_AMT__c = tAX_AMTSUBTOTAL1;
+                    subtotalQuotesItem.GROSS_AMT__c = updateQuotes.SUBTOTAL__c + updateQuotes.TAX__c;
+                    upsertQuotesItemList.add(subtotalQuotesItem);
+                }
+
+                upsert upsertQuotesItemList;
+
+                update updateQuotes;
+
+
+            }
+
+            
+        }catch (Exception e) {
+            ApexPages.addMessages(e);
+            Database.rollback(sp);
+            
+            return null;
+        }
+        return UnabletoEdit();
+    }
+
+    public PageReference Editbtn() {
+        String url = '/apex/NEWCreateSWOQuote?Id=' + Id;
+        PageReference  ref = new Pagereference(url);
+        ref.setRedirect(true);
+        return ref;
+    }
+
+    // 鍒锋柊SWO鎶ヤ环
+    public PageReference UnabletoEdit() {
+        String url = '/apex/NEWCreateSWOQuoteReadOnly?Id=' + Id;
+        PageReference  ref = new Pagereference(url);
+        ref.setRedirect(true);
+        return ref;
+    }
+    //蹇呭~瀛楁妫�鏌�
+    public Boolean QuotesDataCheck() {
+        Boolean result = true;
+        String errormessage = '';
+        if (QuotesPage.DATE__c == null) {
+            errormessage = errorMessage('DATE');
+            // QuotesPage.DATE__c.addError('DATE Can\'t be empty');
+            QuotesPage.DATE__c.addError(errormessage);
+
+            result = false;
+        }
+        // LEAD_TIME__c
+        if (String.isBlank(QuotesPage.LEAD_TIME__c)) {
+            errormessage = errorMessage('LEAD TIME');
+            QuotesPage.LEAD_TIME__c.addError(errormessage);
+            result = false;
+        }
+        if (String.isBlank(QuotesPage.STATUS__c)) {
+            errormessage =  errorMessage('STATUS');
+            QuotesPage.STATUS__c.addError(errormessage);
+            result = false;
+        }
+
+        if (String.isBlank(QuotesPage.LOCATION__c)) {
+            errormessage =  errorMessage('LOCATION');
+            QuotesPage.LOCATION__c.addError(errormessage);
+            result = false;
+        }
+
+        if (String.isBlank(QuotesPage.TERMS__c)) {
+            errormessage =  errorMessage('TERMS');
+            QuotesPage.TERMS__c.addError(errormessage);
+            result = false;
+        }
+
+        if (QuotesPage.EXPIRES__c == null) {
+            errormessage =  errorMessage('EXPIRES');
+            QuotesPage.EXPIRES__c.addError(errormessage);
+            result = false;
+        }
+
+        if (QuotesPage.EXP_CLOSE__c == null) {
+            errormessage =  errorMessage('EXP. CLOSE');
+            QuotesPage.EXP_CLOSE__c.addError(errormessage);
+            result = false;
+        }
+
+        if (String.isBlank(QuotesPage.ORDER_TYPE__c)) {
+            errormessage =  errorMessage('ORDER TYPE');
+            QuotesPage.ORDER_TYPE__c.addError(errormessage);
+            result = false;
+        }
+
+        for (QuotesItemInfo QuotesItemInfo : productInfoList) {
+            String productName = QuotesItemInfo.productName;
+            if (String.isBlank(productName)) {
+                continue;
+            }
+            if (String.isNotBlank(productName) &&
+                    (String.isBlank(QuotesItemInfo.quotesItemId) && String.isBlank(QuotesItemInfo.productId))) {
+
+                continue;
+            }
+            Boolean specialProduct = false;
+            // if (String.isNotBlank(productName) &&
+            //         ('Service Quote Labour'.equals(productName) ||
+            //          'DESCRIPTION'.equals(productName) ||
+            //          'Service Quote Subtotal'.equals(productName) ||
+            //          'Onsite Support Fee'.equals(productName) ||
+            //          'Transportation'.equals(productName) ||
+            //          'Payment Info'.equals(productName))) {
+
+            //     specialProduct = true;
+            // }
+            if (specialProductMap != null && specialProductMap.size() > 0 && specialProductMap.containsKey(productName)) {
+                specialProduct = true;
+            }
+
+            String descriptionStr = QuotesItemInfo.quotesItemINFO.DESCRIPTION__c;
+            if ('Payment Info'.equals(productName) &&
+                    String.isNotBlank(descriptionStr)) {
+                descriptionStr = descriptionStr.replaceAll('锛�', ';');
+                if (descriptionStr.indexOf(';') != -1) {
+                    QuotesItemInfo.quotesItemINFO.DESCRIPTION__c = '';
+                    for (String descriptionLine : descriptionStr.split(';')) {
+                        QuotesItemInfo.quotesItemINFO.DESCRIPTION__c += descriptionLine + ';\n';
+                    }
+                } else {
+                    errormessage = 'Quotes Item No [ ' + QuotesItemInfo.lineNumber + ' ] DESCRIPTION Error';
+                    QuotesItemInfo.quotesItemINFO.DESCRIPTION__c.addError(errormessage);
+                    result = false;
+                }
+            }
+
+            if (String.isNotBlank(productName) &&
+                    ((String.isNotBlank(QuotesItemInfo.quotesItemId) || String.isNotBlank(QuotesItemInfo.productId)))) {
+                if (!specialProduct) {
+                    if (String.isBlank(QuotesItemInfo.quotesItemINFO.TAX_CODE__c)) {
+                        errormessage =  errorMessage('Quotes Item No [ ' + QuotesItemInfo.lineNumber + ' ] TAX CODE');
+                        QuotesItemInfo.quotesItemINFO.TAX_CODE__c.addError(errormessage);
+                        result = false;
+                    }
+                    if (String.isBlank(QuotesItemInfo.quotesItemINFO.LOCATION__c)) {
+                        errormessage =  errorMessage('Quotes Item No [ ' + QuotesItemInfo.lineNumber + ' ] LOCATION');
+                        QuotesItemInfo.quotesItemINFO.LOCATION__c.addError(errormessage);
+                        result = false;
+                    }
+                }
+
+                if (QuotesItemInfo.quotesItemINFO.QUANTITY__c == null ||
+                        QuotesItemInfo.quotesItemINFO.QUANTITY__c == 0) {
+                    errormessage =  errorMessage('Quotes Item No [ ' + QuotesItemInfo.lineNumber + ' ] QUANTITY');
+                    errormessage += ' OR Can not be Zero';
+                    QuotesItemInfo.quotesItemINFO.QUANTITY__c.addError(errormessage);
+                    result = false;
+                }
+
+            }
+
+        }
+
+        return result;
+    }
+
+    public String errorMessage(String type) {
+        String result = type + ' can not be empty';
+        return result;
+    }
+
+    public class QuotesItemInfo {
+        public String productId {get; set;}//浜у搧Id
+        public Quotes_item__c quotesItemINFO {get; set;} //鎶ヤ环琛岄」鐩�
+        public String quotesItemName {get; private set;}
+        public String quotesItemId {get; set;} //鎶ヤ环琛岄」鐩甀d
+        public Decimal lineNumber {get; set;}//琛屽彿
+        public Decimal quantity {get; set;}//鏁伴噺
+        public Decimal price {get; set;} //鍗曚环
+        public Decimal totalPrice {get; set;} //鎬讳环
+        public String productCode {get; set;} //OT Code
+        public String description {get; set;} //鎻忚堪
+        public String partNumber {get; set;} //PART_NUMBER
+        public Decimal productInventory {get; set;}//搴撳瓨
+        public String productName {get; set;}//浜у搧鍚嶇О
+        public String on_hand {get; set;}
+
+        public QuotesItemInfo (Integer productNo, Quotes_item__c quotesItem) {
+            lineNumber = productNo;
+            quotesItemINFO = quotesItem;
+            quotesItemId = quotesItem.Id;
+        }
+        public QuotesItemInfo ( Integer productNo, Product2 product, Integer productQuantity, Quotes__c quotes, Quotes_item__c quotesItem) {
+            lineNumber = productNo;//quotesItem.LineNumber__c;
+            quotesItemINFO = quotesItem;
+            quantity = productQuantity;
+            productCode = product.ProductCode;
+            description = product.Description;
+            //partNumber  = product.PART_NUMBER__c;
+            //productInventory = product.ProductInventory__c;
+            productName = product.Name;
+            productId = product.Id;
+            price = 0;
+            totalPrice = 0;
+            quotesItemId = quotesItem.Id;
+
+        }
+        public QuotesItemInfo ( Integer productNo, Quotes_item__c quotesItem, Quotes__c quotes) {
+            quotesItemINFO = quotesItem;
+            quotesItemName = quotesItem.Name;
+            lineNumber = productNo;//quotesItem.LineNumber__c;//productNo;
+            quantity = quotesItem.QUANTITY__c;
+            productName = quotesItem.productName__c;
+            productId = quotesItem.QuotesItemProduct__c;
+            quotesItemId = quotesItem.Id;
+        }
+
+    }
+
+    public class EmailInfo {
+
+        public Mail_Merge__c mm {get; set; }
+        public List<Attachment> attList {get; set; }
+        public String haveAtt {get; set;}
+        public EmailInfo() {
+
+        }
+        public EmailInfo(Mail_Merge__c mm_in, List<Attachment> attList_in) {
+            mm = mm_in;
+            if (attList_in == null || attList_in.size() == 0) {
+                haveAtt = 'No';
+                attList = new List<Attachment>();
+            } else {
+                attList = attList_in;
+                haveAtt = 'Yes';
+            }
+        }
+
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/NEWCreateSWOQuoteController.cls-meta.xml b/scr/classes/NEWCreateSWOQuoteController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NEWCreateSWOQuoteController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NEWCreateSWOQuoteControllerTest.cls b/scr/classes/NEWCreateSWOQuoteControllerTest.cls
new file mode 100644
index 0000000..07d5e1f
--- /dev/null
+++ b/scr/classes/NEWCreateSWOQuoteControllerTest.cls
@@ -0,0 +1,288 @@
+@isTest
+private class NEWCreateSWOQuoteControllerTest {
+    static testMethod void QuotesIdIsNull() {
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'Service Quote Labour';
+        product2.IsActive = true;
+        product2.ProductCode = 'Service Quote Labour';
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.SpecialProduct__c = true;
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'Service Quote Subtotal';
+        product3.IsActive = true;
+        product3.ProductCode = 'Service Quote Subtotal';
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.SpecialProduct__c = true;
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product3;
+
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        swo.ITEM__c = product1.Id;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+        RepairPart__c repairPart = new RepairPart__c();
+        repairPart.SWO_ID__c = swo.Id;
+        repairPart.Product__c = product1.Id;
+        repairPart.QUANTITY__c = 22;
+        insert repairPart;
+
+
+        PageReference page = new PageReference('/apex/NEWCreateSWOQuote?swoId='+swo.Id);
+        System.Test.setCurrentPage(page);
+        NEWCreateSWOQuoteController controller = new NEWCreateSWOQuoteController();
+        controller.init();
+        controller.Save();    
+    }
+
+    static testMethod void QuotesIdIsNotNull() {
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'DESCRIPTION';
+        product1.IsActive = true;
+        product1.ProductCode = 'DESCRIPTION';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'Payment Info';
+        product2.IsActive = true;
+        product2.ProductCode = 'Payment Info';
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product2.SpecialProduct__c = true;
+        product2.Description = 'Test01锛汿est02';
+
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'Service Quote Subtotal';
+        product3.IsActive = true;
+        product3.ProductCode = 'Service Quote Subtotal';
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.SpecialProduct__c = true;
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product3;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        // swo.ITEM__c = product1.Id;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        insert quotes;
+
+        Quotes_item__c quotesItem =  new Quotes_item__c();
+        quotesItem.QUOTE__c =  quotes.Id;
+        quotesItem.QuotesItemProduct__c = product1.Id;
+        insert quotesItem;
+
+        Quotes_item__c quotesItem1 =  new Quotes_item__c();
+        quotesItem1.QUOTE__c =  quotes.Id;
+        quotesItem1.QuotesItemProduct__c = product2.Id;
+        quotesItem1.DESCRIPTION__c = 'Test01锛汿est02';
+        insert quotesItem1;
+
+        Quotes_item__c quotesItem2 =  new Quotes_item__c();
+        quotesItem2.QUOTE__c =  quotes.Id;
+        quotesItem2.QuotesItemProduct__c = product3.Id;
+        insert quotesItem2;
+
+        
+        PageReference page = new PageReference('/apex/NEWCreateSWOQuote?Id='+quotes.Id);
+        System.Test.setCurrentPage(page);
+        NEWCreateSWOQuoteController controller = new NEWCreateSWOQuoteController();
+        controller.init();
+        controller.Save(); 
+
+
+    }
+
+
+    static testMethod void QuotesSave() {
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'DESCRIPTION';
+        product1.IsActive = true;
+        product1.ProductCode = 'DESCRIPTION';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.SpecialProduct__c = true;
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'Payment Info';
+        product2.IsActive = true;
+        product2.ProductCode = 'Payment Info';
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product2.SpecialProduct__c = true;
+        product2.Description = 'Test01锛汿est02';
+
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'Service Quote Subtotal';
+        product3.IsActive = true;
+        product3.ProductCode = 'Service Quote Subtotal';
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.SpecialProduct__c = true;
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product3;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        // swo.ITEM__c = product1.Id;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        quotes.DATE__c = Date.today();
+        quotes.LEAD_TIME__c = '1 week';
+        quotes.STATUS__c = 'Qualifying';
+        quotes.LOCATION__c = 'China - Service';
+        quotes.TERMS__c = '1% 10 Net 30';
+        quotes.EXPIRES__c = Date.today();
+        quotes.EXP_CLOSE__c = Date.today();
+        quotes.RATE__c = 333;
+        quotes.ORDER_TYPE__c = 'LS Core Clinical';
+
+        insert quotes;
+
+        Quotes_item__c quotesItem =  new Quotes_item__c();
+        quotesItem.QUOTE__c =  quotes.Id;
+        quotesItem.QuotesItemProduct__c = product1.Id;
+        quotesItem.QUANTITY__c = 22;
+        quotesItem.AMOUNT__c = 22;
+        quotesItem.RATE__c = 222;
+        quotesItem.TAX_AMT__c = 222;
+        insert quotesItem;
+
+        Quotes_item__c quotesItem1 =  new Quotes_item__c();
+        quotesItem1.QUOTE__c =  quotes.Id;
+        quotesItem1.QuotesItemProduct__c = product2.Id;
+        quotesItem1.DESCRIPTION__c = 'Test01锛汿est02';
+        quotesItem1.QUANTITY__c = 22;
+        quotesItem1.AMOUNT__c = 22;
+        quotesItem1.RATE__c = 222;
+        quotesItem1.TAX_AMT__c = 222;
+        insert quotesItem1;
+
+        Quotes_item__c quotesItem2 =  new Quotes_item__c();
+        quotesItem2.QUOTE__c =  quotes.Id;
+        quotesItem2.QuotesItemProduct__c = product3.Id;
+        quotesItem2.QUANTITY__c = 22;
+        quotesItem2.AMOUNT__c = 22;
+        quotesItem2.RATE__c = 222;
+        quotesItem2.TAX_AMT__c = 222;
+        insert quotesItem2;
+
+        Mail_Merge__c  mailMerge = new Mail_Merge__c(); 
+        mailMerge.Quotes__c = quotes.Id;
+        insert mailMerge;
+        
+        PageReference page = new PageReference('/apex/NEWCreateSWOQuote?Id='+quotes.Id);
+        System.Test.setCurrentPage(page);
+        NEWCreateSWOQuoteController controller = new NEWCreateSWOQuoteController();
+        controller.init();
+        controller.UnabletoEdit();
+        controller.Editbtn();
+        controller.Save(); 
+
+
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NEWCreateSWOQuoteControllerTest.cls-meta.xml b/scr/classes/NEWCreateSWOQuoteControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NEWCreateSWOQuoteControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NFMHttpCalloutMock.cls b/scr/classes/NFMHttpCalloutMock.cls
new file mode 100644
index 0000000..38f9b29
--- /dev/null
+++ b/scr/classes/NFMHttpCalloutMock.cls
@@ -0,0 +1,13 @@
+@isTest
+global class NFMHttpCalloutMock implements HttpCalloutMock {
+    // 瀹炵幇杩欎釜鎺ュ彛鏂规硶
+    global HTTPResponse respond(HTTPRequest request) {
+        // 鍒涘缓涓�涓亣鐨勫洖搴�
+        HttpResponse response = new HttpResponse();
+        response.setHeader('Content-Type', 'application/json');
+        response.setBody('{"expires_in":"2032/12/21","access_token":"32defefe"}');
+
+        response.setStatusCode(200);
+        return response; 
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NFMHttpCalloutMock.cls-meta.xml b/scr/classes/NFMHttpCalloutMock.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NFMHttpCalloutMock.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NFMUtil.cls b/scr/classes/NFMUtil.cls
new file mode 100644
index 0000000..5e80a26
--- /dev/null
+++ b/scr/classes/NFMUtil.cls
@@ -0,0 +1,319 @@
+/**
+ * PI銇ㄣ伄閫氫俊鏅傘�佷娇銇嗗叡閫氭鑳�
+ * 鏃ヤ粯澶夋彌銆併儭銉笺儷閫佷俊銇伄
+ */
+global class NFMUtil {
+
+    public static Integer MaxLogColumnLength = 131072;
+    public static String DummyAssetProfix = '涓嶅彲鐢細';
+    public static String Authorization = 'Basic T0NNX1NGX1VTRVI6b2Ntc2ZkYzg0MDI=';
+    public static String CLIENT_CERT_NAME = null;
+    public static String SBG001_ENDPOINT = null;
+    public static String SBG007_ENDPOINT = null;
+    public static String SBG027_ENDPOINT = null;
+
+    public static String CBPR_Auth_Sap = null;
+
+    static {
+        if (isSandbox()) {
+            System.debug('sandbox');
+            CBPR_Auth_Sap = 'Basic U0ZEQ19XU1VTRVI6cG9xMTIzNDU=';
+            CLIENT_CERT_NAME = 'owdc_test';
+            // SBG001_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
+            //SBG007_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
+            //SBG027_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
+            //SBG027_ENDPOINT = 'https://wdp.olympus.com.cn:44301/RESTAdapter/SBG027';
+            // SBG027_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG027';
+            // SBG001_ENDPOINT = 'http://wdp.olympus.com.cn:44301/RESTAdapter/SBG001';
+            //SBG001_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
+            SBG001_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG001';
+            //SBG007_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
+            SBG007_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG007';
+            //SBG027_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
+            //SBG027_ENDPOINT = 'https://wdp.olympus.com.cn:44301/RESTAdapter/SBG027';
+            SBG027_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG027';
+            
+        } else {
+            CBPR_Auth_Sap = 'Basic U0ZEQ19XU1VTRVI6cG9wMTIzNDU=';
+            System.debug('production');
+            CLIENT_CERT_NAME = 'sfdc_ocn';
+            //SBG001_ENDPOINT = 'https://owdc.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_P&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
+            SBG001_ENDPOINT = 'https://wdp.olympus.com.cn:44302/RESTAdapter/SBG001';
+            //SBG007_ENDPOINT = 'https://owdc.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_P&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
+            SBG007_ENDPOINT = 'https://wdp.olympus.com.cn:44302/RESTAdapter/SBG007';
+            //SBG027_ENDPOINT = 'https://owdc.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_P&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
+            
+            SBG027_ENDPOINT = 'https://wdp.olympus.com.cn:44302/RESTAdapter/SBG027';
+        }
+    }
+    
+    // 鍙椾俊鐢�
+    global class Monitoring {
+        webservice String Tag;
+        webservice String Sender;
+        webservice String Receiver;
+        webservice String MessageType;
+        webservice String MessageGroupNumber;
+        webservice String NumberOfRecord;
+        webservice String TransmissionDateTime;
+        webservice String Text;
+    }
+
+    /**
+     * @return yyyyMMdd 銇棩浠樻枃瀛楀垪
+     */
+    public static String formatDate2Str(Date dt) {
+        String rtn = null;
+        if (dt == null) {
+            return rtn;
+        }
+        rtn = String.valueOf(dt);
+        rtn = rtn.replaceAll('-', '');
+        if (rtn >= '40001231') {
+            rtn = '99991231';
+        } else if (rtn < '19000101') {
+            rtn = '19000101';
+        }
+        return rtn;
+    }
+
+    public static Date parseStr2DateTimeDate(String pDateTime) {
+        if (pDateTime == null || pDateTime.length() != 14) {
+            return null;
+        }
+        return parseStr2Date(pDateTime.substring(0, 8));
+    }
+    public static Datetime parseStr2DateTime(String pDateTime) {
+        if (pDateTime == null || pDateTime.length() != 14) {
+            return null;
+        }
+        return parseStr2DateTime(pDateTime.substring(0, 8), pDateTime.substring(8, 14));
+    }
+    public static Datetime parseStr2DateTime(String pDate, String pTime) {
+        Datetime rtn = null;
+        try {
+            if (pDate == null || pDate.length() != 8) {
+                return rtn;
+            } else if (pDate > '40001231') {
+                pDate = '40001231';
+            } else if (pDate < '19000101') {
+                pDate = '19000101';
+            }
+            if (pDate == '19000101') {
+                return null;
+            }
+            rtn = Datetime.newinstance(
+                    Integer.valueOf(pDate.substring(0, 4)),
+                    Integer.valueOf(pDate.substring(4, 6)),
+                    Integer.valueOf(pDate.substring(6, 8)),
+                    Integer.valueOf(pTime.substring(0, 2)),
+                    Integer.valueOf(pTime.substring(2, 4)),
+                    Integer.valueOf(pTime.substring(4, 6))
+            );
+        } catch (Exception ex) {
+            System.debug(Logginglevel.ERROR, 'NFMUtil#parseStr2DateTime(' + pDate + ', ' + pTime + ')' + ex.getMessage());
+        }
+        return rtn;
+    }
+    /**
+     * @param pStr yyyyMMdd 銇棩浠樻枃瀛楀垪
+     */
+    public static Date parseStr2Date(String pStr) {
+        return parseStr2Date(pStr, true);
+    }
+    /**
+     * @param pStr         yyyyMMdd 銇棩浠樻枃瀛楀垪
+     * @param changeToNull 19000101浠ヤ笅銇牬鍚� null 銇鎻涖仚銈嬨亱銇┿亞銇�
+     */
+    public static Date parseStr2Date(String pStr, boolean changeToNull) {
+        Date rtn = null;
+        try {
+            if (pStr == null || pStr.length() != 8) {
+                return rtn;
+            } else if (pStr > '40001231') {
+                pStr = '40001231';
+            } else if (pStr < '19000101') {
+                pStr = '19000101';
+            }
+            if (pStr == '19000101' && changeToNull) {
+                return null;
+            }
+            rtn = Date.newinstance(
+                    Integer.valueOf(pStr.substring(0, 4)),
+                    Integer.valueOf(pStr.substring(4, 6)),
+                    Integer.valueOf(pStr.substring(6, 8))
+            );
+        } catch (Exception ex) {
+            System.debug(Logginglevel.ERROR, 'NFMUtil#parseStr2Date(' + pStr + ')' + ex.getMessage());
+        }
+        return rtn;
+    }
+    
+    /**
+     * 銈傘仐key銇宮ap銇瓨鍦ㄣ仐銇亜鍫村悎銆乲ey銈掋仢銇伨銇炬埢銈�
+     */
+    public static String getMapValue(Map<String, String> transferMap, String col, String key, BatchIF_Log__c iflog) {
+        String rtn = key;
+        if (transferMap == null) {
+            return rtn;
+        }
+        if (key == null) {
+            return null;
+        }
+        if (col == null) {
+            col = '';
+        }
+        rtn = transferMap.get(col + key);
+        if (rtn == null) {
+            iflog.ErrorLog__c += 'Warning! Please check [' + col + '] can not transfer key [' + key + ']\n';
+            rtn = key;
+        }
+        return rtn;
+    }
+
+    /**
+     * 鍏堥牠銇寚瀹氭枃瀛椼倰trim
+     *
+     * @param trimChar 鎸囧畾銇椼仧trim鏂囧瓧
+     */
+    public static String trimLeft(String orgStr, String trimChar) {
+        String rtn = orgStr;
+        if (orgStr == null) {
+            return rtn;
+        }
+        if (trimChar == null) {
+            return null;
+        }
+        rtn = orgStr.replaceAll('^' + trimChar + '+(?!$)', '');
+        return rtn;
+    }
+
+    public static Boolean isSandbox() {
+        //System.debug(URL.getSalesforceBaseUrl().getHost());
+        //return URL.getSalesforceBaseUrl().getHost().left(2).equalsignorecase('cs');
+        return [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
+
+    }
+
+     public static void sendToSap(String rowDataStr, String endpoint) {
+
+        Http http = new Http();
+        HttpRequest req = new HttpRequest();
+        HTTPResponse res;
+        String resb;
+
+        req.setTimeout(120000);
+        req.setEndpoint(endpoint);
+        req.setMethod('POST');
+        req.setHeader('Authorization', CBPR_Auth_Sap);
+        req.setBody(rowDataStr);
+ 
+        res = http.send(req);
+        resb = res.getBody();
+    }
+
+    public static String sendToSapRet(String rowDataStr, String endpoint) {
+        Http http = new Http();
+        HttpRequest req = new HttpRequest();
+        HTTPResponse res;
+        String resb;
+
+        req.setTimeout(120000);
+        req.setEndpoint(endpoint);
+        req.setMethod('POST');
+        req.setHeader('Authorization', CBPR_Auth_Sap);
+        req.setBody(rowDataStr);
+ 
+        res = http.send(req);
+        resb = res.getStatus();
+        return resb;
+    }
+    public static BatchIF_Log__c makeRowData(NFMUtil.Monitoring Monitoring, String NFMType, Object NFMData) {
+        BatchIF_Log__c rowData = new BatchIF_Log__c();
+        rowData.Type__c = NFMType;
+        rowData.MessageGroupNumber__c = Monitoring.MessageGroupNumber;
+        rowData.TransmissionDateTime__c = Monitoring.TransmissionDateTime;
+        rowData.RowDataFlg__c = true;
+        rowData.Log__c = '';
+        rowData.ErrorLog__c = '';
+        String rowDataStr = JSON.serialize(NFMData);
+        if (rowDataStr.length() > 0) {
+            Integer splitIdx = 1;
+            while (rowDataStr.length() > 0) {
+                if (splitIdx == 1) {
+                    rowData.put('Log__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
+                } else if (splitIdx == 13) {
+                    rowData.ErrorLog__c = rowDataStr;
+                    break;
+                } else {
+                    rowData.put('Log' + splitIdx + '__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
+                }
+                splitIdx++;
+                rowDataStr = rowDataStr.substring((rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length()));
+            }
+        }
+        return rowData;
+    }
+    public static BatchIF_Log__c saveRowData(NFMUtil.Monitoring Monitoring, String NFMType, Object NFMData) {
+        BatchIF_Log__c rowData = new BatchIF_Log__c();
+        rowData.Type__c = NFMType;
+        rowData.MessageGroupNumber__c = Monitoring.MessageGroupNumber;
+        rowData.TransmissionDateTime__c = Monitoring.TransmissionDateTime;
+        rowData.RowDataFlg__c = true;
+        rowData.Log__c = '';
+        rowData.ErrorLog__c = '';
+        insert rowData;
+        String rowDataStr = JSON.serialize(NFMData);
+        if (rowDataStr.length() > 0) {
+            Integer splitIdx = 1;
+            while (rowDataStr.length() > 0) {
+                if (splitIdx == 1) {
+                    rowData.put('Log__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
+                } else if (splitIdx == 13) {
+                    rowData.ErrorLog__c = rowDataStr;
+                    break;
+                } else {
+                    rowData.put('Log' + splitIdx + '__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
+                }
+                splitIdx++;
+                rowDataStr = rowDataStr.substring((rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length()));
+            }
+            update rowData;
+        }
+        return rowData;
+    }
+    
+
+    public static String getRowDataStr(BatchIF_Log__c rowData) {
+        String rowDataStr = rowData.Log__c;
+        Integer splitIdx = 2;
+        while (rowData.get('Log' + splitIdx + '__c') != null && String.isBlank('' + rowData.get('Log' + splitIdx + '__c')) == false) {
+            rowDataStr += rowData.get('Log' + splitIdx + '__c');
+            splitIdx++;
+            if (splitIdx == 13) break;
+        }
+        if (String.isBlank(rowData.ErrorLog__c) == false) {
+            rowDataStr += rowData.ErrorLog__c;
+        }
+        return rowDataStr;
+    }
+    //杞崲琛ㄨ浆鎹㈠悗鐨勬暟鎹�
+    public static Map<String,String> BatchIF_Transfer(String object_API_Name) {
+
+        Map<String, String> result = new Map<String, String>();
+        List<BatchIF_Transfer__c> transferList = [select Table__c,
+                                                        Column__c,
+                                                        External_value__c,
+                                                        Internal_value__c
+                                                from BatchIF_Transfer__c
+                                                where Dropped_Flag__c = false
+                                                and Table__c = :object_API_Name];
+        for (BatchIF_Transfer__c t : transferList) {
+            result.put(t.Column__c + t.External_value__c, t.Internal_value__c);
+        }
+        return result;
+    }
+
+    public static Boolean EscapeSBG001TriggerHandler = false;
+
+}
\ No newline at end of file
diff --git a/scr/classes/NFMUtil.cls-meta.xml b/scr/classes/NFMUtil.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/NFMUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NFMUtilTest.cls b/scr/classes/NFMUtilTest.cls
new file mode 100644
index 0000000..56bb4ff
--- /dev/null
+++ b/scr/classes/NFMUtilTest.cls
@@ -0,0 +1,198 @@
+@isTest
+private class NFMUtilTest {
+
+    static testMethod void testMonitoring() {
+        NFMUtil.Monitoring Monitoring = new NFMUtil.Monitoring();
+    }
+    
+    static testMethod void testParseStr2Date() {
+        Date rtn = NFMUtil.parseStr2Date(null);
+        System.assertEquals(null, rtn);
+        
+        rtn = NFMUtil.parseStr2Date('2000');
+        System.assertEquals(null, rtn);
+        
+        rtn = NFMUtil.parseStr2Date('2000123123');
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.parseStr2Date('2000AB13');
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.parseStr2Date('20001231');
+        System.assertEquals(Date.newinstance(2000, 12, 31), rtn);
+
+        rtn = NFMUtil.parseStr2Date('99991231');
+        System.assertEquals(Date.newinstance(4000, 12, 31), rtn);
+
+        rtn = NFMUtil.parseStr2Date('40001231');
+        System.assertEquals(Date.newinstance(4000, 12, 31), rtn);
+
+        rtn = NFMUtil.parseStr2Date('40010101');
+        System.assertEquals(Date.newinstance(4000, 12, 31), rtn);
+
+        rtn = NFMUtil.parseStr2Date('00000000');
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.parseStr2Date('19000101');
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.parseStr2Date('18991231');
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.parseStr2Date('00000000', false);
+        System.assertEquals(Date.newinstance(1900, 1, 1), rtn);
+
+        rtn = NFMUtil.parseStr2Date('19000101', false);
+        System.assertEquals(Date.newinstance(1900, 1, 1), rtn);
+
+        rtn = NFMUtil.parseStr2Date('18991231', false);
+        System.assertEquals(Date.newinstance(1900, 1, 1), rtn);
+    }
+
+    static testMethod void testFormatDate2Str() {
+        String rtn = NFMUtil.formatDate2Str(null);
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(2000, 11, 22));
+        System.assertEquals('20001122', rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(1900, 01, 02));
+        System.assertEquals('19000102', rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(1900, 01, 01));
+        System.assertEquals('19000101', rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(1899, 12, 31));
+        System.assertEquals('19000101', rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(4000, 12, 30));
+        System.assertEquals('40001230', rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(4000, 12, 31));
+        System.assertEquals('99991231', rtn);
+
+        rtn = NFMUtil.formatDate2Str(Date.newinstance(4001, 1, 1));
+        System.assertEquals('99991231', rtn);
+    }
+    
+    static testMethod void testGetMapValue() {
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+
+        Map<String, String> transferMap = new Map<String, String>();
+        transferMap.put('ckey1', 'value1');
+
+        String rtn = NFMUtil.getMapValue(null, null, null, iflog);
+        System.assertEquals(null, rtn);
+        
+        rtn = NFMUtil.getMapValue(null, null, 'key', iflog);
+        System.assertEquals('key', rtn);
+
+        rtn = NFMUtil.getMapValue(transferMap, 'c', null, iflog);
+        System.assertEquals(null, rtn);
+        System.assertEquals(null, iflog.ErrorLog__c);
+
+        rtn = NFMUtil.getMapValue(transferMap, 'c', 'key', iflog);
+        System.assertEquals('key', rtn);
+        System.assertEquals(true, iflog.ErrorLog__c.indexOf('Please') >= 0);
+
+        rtn = NFMUtil.getMapValue(transferMap, 'c', 'key1', iflog);
+        System.assertEquals('value1', rtn);
+
+        rtn = NFMUtil.getMapValue(transferMap, '', 'ckey1', iflog);
+        System.assertEquals('value1', rtn);
+
+        rtn = NFMUtil.getMapValue(transferMap, null, 'ckey1', iflog);
+        System.assertEquals('value1', rtn);
+    }
+
+    static testMethod void testTrimLeft() {
+        String rtn = NFMUtil.trimLeft('AAAA70000', 'A');
+        System.assertEquals('70000', rtn);
+
+        rtn = NFMUtil.trimLeft('000070000', '0');
+        System.assertEquals('70000', rtn);
+
+        rtn = NFMUtil.trimLeft(' 000070000', '0');
+        System.assertEquals(' 000070000', rtn);
+
+        rtn = NFMUtil.trimLeft('0 00070000', '0');
+        System.assertEquals(' 00070000', rtn);
+
+        rtn = NFMUtil.trimLeft('', '0');
+        System.assertEquals('', rtn);
+
+        rtn = NFMUtil.trimLeft('0 00070000', null);
+        System.assertEquals(null, rtn);
+
+        rtn = NFMUtil.trimLeft(null, '0');
+        System.assertEquals(null, rtn);
+    }
+
+    static testMethod void testIsSandbox() {
+        Organization currOrg = [Select IsSandbox from Organization limit 1];
+        Boolean urlIsSandbox = NFMUtil.isSandbox();
+        //System.assertEquals(currOrg.IsSandbox, urlIsSandbox);
+        if (currOrg.IsSandbox) {
+            System.assertEquals('owdc_test', NFMUtil.CLIENT_CERT_NAME);
+        } else {
+            System.assertEquals('sfdc_ocn', NFMUtil.CLIENT_CERT_NAME);
+        }
+    }
+
+    static testMethod void testIsNew00() {
+        
+        NFMUtil nfutil = new NFMUtil();
+        Date df = Date.valueOf('2018-12-19');
+        nfmutil.formatDate2Str(null);
+        nfmutil.formatDate2Str(df);
+        //nfmutil.formatDate2StrSpo(null);
+        //nfmutil.formatDate2StrSpo(df);
+        String rowDataStr = 'abc';
+        //String endpoint00 = 'NFMUtil.NFM201_ENDPOINT';
+        //String endpoint01 = 'NFMUtil.NFM009_ENDPOINT';
+        
+        String endpoint00 = 'NFMUtil.SBG027_ENDPOINT';
+        
+        Test.setMock(HttpCalloutMock.class, new NFMHttpCalloutMock());
+        nfmutil.sendToSap(rowDataStr,endpoint00);
+        //nfmutil.sendToSap(rowDataStr,endpoint01);
+
+    }
+
+    static testMethod void TestgetRowDataStr() {
+        BatchIF_Log__c rowData = null;
+        String endusers = '12';
+        NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+        Monitoring.Text = '';
+        rowData = NFMUtil.makeRowData(Monitoring, 'SBG027', endusers);
+        NFMUtil.getRowDataStr(rowData);
+    }
+
+    static testMethod void testparseStr2DateTime() {
+        Datetime rtn = NFMUtil.parseStr2DateTime('201812191104');
+        rtn = NFMUtil.parseStr2DateTimeDate('20181219110400');
+        rtn = NFMUtil.parseStr2DateTime('20181219110400');
+        rtn = NFMUtil.parseStr2DateTime('20181219','110401');
+        rtn = NFMUtil.parseStr2DateTime('50001219','110401');
+        rtn = NFMUtil.parseStr2DateTime('18001219','110401');
+        //System.assertEquals(null, rtn);
+
+        //rtn = NFMUtil.parseStr2DateTime(Date.newinstance(2000, 11, 22));
+        //System.assertEquals('20001122', rtn);
+    }
+
+    static testMethod void testIsNew02() {
+        
+        NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+        Monitoring.Text = '';
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        GeDatas.GeData = new SBGITMRest.GeData[]{GeData};
+        NFMUtil.saveRowData(Monitoring, 'SBGITM', GeDatas.GeData);
+       
+    }
+
+
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/NFMUtilTest.cls-meta.xml b/scr/classes/NFMUtilTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/NFMUtilTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NetworkAccess.cls b/scr/classes/NetworkAccess.cls
new file mode 100644
index 0000000..a6e6d9e
--- /dev/null
+++ b/scr/classes/NetworkAccess.cls
@@ -0,0 +1,60 @@
+global class NetworkAccess implements Process.Plugin
+{    
+    global Process.PluginResult invoke(Process.PluginRequest request)
+    {   
+        Map<String, Object> result = new Map<String, Object>();  
+        boolean isTrustedIP = false;
+        
+        String sourceIp = (String)request.inputParameters.get('IP');
+        
+        //IP not provided, use the current session IP address
+        if(sourceIP == null || sourceIP == '')
+        {
+            Map<String,String> sessionAttributes;
+            try 
+            {
+                sessionAttributes = Auth.SessionManagement.getCurrentSession();
+            }
+            catch(Exception e)
+            {
+                result.put('IsTrusted', false);
+        
+                return new Process.PluginResult(result);
+            }
+            
+            for(string key : sessionAttributes.keySet())
+            {
+                system.debug('key: ' + key + ' value: ' + sessionAttributes.get(key));
+            }
+    
+            sourceIP = sessionAttributes.get('SourceIp');
+        }
+        
+        system.debug('SourceIP: ' + sourceIp);
+        
+        if(sourceIp != null)
+            isTrustedIP = Auth.SessionManagement.inOrgNetworkRange(sourceIP);
+         
+        result.put('IsTrusted', isTrustedIP);
+        
+        return new Process.PluginResult(result);
+    }
+
+    global Process.PluginDescribeResult describe()
+    {
+        Process.PluginDescribeResult result = new Process.PluginDescribeResult();
+        result.description='This plug-in verifies if the input IP address is in your organization trusted IP range';
+        result.tag='Identity';
+        
+        result.inputParameters = new List<Process.PluginDescribeResult.InputParameter> {
+            new Process.PluginDescribeResult.InputParameter('IP', Process.PluginDescribeResult.ParameterType.STRING, true)
+        };
+        
+        result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter> {
+            new Process.PluginDescribeResult.OutputParameter('IsTrusted',
+                Process.PluginDescribeResult.ParameterType.Boolean)
+        };
+           
+        return result;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NetworkAccess.cls-meta.xml b/scr/classes/NetworkAccess.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/NetworkAccess.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NetworkAccessTest.cls b/scr/classes/NetworkAccessTest.cls
new file mode 100644
index 0000000..3b925f7
--- /dev/null
+++ b/scr/classes/NetworkAccessTest.cls
@@ -0,0 +1,27 @@
+@isTest
+private class NetworkAccessTest
+{
+    static testMethod void inputIP() {
+     
+        NetworkAccess network = new NetworkAccess();
+        Map<String,Object> inputParams = new Map<String,Object>();
+        Map<String,Object> outputParams = new Map<String,Object>();
+         
+        inputParams.put('IP', '1.1.1.1');
+         
+        Process.PluginRequest request = new Process.PluginRequest(inputParams);
+        Process.PluginResult result;
+        result = network.invoke(request);
+        
+        System.AssertEquals(1,1);
+    }
+
+    static testMethod void describeTest() {
+
+        NetworkAccess network = new NetworkAccess();
+        Process.PluginDescribeResult result = network.describe();
+        
+        System.AssertEquals(result.inputParameters.size(), 1);
+        System.AssertEquals(result.OutputParameters.size(), 1);
+     }
+}
\ No newline at end of file
diff --git a/scr/classes/NetworkAccessTest.cls-meta.xml b/scr/classes/NetworkAccessTest.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/NetworkAccessTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewCrossHighOpportunityController.cls b/scr/classes/NewCrossHighOpportunityController.cls
new file mode 100644
index 0000000..bcd3267
--- /dev/null
+++ b/scr/classes/NewCrossHighOpportunityController.cls
@@ -0,0 +1,128 @@
+public with sharing class NewCrossHighOpportunityController {
+    public boolean hasError { get; set; }
+	public boolean isDealerPage { get; set; }
+
+	public Opportunity opp { get; set; }
+
+	public String accId { get; set; }
+	public String conId { get; set; }
+	private Account acc;
+	private Contact con;
+
+	public String baseUrl { get; set; }
+	public String rtUrl { get; set; }
+
+	public String ProductSegment { get; set; }
+
+	public NewCrossHighOpportunityController() {
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+		String path = URL.getCurrentRequestUrl().getPath();
+		if (path.indexOf('/apex') > 0) {
+			baseUrl += path.substring(0, path.indexOf('/apex'));
+		} else if (path.indexOf('production/') > 0) {
+			baseUrl += '/production';
+		}
+		rtUrl = System.currentPageReference().getParameters().get('retURL');
+		if (rtUrl == null || rtUrl == 'null') {
+			rtUrl = '';
+		}
+	}
+
+	public PageReference init() {
+		hasError = false;
+
+		accId = System.currentPageReference().getParameters().get('accid');
+		conId = System.currentPageReference().getParameters().get('conId');
+
+		List<Account> accList = [select Id, Name, ProductSegment__c,OwnerID__c from Account where Id = :accId];
+		if (accList.size() > 0) {
+			acc = accList[0];
+		}
+
+		List<Contact> conList = [select Id, Name from Contact where Id = :conId];
+		if (conList.size() > 0) {
+			con = conList[0];
+		}
+		ProductSegment = acc.ProductSegment__c;
+		isDealerPage = UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS' && acc.ProductSegment__c != 'IE' && acc.ProductSegment__c != 'RVI' && acc.RecordTypeId != System.Label.RT_SSBD_Service;
+		String dealerName = '';
+		String dealerId = '';
+		if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+			User dealerUser = [select id, DealerName__c, DealerId__c from User where id = :UserInfo.getUserId()];
+			dealerName = dealerUser.DealerName__c;
+			dealerId = dealerUser.DealerId__c;
+		}
+
+        Id recordTypeId =Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SSBD_HighendProducts').getRecordTypeId();
+        system.debug(recordTypeId);
+		opp = new Opportunity();
+		opp.RecordTypeId = recordTypeId;
+		opp.AccountId = acc.Id;
+		opp.Account = acc;
+		opp.ProductSegment__c = acc.ProductSegment__c;
+		opp.Type = 'Not Traget';
+		opp.SalesChannel__c = 'dealer';
+		opp.NewInquiryDate__c = Date.today();
+		opp.StageName = 'Prospect Created';
+		opp.CloseDate = Date.valueOf('1900-01-01');
+		//opp.OwnerId = acc.OwnerID__c;
+
+		if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+			opp.Dealer__c = dealerId;
+		}
+
+		return null;
+	}
+
+	public PageReference saveBtn() {
+		List<Opportunity> checkList = [select id, Name from Opportunity where AccountId = :opp.AccountId and Name = :opp.Name];
+		if (checkList.size() > 0) {
+			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇ュ鎴蜂笅鏈夊悕绉颁竴鏍风殑璇环锛屾槸鍚︾户缁垱寤鸿璇环锛�'));
+			hasError = true;
+		} else {
+			return saveBtnYes();
+		}
+		return null;
+	}
+
+	public PageReference saveBtnYes() {
+		system.debug('=====saveBtnYes');
+
+		Savepoint sp = Database.setSavepoint();
+		try {
+			//娴嬭瘯鐜Id
+			opp.RecordTypeId =  '0120T0000002kYL';
+			//姝e紡鐜id
+			//opp.RecordTypeId =  '0120K000000OpaH';
+			opp.CrossCooperativeProject__c = true;
+			opp.CrossCooperativeProjectL__c = true;
+
+			insert opp;
+
+			OpportunityContactRole ocr = new OpportunityContactRole();
+			ocr.OpportunityId = opp.Id;
+			ocr.ContactId = con.Id;
+			ocr.Role = 'End user';
+			ocr.IsPrimary = true;
+			insert ocr;
+
+			hasError = false;
+
+			String url = baseUrl + '\\' + opp.Id;
+			return new Pagereference(url);
+		} catch (Exception e) {
+			Database.rollback(sp);
+			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+			hasError = false;
+		}
+
+		return null;
+	}
+
+	public PageReference saveBtnNo() {
+		system.debug('=====saveBtnNo');
+		hasError = false;
+
+		return null;
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/NewCrossHighOpportunityController.cls-meta.xml b/scr/classes/NewCrossHighOpportunityController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewCrossHighOpportunityController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewCrossRegionalControllerText.cls b/scr/classes/NewCrossRegionalControllerText.cls
new file mode 100644
index 0000000..138fbef
--- /dev/null
+++ b/scr/classes/NewCrossRegionalControllerText.cls
@@ -0,0 +1,157 @@
+@isTest
+private class NewCrossRegionalControllerText {
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp1 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp1;
+
+        PageReference page = new PageReference('/apex/NewCrossHighOpportunity?accid=' + accIE.Id + '&conId=' + con.Id);
+        System.Test.setCurrentPage(page);
+        NewCrossHighOpportunityController controller = new NewCrossHighOpportunityController();
+
+        controller.init();
+
+        controller.opp.Name = 'test opp 001';
+        controller.opp.TradeType__c = 'Taxation';
+        controller.opp.LeadSource = 'Others';
+        controller.opp.SalesChannel__c = 'direct';
+        controller.opp.Have_Computer__c = true;
+        controller.opp.Association_Opportunity__c = opp1.Id;
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.saveBtnYes();
+
+        controller.saveBtnNo();
+    }
+    static testMethod void testMethod2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp1 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp1;
+
+        PageReference page = new PageReference('/apex/NewCrossRegionalSalesOpportunity?accid=' + accIE.Id + '&conId=' + con.Id);
+        System.Test.setCurrentPage(page);
+        NewCrossRegionalSalesController controller = new NewCrossRegionalSalesController();
+
+        controller.init();
+
+        controller.opp.Name = 'test opp 001';
+        controller.opp.TradeType__c = 'Taxation';
+        controller.opp.LeadSource = 'Others';
+        controller.opp.SalesChannel__c = 'direct';
+        controller.opp.Have_Computer__c = true;
+        controller.opp.Association_Opportunity__c = opp1.Id;
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.saveBtnYes();
+
+        controller.saveBtnNo();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewCrossRegionalControllerText.cls-meta.xml b/scr/classes/NewCrossRegionalControllerText.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewCrossRegionalControllerText.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewCrossRegionalSalesController.cls b/scr/classes/NewCrossRegionalSalesController.cls
new file mode 100644
index 0000000..5d756d6
--- /dev/null
+++ b/scr/classes/NewCrossRegionalSalesController.cls
@@ -0,0 +1,159 @@
+public with sharing class NewCrossRegionalSalesController {
+    public boolean hasError { get; set; }
+    public boolean isDealerPage { get; set; }
+
+    public Opportunity opp { get; set; }
+
+    public String accId { get; set; }
+    public String conId { get; set; }
+    private Account acc;
+    private Contact con;
+
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public String ProductSegment { get; set; }
+
+    public Boolean isIEDealer{get; set; }
+
+    public NewCrossRegionalSalesController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+
+    public PageReference init() {
+        hasError = false;
+
+        accId = System.currentPageReference().getParameters().get('accid');
+        conId = System.currentPageReference().getParameters().get('conId');
+
+        List<Account> accList = [select Id, Name, ProductSegment__c,compo_Acc__c,UserType__c from Account where Id = :accId];
+        if (accList.size() > 0) {
+            acc = accList[0];
+        }
+
+        List<Contact> conList = [select Id, Name from Contact where Id = :conId];
+        if (conList.size() > 0) {
+            con = conList[0];
+        }
+        ProductSegment = acc.ProductSegment__c;
+
+        //isDealerPage = UserInfo.getUserType() == 'PowerPartner'
+
+        isDealerPage = UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS' && acc.ProductSegment__c != 'IE' && acc.ProductSegment__c != 'RVI' && acc.RecordTypeId != System.Label.RT_SSBD_Service;
+        
+        String dealerName = '';
+        String dealerId = '';
+        if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+            User dealerUser = [select id, DealerName__c, DealerId__c from User where id = :UserInfo.getUserId()];
+            dealerName = dealerUser.DealerName__c;
+            dealerId = dealerUser.DealerId__c;
+        }
+
+        //no.6 gwy 2021-06-03
+        opp = new Opportunity();
+        if(acc.compo_Acc__c == 'COMPO瀹㈡埛' && acc.ProductSegment__c == 'IE'){
+            opp.compo_opp__c = true;
+        }
+        if(acc.UserType__c == 'OEM瀹㈡埛' && acc.ProductSegment__c == 'BS'){
+            opp.useing__c = 'OEM';
+        }
+        opp.AccountId = acc.Id;
+        opp.Account = acc;
+        opp.ProductSegment__c = acc.ProductSegment__c;
+        opp.Type = 'Not Traget';
+        opp.SalesChannel__c = 'dealer';
+        opp.NewInquiryDate__c = Date.today();
+        opp.StageName = 'Prospect Created';
+        opp.CloseDate = Date.valueOf('1900-01-01');
+        if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+            opp.Dealer__c = dealerId;
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtn() {
+        List<Opportunity> checkList = [select id, Name from Opportunity where AccountId = :opp.AccountId and Name = :opp.Name];
+        if (checkList.size() > 0) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇ュ鎴蜂笅鏈夊悕绉颁竴鏍风殑璇环锛屾槸鍚︾户缁垱寤鸿璇环锛�'));
+            hasError = true;
+        } else {
+             if(opp.Have_Computer__c && opp.Association_Opportunity__c == null){
+               
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇烽�夋嫨鍏宠仈鐨勮浠�'));
+                return null;
+                
+            }else if(opp.Have_Computer__c == false && opp.Association_Opportunity__c != null){
+                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info, '璇峰湪鍖呭惈鐢佃剳鐨勮浠蜂腑閫夋嫨涓绘満璇环銆�'));
+                return null;
+            }else if(opp.Have_Computer__c && opp.Association_Opportunity__c != null){
+                Opportunity opp1 = [select id,Have_Computer__c from Opportunity where id = :opp.Association_Opportunity__c];
+                if(opp1.Have_Computer__c){
+                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info, '閫夋嫨鐨勮浠锋槸鐢佃剳璇环锛岃纭璇环淇℃伅鍚庡啀淇濆瓨銆�'));
+                    return null;
+                }
+            }
+            return saveBtnYes();
+        }
+        return null;
+    }
+
+    public PageReference saveBtnYes() {
+        system.debug('=====saveBtnYes');
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            //娴嬭瘯鐜ID
+            opp.RecordTypeId = '0120T0000002Vh9';
+            //姝e紡鐜ID
+            //opp.RecordTypeId = '0120K000000OpaG';
+            opp.CrossCooperativeProject__c = true;
+
+            insert opp;
+            if(opp.Have_Computer__c && opp.Association_Opportunity__c != null){
+
+                StaticParameter.OppChangeopp = true;
+                StaticParameter.OppCanChangeOpp = true;
+                Opportunity newopp = new Opportunity();
+                newopp.Id = opp.Association_Opportunity__c;
+                newopp.Association_Opportunity__c = opp.Id;
+                system.debug(opp.Association_Opportunity__c);
+                update newopp;
+            }
+            OpportunityContactRole ocr = new OpportunityContactRole();
+            ocr.OpportunityId = opp.Id;
+            ocr.ContactId = con.Id;
+            ocr.Role = 'End user';
+            ocr.IsPrimary = true;
+            insert ocr;
+
+            hasError = false;
+
+            String url = baseUrl + '\\' + opp.Id;
+            return new Pagereference(url);
+        } catch (Exception e) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+            hasError = false;
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtnNo() {
+        system.debug('=====saveBtnNo');
+        hasError = false;
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewCrossRegionalSalesController.cls-meta.xml b/scr/classes/NewCrossRegionalSalesController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewCrossRegionalSalesController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewDiagnosisPartController.cls b/scr/classes/NewDiagnosisPartController.cls
new file mode 100644
index 0000000..82aefa3
--- /dev/null
+++ b/scr/classes/NewDiagnosisPartController.cls
@@ -0,0 +1,122 @@
+public with sharing class NewDiagnosisPartController {
+
+    public Diagnosis_Part__c diagnosisPart {get; set;}
+    public String swoId {get; set;}
+    public String diagnosisPartId {get; set;}
+
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public Boolean pageClose{ get; set; }
+    public Boolean DELIVERED_isCheck{get;set;}
+    public Boolean RETURNED_isCheck{get;set;}
+
+    public NewDiagnosisPartController() {
+        swoId = System.currentPageReference().getParameters().get('swoId');
+        diagnosisPartId = System.currentPageReference().getParameters().get('id');
+    }
+    public NewDiagnosisPartController(ApexPages.StandardController controller) {
+        swoId = System.currentPageReference().getParameters().get('swoId');
+        diagnosisPartId = System.currentPageReference().getParameters().get('id');
+
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+    }
+
+    public void init() {
+        DELIVERED_isCheck = false;
+        RETURNED_isCheck = false;
+        if (String.isNotBlank(diagnosisPartId)) {
+            Schema.DescribeSobjectResult repairPartType = Diagnosis_Part__c.sObjectType.getDescribe();
+            Map<String, Schema.SObjectField> repairPart_fields = repairPartType.fields.getMap();
+            String soql_repair = 'select ';
+            String fields = '';
+            for (String field : repairPart_fields.keySet()) {
+                if (fields.length() > 0) {
+                    fields += ', ';
+                }
+                fields += field;
+            }
+            soql_repair += fields;
+            soql_repair += ' from Diagnosis_Part__c where Id = \'' + diagnosisPartId + '\'';
+            diagnosisPart = Database.query(soql_repair);
+            DELIVERED_isCheck = diagnosisPart.DELIVERED__c;
+            RETURNED_isCheck = diagnosisPart.RETURNED__c;
+        } else {
+            diagnosisPart = new Diagnosis_Part__c();
+        }
+        if (String.isNotBlank(swoId)) {
+            diagnosisPart.SWO__c = swoId;
+        }
+    }
+
+    public void save() {
+        Boolean isSave = true;
+        if(diagnosisPart.DELIVERED__c == false && DELIVERED_isCheck == true){
+            diagnosisPart.DELIVERED__c.addError('DELIVERED 涓嶅厑璁稿彇娑堝嬀閫�');
+            isSave = false;
+        }
+        if(diagnosisPart.RETURNED__c == false && RETURNED_isCheck == true){
+            diagnosisPart.RETURNED__c.addError('RETURNED 涓嶅厑璁稿彇娑堝嬀閫�');
+            isSave = false;
+        }
+        if(!isSave){
+            return;
+        }
+        String productId = diagnosisPart.Product__c;
+        if (String.isNotBlank(productId)) {
+            Product2 product = [SELECT Id, Name, Product_ECCode__c, Description FROM Product2 WHERE Id = :productId limit 1];
+            diagnosisPart.PART_NUMBER__c = product.Product_ECCode__c;
+            diagnosisPart.DESCRIPTION__c = product.Description;
+        }
+        pageClose = false;
+
+        if (diagnosisPart.DELIVERED__c == false  && String.isBlank(diagnosisPart.Id)) {
+            Boolean isUpdateSwo = false;
+            List<SWO__c> swoList = [select Id,Diagnose_part_not_delievered_1__c,Diagnose_part_not_delievered_2__c,Diagnose_part_not_delievered_3__c from SWO__c where Id=:diagnosisPart.SWO__c];
+            System.debug('swoList.size():'+swoList.size());
+            if (swoList!=null && swoList.size()!=0) {
+                SWO__c swo = swoList[0];
+                if(String.isBlank(swo.Diagnose_part_not_delievered_1__c)){
+                    isUpdateSwo = true;
+                    swo.Diagnose_part_not_delievered_1__c = diagnosisPart.PART_NUMBER__c;
+                }else if(String.isBlank(swo.Diagnose_part_not_delievered_2__c)){ 
+                    isUpdateSwo = true;
+                    swo.Diagnose_part_not_delievered_2__c = diagnosisPart.PART_NUMBER__c;
+                }else if(String.isBlank(swo.Diagnose_part_not_delievered_3__c)){
+                    isUpdateSwo = true;
+                    swo.Diagnose_part_not_delievered_3__c = diagnosisPart.PART_NUMBER__c;
+                }
+                System.debug('swo.Id:'+swo.Id);
+                if(isUpdateSwo) update swo;
+            }
+        }
+
+        upsert diagnosisPart;
+        pageClose = true;
+        System.debug('id:' + diagnosisPart.Id);
+        diagnosisPartId = diagnosisPart.Id;
+        return;
+    }
+
+    public PageReference deleteAction() {
+        if (String.isNotBlank(diagnosisPart.Id)) {
+            delete diagnosisPart;
+        }
+        return ReturnSWO();
+    }
+
+    public PageReference ReturnSWO() {
+        String swoId = diagnosisPart.SWO__c;
+        String url = '/apex/SWOPage?id=' + swoId + '&type=Diagnosis';
+        PageReference  ref = new Pagereference(url);
+        ref.setRedirect(true);
+         return ref;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewDiagnosisPartController.cls-meta.xml b/scr/classes/NewDiagnosisPartController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewDiagnosisPartController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewDiagnosisPartControllerTest.cls b/scr/classes/NewDiagnosisPartControllerTest.cls
new file mode 100644
index 0000000..e12aab0
--- /dev/null
+++ b/scr/classes/NewDiagnosisPartControllerTest.cls
@@ -0,0 +1,54 @@
+@isTest
+private class NewDiagnosisPartControllerTest {
+
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        insert swo;
+
+        PageReference page = new PageReference('/apex/NewDiagnosisPart?swoId=' + swo.Id );
+        System.Test.setCurrentPage(page);
+        NewDiagnosisPartController controller = new NewDiagnosisPartController();
+        controller.init();
+        controller.diagnosisPart.Product__c = product1.Id;
+        controller.diagnosisPart.QUANTITY__c = 1;
+        controller.deleteAction();
+        controller.save();
+
+        Diagnosis_Part__c diagnosisPart = new Diagnosis_Part__c();
+        diagnosisPart.SWO__c = swo.Id;
+        insert diagnosisPart;
+
+        PageReference page1 = new PageReference('/apex/NewDiagnosisPart?id='+diagnosisPart.Id + '&sfdc.override=1');
+        System.Test.setCurrentPage(page1);
+        NewDiagnosisPartController controller1 = new NewDiagnosisPartController(new ApexPages.StandardController(diagnosisPart));
+        controller1.init();
+        controller1.deleteAction();
+        controller1.ReturnSWO();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewDiagnosisPartControllerTest.cls-meta.xml b/scr/classes/NewDiagnosisPartControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewDiagnosisPartControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewHighProductsOppController.cls b/scr/classes/NewHighProductsOppController.cls
new file mode 100644
index 0000000..722d92c
--- /dev/null
+++ b/scr/classes/NewHighProductsOppController.cls
@@ -0,0 +1,124 @@
+public with sharing class NewHighProductsOppController {
+	public boolean hasError { get; set; }
+	public boolean isDealerPage { get; set; }
+
+	public Opportunity opp { get; set; }
+
+	public String accId { get; set; }
+	public String conId { get; set; }
+	private Account acc;
+	private Contact con;
+
+	public String baseUrl { get; set; }
+	public String rtUrl { get; set; }
+
+	public String ProductSegment { get; set; }
+
+	public NewHighProductsOppController() {
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+		String path = URL.getCurrentRequestUrl().getPath();
+		if (path.indexOf('/apex') > 0) {
+			baseUrl += path.substring(0, path.indexOf('/apex'));
+		} else if (path.indexOf('production/') > 0) {
+			baseUrl += '/production';
+		}
+		rtUrl = System.currentPageReference().getParameters().get('retURL');
+		if (rtUrl == null || rtUrl == 'null') {
+			rtUrl = '';
+		}
+	}
+
+	public PageReference init() {
+		hasError = false;
+
+		accId = System.currentPageReference().getParameters().get('accid');
+		conId = System.currentPageReference().getParameters().get('conId');
+
+		List<Account> accList = [select Id, Name, ProductSegment__c,OwnerID__c from Account where Id = :accId];
+		if (accList.size() > 0) {
+			acc = accList[0];
+		}
+
+		List<Contact> conList = [select Id, Name from Contact where Id = :conId];
+		if (conList.size() > 0) {
+			con = conList[0];
+		}
+		ProductSegment = acc.ProductSegment__c;
+		isDealerPage = UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS' && acc.ProductSegment__c != 'IE' && acc.ProductSegment__c != 'RVI' && acc.RecordTypeId != System.Label.RT_SSBD_Service;
+		String dealerName = '';
+		String dealerId = '';
+		if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+			User dealerUser = [select id, DealerName__c, DealerId__c from User where id = :UserInfo.getUserId()];
+			dealerName = dealerUser.DealerName__c;
+			dealerId = dealerUser.DealerId__c;
+		}
+
+        Id recordTypeId =Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SSBD_HighendProducts').getRecordTypeId();
+        system.debug(recordTypeId);
+		opp = new Opportunity();
+		opp.RecordTypeId = recordTypeId;
+		opp.AccountId = acc.Id;
+		opp.Account = acc;
+		opp.ProductSegment__c = acc.ProductSegment__c;
+		opp.Type = 'Not Traget';
+		opp.SalesChannel__c = 'dealer';
+		opp.NewInquiryDate__c = Date.today();
+		opp.StageName = 'Prospect Created';
+		opp.CloseDate = Date.valueOf('1900-01-01');
+		//opp.OwnerId = acc.OwnerID__c;
+
+		if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+			opp.Dealer__c = dealerId;
+		}
+
+		return null;
+	}
+
+	public PageReference saveBtn() {
+		List<Opportunity> checkList = [select id, Name from Opportunity where AccountId = :opp.AccountId and Name = :opp.Name];
+		if (checkList.size() > 0) {
+			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇ュ鎴蜂笅鏈夊悕绉颁竴鏍风殑璇环锛屾槸鍚︾户缁垱寤鸿璇环锛�'));
+			hasError = true;
+		} else {
+			return saveBtnYes();
+		}
+		return null;
+	}
+
+	public PageReference saveBtnYes() {
+		system.debug('=====saveBtnYes');
+
+		Savepoint sp = Database.setSavepoint();
+		try {
+			
+			opp.RecordTypeId =  System.Label.SSBD_HighendProducts;
+
+			insert opp;
+
+			OpportunityContactRole ocr = new OpportunityContactRole();
+			ocr.OpportunityId = opp.Id;
+			ocr.ContactId = con.Id;
+			ocr.Role = 'End user';
+			ocr.IsPrimary = true;
+			insert ocr;
+
+			hasError = false;
+
+			String url = baseUrl + '\\' + opp.Id;
+			return new Pagereference(url);
+		} catch (Exception e) {
+			Database.rollback(sp);
+			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+			hasError = false;
+		}
+
+		return null;
+	}
+
+	public PageReference saveBtnNo() {
+		system.debug('=====saveBtnNo');
+		hasError = false;
+
+		return null;
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/NewHighProductsOppController.cls-meta.xml b/scr/classes/NewHighProductsOppController.cls-meta.xml
new file mode 100644
index 0000000..91b23b8
--- /dev/null
+++ b/scr/classes/NewHighProductsOppController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>46.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewHighProductsOppControllerTest.cls b/scr/classes/NewHighProductsOppControllerTest.cls
new file mode 100644
index 0000000..5cba708
--- /dev/null
+++ b/scr/classes/NewHighProductsOppControllerTest.cls
@@ -0,0 +1,59 @@
+@isTest
+private class NewHighProductsOppControllerTest {
+    @isTest static void test_method_one() {
+		List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        PageReference page = new PageReference('/apex/NewHighProductsOpp?accid=' + accIE.Id + '&conId=' + con.Id);
+        System.Test.setCurrentPage(page);
+        NewHighProductsOppController controller = new NewHighProductsOppController();
+        controller.init();
+
+        controller.opp.Name = 'test opp 001';
+        controller.opp.TradeType__c = 'Taxation';
+        controller.opp.LeadSource = 'Others';
+        controller.opp.SalesChannel__c = 'direct';
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.saveBtnYes();
+
+        controller.saveBtnNo();
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/NewHighProductsOppControllerTest.cls-meta.xml b/scr/classes/NewHighProductsOppControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewHighProductsOppControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewLoanerApplicationController.cls b/scr/classes/NewLoanerApplicationController.cls
new file mode 100644
index 0000000..de3eb9c
--- /dev/null
+++ b/scr/classes/NewLoanerApplicationController.cls
@@ -0,0 +1,99 @@
+public with sharing class NewLoanerApplicationController {
+	//瀹㈡埛ID
+	public String accountID {get; private set;}
+	//鑱旂郴浜篿d
+	public String contactID {get; private set;}
+
+	public loaner_application__c la{get; private set;}
+	public String typeName {get; private set;}
+
+	public String userType {get; private set;}
+
+	public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+	public NewLoanerApplicationController() {
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+	}
+
+	public PageReference init() {
+		userType = UserInfo.getUserType();
+		accountID = System.currentPageReference().getParameters().get('accid');
+        contactID = System.currentPageReference().getParameters().get('conId');
+
+        Account acc = [select id,ProductSegment__c from Account where id = :accountID];
+        typeName = acc.ProductSegment__c;
+        Id recordTypeId =Schema.SObjectType.loaner_application__c.getRecordTypeInfosByName()
+                  .get(typeName).getRecordTypeId();
+		
+		la = new loaner_application__c();
+		la.RecordTypeId= recordTypeId;
+		if(typeName == 'BS' && userType != 'Standard'){
+			la.RecordTypeId = System.label.bs_D_ID;
+		}
+		System.debug(la.RecordTypeId);
+		//ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,accountID));
+		return null;
+	}
+
+	public PageReference saveBtn() {
+		if(la.Request_shipping_Date__c < Date.today()){
+			 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鍒拌揣鏃ヤ笉寰楁棭浜庝粖澶�'));
+			return null;
+		}
+		if(la.Request_shipping_Date__c >= la.Request_return_Date__c){
+			 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '褰掕繕鏃ヤ笉寰楁棭浜庡埌璐ф棩'));
+			return null;
+		}
+		Account acc = [select id,Name from Account where id = :accountID];
+		la.Loaner_Account__c = acc.Name;
+		la.ApplyPerson__c = UserInfo.getUserId();
+	 	Savepoint sp = Database.setSavepoint();
+        try {
+            insert la;
+
+            loaner_user__c lu = new loaner_user__c();
+	        lu.loaner_application__c = la.id;
+	        lu.Customer__c = accountID;
+		 	
+		 	if(contactID != null){
+		 		lu.Contact__c = contactID;
+		 		Contact contact = [select id,Phone,Name,Address1__c from Contact where id = :contactID];
+		 		lu.ContactNumber__c = contact.Phone;
+		 		
+		 	}
+	 		
+            insert lu;
+            String url = baseUrl + '\\' + la.Id;
+            return new Pagereference(url);
+        } catch (Exception e) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+        }
+
+        return null;
+	}
+
+	    public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        if(contactID == null){
+        	url += '\\' + accountID;
+        }else{
+        	url += '\\' + contactID;
+        }
+        
+        return new Pagereference(url);
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewLoanerApplicationController.cls-meta.xml b/scr/classes/NewLoanerApplicationController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/NewLoanerApplicationController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewLoanerApplicationControllerTest.cls b/scr/classes/NewLoanerApplicationControllerTest.cls
new file mode 100644
index 0000000..c9e3e1e
--- /dev/null
+++ b/scr/classes/NewLoanerApplicationControllerTest.cls
@@ -0,0 +1,97 @@
+@isTest
+private class NewLoanerApplicationControllerTest {
+	static void setupTestData() {
+                OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+                insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+            }
+	@isTest static void test_method_one() {
+		setupTestData();
+		// Implement test code
+		List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+
+		// 鏂板缓 瀹㈡埛
+		Account acc = new Account();
+		acc.RecordTypeId = rectCo[0].Id;
+		acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+		acc.DivisionName__c = 'DivTEST';
+		acc.FacilityName__c = 'FacTEST	';
+		acc.PostCode__c = '000000';
+		insert acc;
+
+		// 鏂板缓 鑱旂郴浜�
+		Contact con = new Contact();
+		con.LastName = 'test1';
+		con.AccountId = acc.Id;
+		con.Address1__c = 'Address1D__c';
+		con.Postcode__c = '100111';
+		con.ContactStatus__c = 'ContactStatusD__c';
+		con.StatusD__c = 'Pass';
+		insert con;
+
+		// 鏂板缓鐢ㄦ埛
+		User user = new User();
+		user.LastName = 'test';
+		user.FirstName = 'test';
+		user.Alias = 'test';
+		user.Email = 'test@test.com';
+		user.Username = 'test111@test222.com';
+		user.CommunityNickname = 'test';
+		user.IsActive = true;
+		user.EmailEncodingKey = 'ISO-2022-JP';
+		user.TimeZoneSidKey = 'Asia/Tokyo';
+		user.LocaleSidKey = 'ja_JP';
+		user.LanguageLocaleKey = 'ja';
+		user.ProfileId = System.Label.SystemAdmin;
+		insert user;
+
+		//PageReference page = new PageReference('/apex/NewLoanerApplicationController?accid=' + acc.Id );
+		PageReference page = new PageReference('/apex/NewLoanerApplicationController?accid=' + acc.Id + '&ConId=' + con.id);
+		System.Test.setCurrentPage(page);
+		NewLoanerApplicationController  controller = new NewLoanerApplicationController();
+
+		controller.init();
+
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+
+		controller.la.name = '鐢宠1';
+		controller.la.Demo_purpose__c = '灞曚細';
+		controller.la.RecordTypeId = rectLo[0].id;
+		controller.la.Loaner_Ser__c = '鍊熺敤鎷呭綋';
+		controller.la.Request_shipping_Date__c = Date.today();
+		controller.la.Request_return_Date__c = Date.today().addDays(2);
+		controller.la.Approver__c = user.id;
+
+		controller.saveBtn();
+
+		List<loaner_user__c> luNew = [select Id, Remarks__c, Contact__r.name, Customer__c, ContactNumber__c from loaner_user__c];
+		List<loaner_application__c> laNew = [select name from loaner_application__c];
+
+		system.assertEquals('鐢宠1', laNew[0].name);
+		system.assertEquals(acc.id, luNew[0].Customer__c);
+
+
+		controller.cancelBtn();
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/NewLoanerApplicationControllerTest.cls-meta.xml b/scr/classes/NewLoanerApplicationControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/NewLoanerApplicationControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewLoanerUserController.cls b/scr/classes/NewLoanerUserController.cls
new file mode 100644
index 0000000..2a612b9
--- /dev/null
+++ b/scr/classes/NewLoanerUserController.cls
@@ -0,0 +1,152 @@
+public with sharing class NewLoanerUserController {
+	//鍩虹url
+	public String baseUrl { get; private set; }
+
+	public List<loaner_user__c> luList{get; private set; }
+	//鏁版嵁List
+	public List<loaner_user__c> dataLines {get; private set;}
+	//璁㈠崟Id
+	public String laId {get; private set;}
+	//
+	/*public NewLoanerUserController() {
+		 laId = System.currentPageReference().getParameters().get('headId');
+         //ApexPages.currentPage().getParameters().get('headId');
+
+    }*/
+
+    public NewLoanerUserController(ApexPages.StandardController stdController) {
+        String luId = stdController.getId();
+        if(luId == null || luId == ''){
+             laId = System.currentPageReference().getParameters().get('headId');
+        }else{
+            loaner_user__c lu = [select id,loaner_application__c from loaner_user__c where id = :luId];
+            laId = lu.loaner_application__c; 
+        }     
+    }
+    
+
+
+	//鍒濆鍖栨柟娉�
+	public PageReference init() {
+ 		// 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        dataLines = new List<loaner_user__c>();
+        luList = [select id,Contact__c,ContactNumber__c,FromThePeriod__c,EndThePeriod__c,Remarks__c,Customer__c,Follow_UP_Opp__c from loaner_user__c where  loaner_application__c =:laId];
+        if(luList.size() >0){
+        	for(loaner_user__c lu : luList){
+        		dataLines.add(lu);
+        	}
+        }
+        if(dataLines.size()<50){
+        	integer num = dataLines.size();
+        	for(integer i = 0 ;i<50-num;i++){
+        		loaner_user__c luc = new loaner_user__c();
+        		dataLines.add(luc);
+        	}
+        }
+		return null;
+	}
+
+	public PageReference updateUser() {
+
+		List<loaner_user__c> updateList = new List<loaner_user__c>();
+		loaner_application__c la =[select id,RecordType.DeveloperName from loaner_application__c where id=:laId];
+        List<String> contactIdList = new List<String>();
+
+        String firstLuId = '';
+        String accountName = '';
+        List<String> idList = new List<String>();
+		for(loaner_user__c luc : dataLines){
+			if(!(String.isBlank(luc.Contact__c) || luc.Customer__c == null)){
+				loaner_user__c lu = new loaner_user__c();
+				lu.Contact__c = luc.Contact__c;
+                contactIdList.add(luc.Contact__c);
+                
+                if(firstLuId == '') firstLuId = luc.Contact__c;
+				
+                lu.FromThePeriod__c = luc.FromThePeriod__c;
+				lu.EndThePeriod__c = luc.EndThePeriod__c;
+				lu.Remarks__c = luc.Remarks__c;
+				lu.Customer__c = luc.Customer__c;
+                lu.Follow_UP_Opp__c = luc.Follow_UP_Opp__c;
+				lu.loaner_application__c = laId;
+				updateList.add(lu);
+                //
+                idList.add(luc.Customer__c);
+			}
+		}
+
+        List<Contact> contactList = [select id,Phone from Contact where id = :contactIdList];
+        for(Contact con : contactList){
+            for(loaner_user__c lu1 : updateList){
+                if(lu1.Contact__c == con.id){
+                    lu1.ContactNumber__c = con.Phone;
+                }
+            }
+        }
+        if(firstLuId == '' || firstLuId == null){
+            delete luList;
+            String url = baseUrl;
+            url += '\\' + laId;
+            return new Pagereference(url);
+        }
+        if(la.RecordType.DeveloperName == 'BS'){
+            Contact contact = [select id,Name,Phone,Address1__c,Postcode__c from Contact where id = : firstLuId]; 
+            la.id = laId;
+            la.Loaner_receive_staff__c = contact.Name;
+            la.Loaner_receive_staff_phone__c = contact.Phone;
+            la.direct_shippment_address__c = contact.Address1__c;
+            la.Post_Code__c = contact.Postcode__c;
+        }
+
+		Savepoint sp = Database.setSavepoint();
+       
+        try {
+            
+            if (updateList.size() > 0) {
+                delete luList;
+                insert updateList;
+            }
+            System.debug(accountName);
+            if(accountName == ''){
+                System.debug('1111');
+                List<Account> luList = new List<Account>();
+                luList = [select id,Name from Account where id in :idList];
+                System.debug('luList'+ luList);
+                for(Account lu : luList){
+                    if(accountName == ''){
+                        accountName = lu.Name;
+                    }else{
+                        accountName += (',' + lu.Name);
+                    }
+                }
+            }
+            System.debug(accountName);
+            la.Loaner_Account__c = accountName;
+            update la;
+        }catch (Exception ex) {
+                Database.rollback(sp);
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+                return null;
+        }
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+	}
+
+
+	public PageReference cancelBtn() {
+        // 杩斿洖鏍锋満鍊熷嚭鐢宠鐢婚潰
+        String url = baseUrl;
+        url += '\\' + laId;
+        return new Pagereference(url);
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewLoanerUserController.cls-meta.xml b/scr/classes/NewLoanerUserController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/NewLoanerUserController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewLoanerUserControllerTest.cls b/scr/classes/NewLoanerUserControllerTest.cls
new file mode 100644
index 0000000..06698d0
--- /dev/null
+++ b/scr/classes/NewLoanerUserControllerTest.cls
@@ -0,0 +1,121 @@
+@isTest
+private class NewLoanerUserControllerTest {
+	static void setupTestData() {
+                OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+                OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+                OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+                insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+            }
+	@isTest static void test_method_one() {
+		setupTestData();
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'BS'];
+
+		List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+
+		// 鏂板缓澶囧搧鍊熷嚭鐢宠
+		loaner_application__c loaner = new loaner_application__c();
+		loaner.Name = 'TEST';
+		loaner.RecordTypeId = rectLo[0].id;
+		loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+		loaner.Request_shipping_Date__c = Date.today();
+		loaner.Request_return_Date__c = Date.today();
+		loaner.Status__c = '宸插嚭搴撴寚绀�';
+		loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+		insert loaner;
+
+		// 鏂板缓 瀹㈡埛
+		Account acc = new Account();
+		acc.RecordTypeId = rectCo[0].Id;
+		acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+		acc.DivisionName__c = 'DivisionName__c';
+		acc.FacilityName__c = 'FacilityName__c';
+		acc.PostCode__c = '000000';
+		insert acc;
+
+		// 鏂板缓 瀹㈡埛2
+		Account acc2 = new Account();
+		acc2.RecordTypeId = rectCo[0].Id;
+		acc2.Name         = '瀹㈡埛銉嗐偣銉�2';
+		acc2.DivisionName__c = 'DivisionName__c';
+		acc2.FacilityName__c = 'FFFF';
+		acc2.Phone = '123456789';
+		acc2.PostCode__c = '000000';
+		insert acc2;
+
+		// 鏂板缓 鑱旂郴浜�
+		Contact con = new Contact();
+		con.LastName = 'test1';
+		con.AccountId = acc.Id;
+		con.Address1__c = 'Address1D__c';
+		con.Postcode__c = '100111';
+		con.Phone = '123456789';
+		con.ContactStatus__c = 'ContactStatusD__c';
+		con.StatusD__c = 'Pass';
+
+		insert con;
+
+		// 鏂板缓 鑱旂郴浜�2
+		Contact con2 = new Contact();
+		con2.LastName = 'test2';
+		con2.AccountId = acc.Id;
+		con2.Address1__c = 'Address1D__c';
+		con2.Postcode__c = '100111';
+		con2.ContactStatus__c = 'ContactStatusD__c';
+		con2.StatusD__c = 'Pass';
+
+        insert con2;
+
+		// 鍊熺敤瀹㈡埛
+		loaner_user__c lu = new loaner_user__c();
+		lu.Customer__c = acc.id;
+		lu.Contact__c = con.id;
+		lu.loaner_application__c = loaner.id;
+		lu.Remarks__c = '123';
+		insert lu;
+
+		//
+		PageReference page = new PageReference('/apex/NewLoanerUserController?headId=' + loaner.Id );
+		System.Test.setCurrentPage(page);
+		NewLoanerUserController  controller = new NewLoanerUserController(new ApexPages.StandardController(lu));
+
+		controller.init();
+
+		controller.dataLines[0].Remarks__c = '澶囨敞';
+		controller.dataLines[0].Contact__c = con2.id;
+		controller.dataLines[0].Customer__c = acc2.id;
+
+		controller.updateUser();
+
+		List<loaner_user__c> luNew = [select Id, Remarks__c, Contact__r.name, Customer__r.name, ContactNumber__c from loaner_user__c];
+		List<loaner_application__c> laNew = [select Loaner_receive_staff__c, Loaner_receive_staff_phone__c, direct_shippment_address__c, Post_Code__c from loaner_application__c];
+
+		//system.assertEquals('澶囨敞', luNew[0].Remarks__c);
+		//system.assertEquals('test2', luNew[0].Contact__r.name);
+		//system.assertEquals('test2', laNew[0].Loaner_receive_staff__c);
+		//system.assertEquals('Address1D__c', laNew[0].direct_shippment_address__c);
+		//system.assertEquals('100111', laNew[0].Post_Code__c);
+
+		controller.cancelBtn();
+	}
+	
+	@isTest static void test_method_two() {
+		// Implement test code
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/NewLoanerUserControllerTest.cls-meta.xml b/scr/classes/NewLoanerUserControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/NewLoanerUserControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewOpportunityController.cls b/scr/classes/NewOpportunityController.cls
new file mode 100644
index 0000000..5e30945
--- /dev/null
+++ b/scr/classes/NewOpportunityController.cls
@@ -0,0 +1,171 @@
+public with sharing class NewOpportunityController {
+    public boolean hasError { get; set; }
+    public boolean isDealerPage { get; set; }
+
+    public Opportunity opp { get; set; }
+
+    public String accId { get; set; }
+    public String conId { get; set; }
+    private Account acc;
+    private Contact con;
+
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public String ProductSegment { get; set; }
+
+    public Boolean isIEDealer{get; set; }
+
+    public NewOpportunityController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+
+    public PageReference init() {
+        hasError = false;
+
+        accId = System.currentPageReference().getParameters().get('accid');
+        conId = System.currentPageReference().getParameters().get('conId');
+
+        List<Account> accList = [select Id, Name, ProductSegment__c,compo_Acc__c,UserType__c from Account where Id = :accId];
+        if (accList.size() > 0) {
+            acc = accList[0];
+        }
+
+        List<Contact> conList = [select Id, Name from Contact where Id = :conId];
+        if (conList.size() > 0) {
+            con = conList[0];
+        }
+        ProductSegment = acc.ProductSegment__c;
+        isDealerPage = UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS' && acc.ProductSegment__c != 'IE' && acc.ProductSegment__c != 'RVI' && acc.RecordTypeId != System.Label.RT_SSBD_Service;
+        // String proId = UserInfo.getProfileId().subString(0, 15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        
+        List<String> IEpageList = new List<String>{
+            '00e28000000h9jy',
+            '00e28000001wePQ',
+            '00e0T000000DuK3',//涓婄嚎闇�瑕佹浛鎹负姝e紡鐜ID(宸茶拷鍔�)
+            '00e0T000000DuK8',//涓婄嚎闇�瑕佹浛鎹负姝e紡鐜ID(宸茶拷鍔�)
+            '00e28000000YMiG',
+            '00e28000000eN63',
+            '00e28000001wewP',
+            '00e0K000001l0l9',
+            '00e0K000002NxSz',
+            '00e0K000002NxT4'
+        };
+        isIEDealer = IEpageList.contains(new_profileId) || IEpageList.contains(new_profileId);
+        //System.debug('UserInfo.getProfileId' + UserInfo.getProfileId());
+        String dealerName = '';
+        String dealerId = '';
+        if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+            User dealerUser = [select id, DealerName__c, DealerId__c from User where id = :UserInfo.getUserId()];
+            dealerName = dealerUser.DealerName__c;
+            dealerId = dealerUser.DealerId__c;
+        }
+
+        //no.6 gwy 2021-06-03
+        opp = new Opportunity();
+        if(acc.compo_Acc__c == 'COMPO瀹㈡埛' && acc.ProductSegment__c == 'IE'){
+            opp.compo_opp__c = true;
+        }
+        if(acc.UserType__c == 'OEM瀹㈡埛' && acc.ProductSegment__c == 'BS'){
+            opp.useing__c = 'OEM';
+        }
+        opp.AccountId = acc.Id;
+        opp.Account = acc;
+        opp.ProductSegment__c = acc.ProductSegment__c;
+        opp.Type = 'Not Traget';
+        opp.SalesChannel__c = 'dealer';
+        opp.NewInquiryDate__c = Date.today();
+        opp.StageName = 'Prospect Created';
+        opp.CloseDate = Date.valueOf('1900-01-01');
+        if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+            opp.Dealer__c = dealerId;
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtn() {
+        List<Opportunity> checkList = [select id, Name from Opportunity where AccountId = :opp.AccountId and Name = :opp.Name];
+        if (checkList.size() > 0) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇ュ鎴蜂笅鏈夊悕绉颁竴鏍风殑璇环锛屾槸鍚︾户缁垱寤鸿璇环锛�'));
+            hasError = true;
+        } else {
+             if(opp.Have_Computer__c && opp.Association_Opportunity__c == null){
+               
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇烽�夋嫨鍏宠仈鐨勮浠�'));
+                return null;
+                
+            }else if(opp.Have_Computer__c == false && opp.Association_Opportunity__c != null){
+                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info, '璇峰湪鍖呭惈鐢佃剳鐨勮浠蜂腑閫夋嫨涓绘満璇环銆�'));
+                return null;
+            }else if(opp.Have_Computer__c && opp.Association_Opportunity__c != null){
+                Opportunity opp1 = [select id,Have_Computer__c from Opportunity where id = :opp.Association_Opportunity__c];
+                if(opp1.Have_Computer__c){
+                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info, '閫夋嫨鐨勮浠锋槸鐢佃剳璇环锛岃纭璇环淇℃伅鍚庡啀淇濆瓨銆�'));
+                    return null;
+                }
+            }
+            return saveBtnYes();
+        }
+        return null;
+    }
+
+    public PageReference saveBtnYes() {
+        system.debug('=====saveBtnYes');
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+
+            
+
+            insert opp;
+            if(opp.Have_Computer__c && opp.Association_Opportunity__c != null){
+
+                StaticParameter.OppChangeopp = true;
+                StaticParameter.OppCanChangeOpp = true;
+                Opportunity newopp = new Opportunity();
+                newopp.Id = opp.Association_Opportunity__c;
+                newopp.Association_Opportunity__c = opp.Id;
+                system.debug(opp.Association_Opportunity__c);
+                update newopp;
+            }
+            OpportunityContactRole ocr = new OpportunityContactRole();
+            ocr.OpportunityId = opp.Id;
+            ocr.ContactId = con.Id;
+            ocr.Role = 'End user';
+            ocr.IsPrimary = true;
+            insert ocr;
+
+            hasError = false;
+
+            String url = baseUrl + '\\' + opp.Id;
+            return new Pagereference(url);
+        } catch (Exception e) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+            hasError = false;
+        }
+
+        return null;
+    }
+
+    public PageReference saveBtnNo() {
+        system.debug('=====saveBtnNo');
+        hasError = false;
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewOpportunityController.cls-meta.xml b/scr/classes/NewOpportunityController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewOpportunityController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewOpportunityControllerTest.cls b/scr/classes/NewOpportunityControllerTest.cls
new file mode 100644
index 0000000..af363d0
--- /dev/null
+++ b/scr/classes/NewOpportunityControllerTest.cls
@@ -0,0 +1,82 @@
+@isTest
+private class NewOpportunityControllerTest {
+
+	@isTest static void test_method_one() {
+		List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp1 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp1;
+
+        PageReference page = new PageReference('/apex/NewOpportunity?accid=' + accIE.Id + '&conId=' + con.Id);
+        System.Test.setCurrentPage(page);
+        NewOpportunityController controller = new NewOpportunityController();
+
+        controller.init();
+
+        controller.opp.Name = 'test opp 001';
+        controller.opp.TradeType__c = 'Taxation';
+        controller.opp.LeadSource = 'Others';
+        controller.opp.SalesChannel__c = 'direct';
+        controller.opp.Have_Computer__c = true;
+        controller.opp.Association_Opportunity__c = opp1.Id;
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        controller.saveBtnYes();
+
+        controller.saveBtnNo();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewOpportunityControllerTest.cls-meta.xml b/scr/classes/NewOpportunityControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewOpportunityControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewOrderController.cls b/scr/classes/NewOrderController.cls
new file mode 100644
index 0000000..77a4aae
--- /dev/null
+++ b/scr/classes/NewOrderController.cls
@@ -0,0 +1,54 @@
+public with sharing class NewOrderController {
+    public Id ordId {get;set;}
+    public boolean errorflg {get;set;}
+    public String errorMessage {get;set;}
+
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public String fileName { get; set; }
+    public List<OrderItem> csv_activities {get;set;}
+
+    public NewOrderController(ApexPages.StandardController controller) {
+        this();
+    }
+
+    public NewOrderController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+
+    public void init () {
+        ordId = System.currentPageReference().getParameters().get('Id');
+
+        if (ordId != null) {
+            csv_activities = [select Id, OrderId, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Name, Quantity, Discount__c, Set__c from OrderItem where OrderId =: ordId];
+        }
+    }
+
+    public PageReference csvExport() {
+        if (fileName == null || fileName == '') {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ラ厤缃鍑烘枃浠跺悕銆�';
+            return null;
+        }
+
+        if (csv_activities.size() == 0) {
+            errorflg = true;
+            errorMessage = '鍚堝悓娌℃湁浜у搧閰嶇疆銆�';
+            return null;
+        }
+
+        PageReference pr = page.OrderCSVExport;
+        return pr;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewOrderController.cls-meta.xml b/scr/classes/NewOrderController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewOrderController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewOrderControllerTest.cls b/scr/classes/NewOrderControllerTest.cls
new file mode 100644
index 0000000..63ee7f7
--- /dev/null
+++ b/scr/classes/NewOrderControllerTest.cls
@@ -0,0 +1,144 @@
+@isTest
+private class NewOrderControllerTest {
+
+	@isTest static void test_method_one() {
+		Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert contact;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10
+        );
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20
+        );
+        insert new OpportunityLineItem[] {oli1, oli2};
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli1 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10,
+            Custom_Price__c = 15,
+            Set__c = 'set01'
+        );
+        QuoteLineItem qli2 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20,
+            Custom_Price__c = 25,
+            Set__c = 'set01'
+        );
+        insert new QuoteLineItem[] {qli1, qli2};
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            QuoteId = quo.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id
+        );
+        insert order;
+
+        PageReference page = new PageReference('/apex/NewOrder?Id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        NewOrderController controller = new NewOrderController();
+
+        controller.init();
+
+        controller.csvExport();
+
+        controller.fileName = 'aaa';
+        controller.csvExport();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewOrderControllerTest.cls-meta.xml b/scr/classes/NewOrderControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewOrderControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewQuoteDevideController.cls b/scr/classes/NewQuoteDevideController.cls
new file mode 100644
index 0000000..4a36f5c
--- /dev/null
+++ b/scr/classes/NewQuoteDevideController.cls
@@ -0,0 +1,75 @@
+public without sharing class NewQuoteDevideController {
+    private String oid;
+    private String qid;
+    private String ot;
+    private String cid;
+    private String rturl;
+
+    public NewQuoteDevideController(ApexPages.StandardController controller) {
+        this();
+    }
+
+    public NewQuoteDevideController() {
+        oid = System.currentPageReference().getParameters().get('oppid');
+        qid = System.currentPageReference().getParameters().get('id');
+        ot = System.currentPageReference().getParameters().get('openType');
+        cid = System.currentPageReference().getParameters().get('copyid');
+        rturl = System.currentPageReference().getParameters().get('retURL');
+    }
+
+    public PageReference init() {
+        PageReference pr = null;
+
+        String quoId = '';
+        String oppId = '';
+        if (cid != null && cid.length() > 0) {
+            quoId = cid;
+        } else if (qid != null && qid.length() > 0) {
+            quoId = qid;
+        } else if (oid != null && oid.length() > 0) {
+            oppId = oid;
+        }
+
+        boolean isService = false;
+        if (ot == 'service') {
+            isService = true;
+        } else {
+            if (quoId != null && quoId.length() > 0) {
+                List<Quote> quoList = [select Id, Quote_Type__c from Quote where Id = :quoId];
+                String rt = quoList[0].Quote_Type__c;
+                isService = rt == 'service';
+            }
+
+            if (oppId != null && oppId.length() > 0) {
+                List<Opportunity> oppList = [select Id, RecordTypeId from Opportunity where Id = :oppId];
+                String rt = oppList[0].RecordTypeId;
+                isService = rt.substring(0, 15) == System.Label.RT_SSBD_Service;
+            }
+        }
+
+        String cStr = '';
+        if (cid != null && cid.length() > 0) {
+            cStr = '&copyid=' + cid;
+        }
+        String rStr = '';
+        if (rturl != null && rturl.length() > 0) {
+            rStr = '&retURL=' + rturl;
+        }
+        if (oid != null && oid.length() > 0) {
+            if (isService == true) {
+                pr = new PageReference('/apex/NewQuoteService?oppid=' + oid + '&openType=service' + cStr + rStr);
+            } else {
+                pr = new PageReference('/apex/NewQuoteEntry?oppid=' + oid + cStr + rStr);
+            }
+        } else if (qid != null && qid.length() > 0) {
+            if (isService == true) {
+                pr = new PageReference('/apex/NewQuoteService?id=' + qid + '&openType=service' + rStr);
+            } else {
+                pr = new PageReference('/apex/NewQuoteEntry?id=' + qid + rStr);
+            }
+        }
+
+        pr.setRedirect(true);
+        return pr;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewQuoteDevideController.cls-meta.xml b/scr/classes/NewQuoteDevideController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewQuoteDevideController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewQuoteDevideControllerTest.cls b/scr/classes/NewQuoteDevideControllerTest.cls
new file mode 100644
index 0000000..7a262fc
--- /dev/null
+++ b/scr/classes/NewQuoteDevideControllerTest.cls
@@ -0,0 +1,69 @@
+@isTest
+private class NewQuoteDevideControllerTest {
+
+	@isTest static void test_init() {
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        Quote quo2 = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1,
+            Quote_Type__c = 'service'
+        );
+        insert quo2;
+
+		PageReference page = new PageReference('/apex/NewQuoteDevide?oppid=' + opp.Id + '&openType=');
+        System.Test.setCurrentPage(page);
+        NewQuoteDevideController controller = new NewQuoteDevideController();
+
+        controller.init();
+
+        PageReference page2 = new PageReference('/apex/NewQuoteDevide?oppid=' + opp.Id + '&openType=service');
+        System.Test.setCurrentPage(page2);
+        NewQuoteDevideController controller2 = new NewQuoteDevideController();
+
+        controller2.init();
+
+        PageReference page3 = new PageReference('/apex/NewQuoteDevide?id=' + quo.Id);
+        System.Test.setCurrentPage(page3);
+        NewQuoteDevideController controller3 = new NewQuoteDevideController();
+
+        controller3.init();
+
+        PageReference page4 = new PageReference('/apex/NewQuoteDevide?id=' + quo2.Id);
+        System.Test.setCurrentPage(page4);
+        NewQuoteDevideController controller4 = new NewQuoteDevideController();
+
+        controller4.init();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewQuoteDevideControllerTest.cls-meta.xml b/scr/classes/NewQuoteDevideControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewQuoteDevideControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewQuoteEntryController.cls b/scr/classes/NewQuoteEntryController.cls
new file mode 100644
index 0000000..bec9234
--- /dev/null
+++ b/scr/classes/NewQuoteEntryController.cls
@@ -0,0 +1,5058 @@
+public without sharing class NewQuoteEntryController {
+    public Integer quoteEntryMaxLine {get; private set;}
+    public Integer quoteEntryMaxSet {get; private set;}
+
+    public Id oppId { get; set; }
+    public Id quoId {get;set;}
+    public Id pricebook2Id {get;set;}
+    public Id accountId {get;set;}
+    public String currencyIsoCode {get;set;}
+
+    public boolean specialerrorflg {get;set;}
+    public boolean errorflg {get;set;}
+    public String errorMessage {get;set;}
+
+    public boolean Messageflg {get;set;}
+    public String Message {get;set;}
+    
+    public Quote quo {get;set;}
+    public Decimal discount {get;set;}
+    public List<QELine> activities {get;set;}
+    private List<QELine> activitiesbk;
+    public List<QELine> tmpactivities = new List<QELine>();
+    public QELine active_activity;
+    public Boolean productStatusUpdated;
+    public List<Boolean> hidFlg {get;set;}
+    public String excel_text { get; set; }
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public boolean decideFlg { get; set; }
+    public boolean isdecide { get; set; }
+    public boolean printFlg { get; set; }
+    private boolean doDecide { get; set; }
+    public String productSegment { get; set; }
+    public boolean isAdmin { get; set; }
+
+    public String fileName { get; set; }
+    public String strExpirationDate { get; set; }
+    public List<QELine> csv_activities {get;set;}
+    public Blob contentFile { get; set; }
+    public String nameFile { get; set; }
+
+    public String openType { get; set; }
+    public boolean isService { get; set; }
+    public boolean is_Parts_direct { get; set; }
+    public boolean is_Parts_dealer { get; set; }
+    public boolean is_hidden_user { get; set; }
+    public boolean is_dealer_user { get; set; }
+
+    public boolean is_hidden_all { get; set; }
+    public Decimal dealer_coefficient { get; set; }
+
+    public Boolean specialDealer { get; set; }
+    //XHL-20190426-AddStart
+    public String setProduct_text { get; set; }
+    public Integer activitiesSize {get;set;}
+    public Integer singleNo {get;set;}
+    public Map<String,String> errorMap {get;set;}
+    public String singleProduct {get; private set;}
+    public Map<String,String> quoteLineSetNameDiscountMap {get; private set;}
+    public String quoteLineSetNameDiscountJson {get; private set;}
+    //XHL-20190426-AddEnd
+    public Opportunity opp {get;set;}
+
+    // WLIG-BTA8C2 XHL 20200925 -Start
+    public String initStringConcatenation;
+    public String saveStringConcatenation;
+    public Boolean verifyProductValidFlag;
+    // WLIG-BTA8C2 XHL 20200925 -End
+    private static Map<String, String> paymentTermsMap = new Map<String, String> {
+        'Z001' => '棰勬敹娆�/棰勪粯娆�',
+        'Z002' => '绔嬪嵆浠樻',
+        'Z003' => '鏈堢粨30澶╁唴浠樻',
+        'Z004' => '鏈堢粨60澶╁唴浠樻',
+        'Z005' => '鏈堢粨90澶╁唴浠樻',
+        'Z006' => '鏈堢粨120澶╁唴浠樻',
+        'Z007' => '鏈堢粨25澶╁唴浠樻',
+        'Z008' => '鏈堢粨55澶╁唴浠樻',
+        'Z009' => '鏈堢粨85澶╁唴浠樻',
+        'Z010' => '鏈堢粨115澶╁唴浠樻',
+        'Z011' => '鏈堢粨175澶╁唴浠樻',
+        'Z012' => '鏈堢粨205澶╁唴浠樻',
+        'Z013' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'Z014' => '鏈堢粨30澶╁唴浠樻',
+        'Z015' => '楠屾敹鍚�15澶╃數姹�',
+        'Z020' => '100%鍙戣揣鍚�30澶╁唴鏀粯',
+        'Z021' => '100%鍙戣揣鍚�60澶╁唴鐢垫眹鏀粯',
+        'Z030' => '鏀跺埌鍙戠エ鍚�30澶╁唴鐢垫眹',
+        'Z045' => '鏈堢粨45澶╁唴浠樻',
+        'Z060' => '鏀跺埌鍙戠エ鍚�60澶╁唴鐢垫眹',
+        'Z075' => '鏀跺埌鍙戠エ鍚�75澶╁唴鐢垫眹',
+        'Z090' => '鏀跺埌鍙戠エ鍚�90澶╁唴鐢垫眹',
+        'Z0LC' => '100% L/C (90/10)',
+        'Z120' => '鏀跺埌鍙戠エ鍚�120澶╁唴鐢垫眹',
+        'Z1LC' => '100% L/C (80/20)',
+        'Z1TT' => '90%TT ADV锛�10%TT AFTER',
+        'Z2LC' => '100% L/C (70/30)',
+        'Z2TT' => '80%TT ADV锛�20%TT AFTER',
+        'Z30E' => '涓嬫湀鏈�',
+        'Z3LC' => '100% L/C 90 days',
+        'Z3TT' => '70%TT ADV锛�30%TT AFTER',
+        'Z4LC' => '90%L/CTransfer 10%TT AFTER',
+        'Z4TT' => '100% TT AFTER',
+        'Z5LC' => '100%L/C at sight Transfer',
+        'Z5TT' => '30% TT ADV锛�50% TT AT SIGHT锛�20% TT AFTER',
+        'Z60E' => '涓�2涓湀鏈�',
+        'Z6LC' => '100%L/C (85/15)',
+        'Z6TT' => '30% TT ADV锛�60% TT AT SIGHT锛�10% TT AFTER',
+        'Z7LC' => '100% L/C (60/40)',
+        'Z7TT' => '100锛匱T AFTER(80/20)',
+        'Z8TT' => '100% TT AFTER锛�70/30锛�',
+        'Z9TT' => '100%TT鍙戣揣鍚�20澶╁唴鏀粯',
+        'ZCOD' => 'C.O.D.',
+        'ZD60' => '绔嬪嵆搴斾粯鐨� 鍒版湡鍑�鍊�',
+        'ZFR1' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'ZL6T' => '90% LC 60 days锛�10% TT AFTER',
+        'ZL95' => '95% L/C AFTER,5% L/C AFTER 6M FROM ACCEPTANCE DATE',
+        'ZLC1' => '100% L/C (90/10) Transfer',
+        'ZLC2' => '100% L/C AT SIGHT (95/5)',
+        'ZLT1' => '90%LC锛�10%TT',
+        'ZLT2' => '80%LC锛�20%TT',
+        'ZLT3' => '70%LC锛�30%TT',
+        'ZLT4' => '95%LC锛�5%TT',
+        'ZLT5' => '50%L/C锛�50%TT after',
+        'ZT20' => '20% T/T ADV,80% T/T AFTER',
+        'ZT30' => '30% T/T ADV, 70%T/T AFTER',
+        'ZT35' => '35% TT ADV锛�65% TT AFTER',
+        'ZT40' => '40% TT ADV锛�60% TT AFTER',
+        'ZT50' => '50% TT ADV锛�50% TT AFTER',
+        'ZT55' => '95%TT ADV锛�5%TT AFTER',
+        'ZT90' => '楠屾敹鍚堟牸鍚嶵/T鏀粯90%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯10%',
+        'ZTT1' => 'TT AFTER DELIVERY 45 DAY',
+        'ZTT2' => 'TT AFTER DELIVERY 120 DAY',
+        'ZTT3' => '100%TT鍙戣揣鍚�15涓伐浣滄棩鍐呮敮浠�',
+        'ZTT4' => '楠屾敹鍚堟牸鍚嶵/T鏀粯80%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯20%',
+        'ZZ60' => '60 DAYS AFTER ISSUING INVOICE',
+        'ZZ95' => '95% L/C AFTER,5% T/T AFTER 6M FROM ACCEPTANCE DATE',
+        'ZZLC' => '100% L/C AT SIGHT',
+        'ZZTT' => '100% TT IN ADVANCE',
+        'Z022' => '100% T/T WITHIN 90 DAYS AFTER SHIPMENT'
+    };
+
+    public NewQuoteEntryController() {
+
+        initStringConcatenation = '';
+        saveStringConcatenation = '';
+        verifyProductValidFlag = false;
+
+
+        singleProduct  = System.Label.SingleProduct;
+        quoteEntryMaxLine = Integer.valueOf(System.Label.QuoteEntryMaxLine);
+        quoteEntryMaxSet = Integer.valueOf(System.Label.QuoteEntryMaxSet);
+        hidFlg = new List<Boolean>(30);
+        for (Integer i = 0; i < 30; i++) {
+            if (i<quoteEntryMaxSet) {
+                hidFlg[i] = true;
+            } else {
+                hidFlg[i] = false;
+            }
+        }
+
+        productStatusUpdated = false;
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        System.debug('path: ' + path);
+        System.debug('baseUrl: ' + baseUrl);
+        System.debug('rtUrl: ' + rtUrl);
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+
+        //system.debug('22222222222222' + quo);
+    }
+
+    public NewQuoteEntryController(ApexPages.StandardController controller) {
+        this();
+    }
+
+    public void init () {
+        specialerrorflg = false ;
+        activitiesSize = 0;
+        errorflg = false;
+        errormessage = null;
+
+        decideFlg = false;
+        isdecide = false;
+        printFlg = false;
+        doDecide = false;
+        productSegment = '';
+        errorMap = new Map<String,String>();
+        quoteLineSetNameDiscountMap = new Map<String,String>();
+        quoteLineSetNameDiscountJson = '';
+        isAdmin = false;
+        String profileId = UserInfo.getProfileId();
+        profileId = profileId.substring(0, 15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+        //system.debug('profileId_20190517_' + profileId);
+        String userid = UserInfo.getUserId();
+        User loginUser = [select id, CanCancelDecideQuote__c from user where Id = :userid];
+        if (new_profileId == System.Label.SystemAdmin || new_profileId == System.Label.SystemAdmin2 
+            || new_profileId == System.Label.SystemAdmin || new_profileId == System.Label.SystemAdmin2
+            || loginUser.CanCancelDecideQuote__c == true) {
+            isAdmin = true;
+        }
+
+        openType = System.currentPageReference().getParameters().get('openType');
+        isService = openType == 'service' ? true : false;
+        is_Parts_direct = false;
+        is_Parts_dealer = false;
+        is_hidden_user = false;
+
+        if (profileId == System.Label.RT_BS_No_Price || new_profileId == System.Label.RT_BS_No_Price) {// || profileId == System.Label.SystemAdmin) {
+            is_hidden_user = true;
+            //system.debug('is_hidden_user_1_1_1_1_' + is_hidden_user);
+        }
+        is_dealer_user = false;
+        //system.debug('UserInfo.getUserType()__20190517_'+UserInfo.getUserType());
+        //system.debug('UserInfo.getUserId()__20190517_1_'+UserInfo.getUserId().substring(0, 15));
+
+        if (UserInfo.getUserType() == 'PowerPartner' || UserInfo.getUserId().substring(0, 15) == '00528000002PBPf') {
+            is_dealer_user = true;
+            //system.debug('is_dealer_user_1_1_1_1_' + is_dealer_user);
+        }
+
+        is_hidden_all = false;
+        specialDealer = false;
+
+        //Quote
+        
+        //system.debug('quo---cccc: '+quo);
+        quo = new Quote();
+        quo.Quote_Type__c = 'sales';
+        if (isService == true) {
+            quo.Quote_Type__c = 'service';
+        }
+        quo.Comment__c  = '1)  The payment terms are - .\n';
+        quo.Comment__c += '浠樻鏂瑰紡 - 銆俓n';
+        quo.Comment__c += '2)  Quoation valid until - .\n';
+        quo.Comment__c += '鎶ヤ环鏈夋晥鏈熷埌 - 銆俓n';
+        quo.Comment__c += '3)  All the commodoties come with - year\'s manufacturer warranty.\n';
+        quo.Comment__c += '鎵�鏈夊晢鍝佸惈 - 骞村巶瀹朵繚淇�俓n';
+        if (isService == false) {
+            quo.Comment__c += '4)  The above quotations are - prices, Commodoties shipped to the clien\'s requirements.\n';
+            quo.Comment__c += '涓婅堪鎶ヤ环涓� - 浠凤紝鍟嗗搧閫佽嚦瀹㈡埛鎸囧畾鍦扮偣銆俓n';
+            quo.Comment__c += '5)  The above quotations are all - .\n';
+            quo.Comment__c += '涓婅堪鎶ヤ环鍧囦负 - 浠枫�俓n';
+            quo.Comment__c += '6)  Configuration as per attached.\n';
+            quo.Comment__c += '閰嶇疆娓呭崟璇﹁闄勪欢銆�';
+        } else {
+            quo.Comment__c += '4)  The above quotations are all - .\n';
+            quo.Comment__c += '涓婅堪鎶ヤ环鍧囦负 - 浠枫�俓n';
+            quo.Comment__c += '5)  Configuration as per attached.\n';
+            quo.Comment__c += '閰嶇疆娓呭崟璇﹁闄勪欢銆�';
+        }
+
+        if (isService == true) {
+            quo.SetName1__c = '闆朵欢璐圭敤';
+            quo.SetQty1__c = 1;
+            quo.SetName2__c = '缁翠慨璐�';
+            quo.SetQty2__c = 1;
+            quo.SetName3__c = '鍏朵粬璐圭敤';
+            quo.SetQty3__c = 1;
+        }
+       
+        quo = new Quote();
+        quo.Quote_Type__c = 'sales';
+        if (isService == true) {
+            quo.Quote_Type__c = 'service';
+        }
+        quo.Comment__c  = '1)  The payment terms are - .\n';
+        quo.Comment__c += '浠樻鏂瑰紡 - 銆俓n';
+        quo.Comment__c += '2)  Quoation valid until - .\n';
+        quo.Comment__c += '鎶ヤ环鏈夋晥鏈熷埌 - 銆俓n';
+        quo.Comment__c += '3)  All the commodoties come with - year\'s manufacturer warranty.\n';
+        quo.Comment__c += '鎵�鏈夊晢鍝佸惈 - 骞村巶瀹朵繚淇�俓n';
+        if (isService == false) {
+            quo.Comment__c += '4)  The above quotations are - prices, Commodoties shipped to the clien\'s requirements.\n';
+            quo.Comment__c += '涓婅堪鎶ヤ环涓� - 浠凤紝鍟嗗搧閫佽嚦瀹㈡埛鎸囧畾鍦扮偣銆俓n';
+            quo.Comment__c += '5)  The above quotations are all - .\n';
+            quo.Comment__c += '涓婅堪鎶ヤ环鍧囦负 - 浠枫�俓n';
+            quo.Comment__c += '6)  Configuration as per attached.\n';
+            quo.Comment__c += '閰嶇疆娓呭崟璇﹁闄勪欢銆�';
+        } else {
+            quo.Comment__c += '4)  The above quotations are all - .\n';
+            quo.Comment__c += '涓婅堪鎶ヤ环鍧囦负 - 浠枫�俓n';
+            quo.Comment__c += '5)  Configuration as per attached.\n';
+            quo.Comment__c += '閰嶇疆娓呭崟璇﹁闄勪欢銆�';
+        }
+
+        if (isService == true) {
+            quo.SetName1__c = '闆朵欢璐圭敤';
+            quo.SetQty1__c = 1;
+            quo.SetName2__c = '缁翠慨璐�';
+            quo.SetQty2__c = 1;
+            quo.SetName3__c = '鍏朵粬璐圭敤';
+            quo.SetQty3__c = 1;
+        }
+
+        //Opportunityid
+        Opportunity oppRecord = null;
+        if (oppId==null) {
+            oppId = System.currentPageReference().getParameters().get('oppid');
+
+            if (oppId==Null) {
+                quoId = System.currentPageReference().getParameters().get('Id');
+
+                List<Quote> ql = New List<Quote>();
+                ql = [select Id,OpportunityId From Quote Where Id =:quoId];
+                if (ql.size()>0) {
+                    oppId = ql[0].OpportunityId;
+                }
+            } 
+
+            List<Opportunity> oppList = New List<Opportunity>();
+            oppList = [select Id,Pricebook2Id,CurrencyIsoCode,AccountId,Is_Decided__c,ProductSegment__c,Machine_Parts__c,SalesChannel__c,Dealer__r.DummyDealer__c,
+                              IE_Discount_Normal__c,Subuse__c,IE_Discount_Special__c,Dealer_Code__c,Province__c,Dealer_Rank__c,Dealer__r.ParentId,Account.MarketVerticals__c,Trade_Type_D__c,
+                              DealerId__c 
+                         From Opportunity Where Id =:oppId];
+
+            if (oppList.size()>0) {
+                opp = oppList[0];
+                oppRecord = oppList[0];
+                pricebook2Id = oppList[0].Pricebook2Id;
+                currencyIsoCode = oppList[0].CurrencyIsoCode;
+                accountId = oppList[0].AccountId;
+                decideFlg = oppList[0].Is_Decided__c;
+                productSegment = oppList[0].ProductSegment__c;
+                if (oppList[0].Machine_Parts__c == 'Parts' && oppList[0].SalesChannel__c == 'direct') {
+                    is_Parts_direct = true;
+                } else if (oppList[0].Machine_Parts__c == 'Parts' && oppList[0].SalesChannel__c == 'dealer') {
+                    is_Parts_dealer = true;
+                }
+               
+                //if(specialdealer == true){
+                   //is_hidden_all = true;
+                //}
+            }
+        }
+        //specialDealer = StaticParameter.specialDealerMap.containsKey(((String)opp.DealerId__c).substring(0,15));
+        //specialDealer = IfspecialDealer(opp.DealerId__c);
+        if (opp != null) {
+            specialDealer = IfspecialDealer(opp.DealerId__c);
+            if(specialDealer == true){
+                is_hidden_all = true;
+            }
+        }
+        Boolean updateOrCopy = false;
+        quoId = System.currentPageReference().getParameters().get('Id');
+
+        if (quoId==null){
+            quoId = System.currentPageReference().getParameters().get('copyid');
+            if (quoId!=null){ 
+                updateOrCopy = true;
+            }
+        } else {
+            updateOrCopy = false;
+        }
+
+        Integer i;
+        
+        if (quoId==null){
+
+            List<Quote> qlCk = New List<Quote>();
+                qlCk = [select Id,OpportunityId,Opportunity.DealerId__c,OrderIsChange__c From Quote Where OpportunityId =:oppId];
+            if (qlCk.size()>0) {
+                //specialDealer =  StaticParameter.specialDealerMap.containsKey(qlCk[0].Opportunity.DealerId__c);
+                specialDealer = IfspecialDealer(qlCk[0].Opportunity.DealerId__c);
+                if(specialDealer == true){
+                    is_hidden_all = true;
+                }
+                if (activities==null){
+                    activities = new List<QELine>();
+                    for (i=0;i<quoteEntryMaxLine;i++){
+                        QELine active_activity = new QELine(i);
+                        activities.add(active_activity);
+                    }
+                }
+
+            } else {
+                Integer k;
+                List<OpportunityLineItem> oppItemList = New List<OpportunityLineItem>();
+                oppItemList = [select Id,Product2Id,ProductCode,Product2.Product_ECCode__c,Product2.Name,Quantity,UnitPrice,Description,PricebookEntryId,
+                                      PricebookEntry.SalesPrice__c,PricebookEntry.SalesPriceA__c,PricebookEntry.SalesPriceB__c,
+                                      PricebookEntry.SalesPriceC__c,Product2.ProductModels__c,PricebookEntry.Hidden_flag__c,
+                                      Opportunity.DealerId__c
+                                 From OpportunityLineItem
+                                Where OpportunityId =:oppId];
+                if (oppItemList.size()>0) {
+                    k = oppItemList.size();
+                } else {
+                    k = 0;
+                }
+                //鏂拌銉偣銉堛偝銉炽儓銉兗銉┿伄鍙栧緱
+                if (activities==null){
+                    activities = new List<QELine>();
+                    for (i=0;i<quoteEntryMaxLine;i++){
+                        QELine active_activity = new QELine(i);
+                        if (i<k) {
+                            active_activity.productName = oppItemList[i].Product2.Name;
+                            active_activity.productCode = oppItemList[i].ProductCode;
+                            active_activity.productEC = oppItemList[i].Product2.Product_ECCode__c;
+                            active_activity.pageObject.Quantity = oppItemList[i].Quantity;
+                            active_activity.pageObject.UnitPrice = oppItemList[i].UnitPrice;
+                            active_activity.pageObject.Description = oppItemList[i].Description;
+                            active_activity.totalPrice = oppItemList[i].Quantity * oppItemList[i].UnitPrice;
+                            if (isService == true) {
+                                active_activity.setName = '闆朵欢璐圭敤';
+                            } else {
+                                active_activity.setName = '鍗曞搧';
+                            }
+                            active_activity.pageObject.Set__c = '鍗曞搧';
+                            active_activity.pageObject.SingleProduct__c = true;
+                            active_activity.pageObject.PricebookEntryId = oppItemList[i].PricebookEntryId;
+                            active_activity.salesPrice = oppItemList[i].PricebookEntry.SalesPrice__c;
+                            active_activity.salesPriceA = oppItemList[i].PricebookEntry.SalesPriceA__c;
+                            active_activity.salesPriceB = oppItemList[i].PricebookEntry.SalesPriceB__c;
+                            active_activity.salesPriceC = oppItemList[i].PricebookEntry.SalesPriceC__c;
+
+                            active_activity.isProductModel = oppItemList[i].Product2.ProductModels__c;
+
+                            active_activity.hiddenflg = oppItemList[i].PricebookEntry.Hidden_flag__c;
+                            //StaticParameter.specialGroupMap.
+                            //specialDealer =  StaticParameter.specialDealerMap.containsKey(oppItemList[i].Opportunity.DealerId__c);
+                            specialDealer = IfspecialDealer(oppItemList[i].Opportunity.DealerId__c);
+                            if(specialDealer == true){
+                                is_hidden_all = true;
+                            }
+                            //system.debug();
+                            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇烽�夋嫨鐩爣瀹㈡埛---->'+oppItemList[i].Opportunity.DealerId__c));
+                            if (specialDealer || is_hidden_user == true || is_dealer_user == true && oppItemList[i].PricebookEntry.Hidden_flag__c == true) {
+                                active_activity.pageObject.UnitPrice = 0;
+                                active_activity.totalPrice = 0;
+                                system.debug('<---is_hidden_all--->03' + is_hidden_all);
+                                is_hidden_all = true;
+                                discount = 0;
+                            }
+                        }
+                        activities.add(active_activity);
+                    }
+                }
+            }
+            
+        } else {
+            system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome to edit class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+
+            String accountid;
+
+            List<Quote> quoList = 
+                [ SELECT Id,Name,QuoteNumber,Account.Name,ExpirationDate,Subtotal,Discount,TotalPrice,GrandTotal,PrintPrice__c,ShippingHandling,
+                    DeliveryLeadTime__c,PaymentTerms__c,ValidDate__c,Warranty__c,SetName1__c,Is_Decided__c,Shipment_Term__c,Shipment_Term2__c,
+                    SetName2__c,SetName3__c,SetName4__c,SetName5__c,SetName6__c,SetName7__c,SetName8__c,SetName9__c,SetName10__c,
+                    SetName11__c,SetName12__c,SetName13__c,SetName14__c,SetName15__c,SetName16__c,SetName17__c,SetName18__c,SetName19__c,
+                    SetName20__c,SetName21__c,SetName22__c,SetName23__c,SetName24__c,SetName25__c,SetName26__c,SetName27__c,SetName28__c,SetName29__c,
+                    SetName30__c,SetQty1__c,SetQty2__c,SetQty3__c,SetQty4__c,SetQty5__c,SetQty6__c,SetQty7__c,SetQty8__c,SetQty9__c,SetQty10__c,SetQty11__c,
+                    SetQty12__c,SetQty13__c,SetQty14__c,SetQty15__c,SetQty16__c,SetQty17__c,SetQty18__c,SetQty19__c,SetQty20__c,SetQty21__c,SetQty22__c,SetQty23__c,
+                    SetQty24__c,SetQty25__c,SetQty26__c,SetQty27__c,SetQty28__c,SetQty29__c,SetQty30__c,Comment__c,Custom_Price_Total__c,Custom_Price_Total_Text__c,Quote_Type__c,
+                    Main_Model__c,Main_Serial_Number__c,Service_Type__c,Contract_Number__c,Service_Date__c,Service_Finish_Date__c,Service_Engineer_Sign__c,
+                    Service_Pickup_Sign__c,Service_Check_Sign__c,Service_Location__c,Service_Status__c,Service_Content__c, Is_upload__c, Total_Price_Text__c,
+                    Discount_Normal__c,Discount_Special__c,OrderIsChange__c 
+                    FROM Quote Where Id =:quoId];
+            List<QuoteLineItem> items = 
+                [Select Id,Product2Id,Product2.Name,Product2.ProductCode,Product2.Product_ECCode__c,Quantity,Subtotal,Discount,TotalPrice,PricebookEntryId,UnitPrice,Description,Set__c,Custom_Price__c,
+                        PricebookEntry.SalesPrice__c,PricebookEntry.SalesPriceA__c,PricebookEntry.SalesPriceB__c,PricebookEntry.SalesPriceC__c,Product2.ProductModels__c,PricebookEntry.Hidden_flag__c,
+                        SingleProduct__c,SetName__c,
+                        Quote.Opportunity.DealerId__c
+                   From QuoteLineItem where Quoteid = :quoId Order by Id];
+
+            //system.debug('quoList==========>'+quoList);
+            //system.debug('items==========>'+items);
+
+            if (quoList.size() > 0) {
+                if (updateOrCopy) {
+
+                    quo = quoList[0];
+                    quo.Id = null;
+                    quo.name = null;
+                    quo.Is_Decided__c = false;
+                    quo.Is_upload__c = false;
+                } else {
+                    quo = quoList[0];
+                }
+                isdecide = quo.Is_Decided__c;
+            }
+
+            if (updateOrCopy) {
+                quoId = null;
+            }
+            quoteLineSetNameDiscountMap = new Map<String,String>();
+            activities = new List<QELine>();
+            i=0;
+            QELine c = new QELine(i);
+
+            if (items.size()>0) {
+                for (QuoteLineItem o:items) {
+
+                    if (String.isNotBlank(o.SetName__c)) {
+                        quoteLineSetNameDiscountMap.put(o.SetName__c,String.valueOf(o.Discount));
+                    }
+                    String setName = o.Set__c;
+                    Integer qty = 1;
+                    if (setName != null) {
+                        //XHL-20190426-UpdateStart
+                        if (!o.SingleProduct__c) {
+                            
+                            String fieldName = setName.substring(3);
+                            fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
+                            Decimal d_qty = (Decimal) quo.get('SetQty' + fieldName + '__c');
+                            qty = d_qty == null ? 1 : d_qty.intValue();
+                        }
+                        //XHL-20190426-UpdateEnd 
+                        
+                    }
+                    c = new QELine(isService,o,i,o.Product2.Name,o.Product2.ProductCode,o.Product2.Product_ECCode__c,qty,o.Product2.ProductModels__c,o.SingleProduct__c,o.SetName__c);
+                    //specialDealer =  StaticParameter.specialDealerMap.containsKey(o.Quote.Opportunity.DealerId__c);
+                    specialDealer = IfspecialDealer(o.Quote.Opportunity.DealerId__c);
+                    if(specialDealer == true){
+                        is_hidden_all = true;
+                    }
+                    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇烽�夋嫨鐩爣瀹㈡埛----2>'+o.Quote.Opportunity.DealerId__c));
+                    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇烽�夋嫨鐩爣瀹㈡埛----n>'+specialDealer));
+
+                    if ( specialDealer || is_hidden_user == true || is_dealer_user == true && c.hiddenflg == true) {
+                        c.pageObject.UnitPrice = 0;
+                        c.totalPrice = 0;
+                        c.customPrice = 0;
+                        system.debug('<---is_hidden_all---04>' + is_hidden_all);
+                        is_hidden_all = true;
+                        discount = 0;
+                    }
+                    activities.add(c);
+                    i++;
+
+                    if (quo.OrderIsChange__c) {
+                        String productCode = o.Product2.ProductCode;
+                        if (String.isNotBlank(productCode)) {
+                             
+                            initStringConcatenation += productCode + '|' + o.Quantity;
+                        }
+                        
+                    }
+                }
+
+                for (integer j=i;j<quoteEntryMaxLine;j++) {
+                    c = new QELine(j);
+                    activities.add(c);
+                }
+                quoteLineSetNameDiscountJson(quoteLineSetNameDiscountMap);
+                
+            } else {
+                activities = new List<QELine>();
+                for (i=0;i<quoteEntryMaxLine;i++) {
+                    QELine active_activity = new QELine(i);
+                    activities.add(active_activity);
+                }
+            }
+
+system.debug('=====is_hidden_all:' + is_hidden_all);
+            if (is_hidden_all) {
+                discount = quo.totalPrice.setScale(2, System.RoundingMode.HALF_UP);
+            } else {
+                discount = quo.Discount == null ? 0 : quo.Discount;
+
+                discount = discount.setScale(2, System.RoundingMode.HALF_UP);
+            }
+system.debug('=====discount:' + discount);
+
+            if (quoId != null) {
+                printFlg = true;
+            }
+
+            system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆 edit class  End!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+        }
+
+        Map<String, Decimal> ddMap = new Map<String, Decimal>();
+        String key1 = '';
+        String key2 = '';
+        List<Dealer_Discount__c> ddList = [select id, Dealer_Rank_F__c,Product_Segment__c, DimensionField1__c, DimensionField2__c, DimensionValue1__c, DimensionValue2__c, Dealer_Rank__c from Dealer_Discount__c where Product_Segment__c = :productSegment];
+        for (Dealer_Discount__c dd : ddList) {
+            ddMap.put(dd.DimensionValue1__c + '|' + dd.DimensionValue2__c, dd.Dealer_Rank_F__c);
+            key1 = dd.DimensionField1__c == null ? '' : dd.DimensionField1__c;
+            key2 = dd.DimensionField2__c == null ? '' : dd.DimensionField2__c;
+        }
+
+        String keyF = ((key1 == '' || oppRecord.get(key1) == null) ? 'null' : oppRecord.get(key1)) + '|' + ((key2 == '' || oppRecord.get(key2) == null) ? 'null' : oppRecord.get(key2));
+
+        quo.Discount_Normal__c = 100 - (ddMap.get(keyF) == null ? 100.0 : ddMap.get(keyF));
+        dealer_coefficient = quo.Discount_Normal__c;
+system.debug('=====keyF:' + keyF);
+system.debug('=====Discount_Normal__c:' + quo.Discount_Normal__c);
+        activitiesSize = activities.size();
+
+        system.debug(specialDealer);
+    }
+
+    public PageReference Refresh() {
+
+        List<Id> Idlist = New List<Id>();
+        for (QELine t:activities) {
+            Idlist.add(t.pageObject.PricebookEntryId);
+        }
+
+        if (Idlist.size()==0) {
+            errorflg = true;
+            errormessage = System.Label.Error_Message01;
+            return null;
+        }
+
+        //List<PricebookEntry> pbes = [
+        //            select Id,Product2Id,ProductCode,Product2.Product_ECCode__c,SalesPrice__c,SalesPriceA__c,SalesPriceB__c,SalesPriceC__c,Hidden_flag__c,Product2.ProductStatus__c
+        //            FROM PricebookEntry where Id in :Idlist];
+        //20191113-XHL---Start-灏嗕骇鍝佺姸鎬佺敤浜у搧鐘舵��(鍏紡)鏇挎崲
+        List<PricebookEntry> pbes = [
+                    select Id,Product2Id,ProductCode,Product2.Product_ECCode__c,SalesPrice__c,SalesPriceA__c,SalesPriceB__c,SalesPriceC__c,Hidden_flag__c,Product2.ProductStatus__c,Product2.ProductStatusFormula__c
+                    FROM PricebookEntry where Id in :Idlist];
+        //20191113-XHL---End-灏嗕骇鍝佺姸鎬佺敤浜у搧鐘舵��(鍏紡)鏇挎崲
+        if (pbes.size()==0) {
+            errorflg = true;
+            errormessage = System.Label.Error_Message01;
+            return null;
+        }
+
+        Map<String, PricebookEntry> tempMap = new Map<String, PricebookEntry>();
+
+        for (PricebookEntry pbe:pbes) {
+            tempMap.put(pbe.Id, pbe);
+        }
+        system.debug('<---is_hidden_all---05>' + is_hidden_all);
+        is_hidden_all = false;
+        for (QELine t:activities) {
+            PricebookEntry tmpPbe = tempMap.get(t.pageObject.PricebookEntryId);
+            if (tmpPbe != null) {
+                if (tmpPbe.SalesPrice__c != null && tmpPbe.Product2.ProductStatus__c == '1' && ( specialDealer == false && is_hidden_user == false && (is_dealer_user == false || tmpPbe.Hidden_flag__c == false))) {
+                //20191113-XHL---灏嗕骇鍝佺姸鎬佺敤浜у搧鐘舵��(鍏紡)鏇挎崲
+                //if (tmpPbe.SalesPrice__c != null && tmpPbe.Product2.ProductStatusFormula__c == '1' && (is_hidden_user == false && (is_dealer_user == false || tmpPbe.Hidden_flag__c == false))) {
+                    t.pageObject.UnitPrice = tmpPbe.SalesPrice__c;
+                    t.salesPrice = tmpPbe.SalesPrice__c;
+                    t.salesPriceA = tmpPbe.SalesPriceA__c;
+                    t.salesPriceB = tmpPbe.SalesPriceB__c;
+                    t.salesPriceC = tmpPbe.SalesPriceC__c;
+                } else if (tmpPbe.SalesPrice__c != null && tmpPbe.Product2.ProductStatus__c == '0' && ( specialDealer == false && is_hidden_user == false && (is_dealer_user == false || tmpPbe.Hidden_flag__c == false))) {
+                //20191113-XHL---灏嗕骇鍝佺姸鎬佺敤浜у搧鐘舵��(鍏紡)鏇挎崲
+                //} else if (tmpPbe.SalesPrice__c != null && tmpPbe.Product2.ProductStatusFormula__c == '0' && (is_hidden_user == false && (is_dealer_user == false || tmpPbe.Hidden_flag__c == false))) {
+                    t.pageObject.UnitPrice = 0;
+                    t.salesPrice = 0;
+                    t.salesPriceA = 0;
+                    t.salesPriceB = 0;
+                    t.salesPriceC = 0;
+                } else {
+                    t.pageObject.UnitPrice = 0;
+                    t.salesPrice = 0;
+                    t.salesPriceA = 0;
+                    t.salesPriceB = 0;
+                    t.salesPriceC = 0;
+
+                    is_hidden_all = true;
+                    discount = 0;
+                }
+            }
+        }
+
+        return null;
+    }
+
+    //excelImport
+    public PageReference excelImport() {
+/*        system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼媁elcome to excelImport!!');
+        system.debug('鈻尖柤鈻尖柤鈻糴xcel_text:' + excel_text);
+        //opp銇敾闈€伄鍊ゃ倰瑷畾
+        setOppFromOppInfo();
+
+        errorflg = false;
+        errormessage = null;
+
+        //鏃㈠瓨銉囥兗銈挎暟銇⒑瑾�
+        Integer j = 0;
+        for (QELine s:activities) {
+            if ((s.productName==null) || (s.productName=='')) {
+                break;
+            }
+            j++;
+        }
+
+        //=======Temporary=====
+        tmpactivities = activities;
+
+        //=======Initialize=========
+        activities = new List<QELine>();
+        Integer i = 0;
+        Integer xlscnt = 0;
+        Integer rightcnt = 0; // 鎴愬姛銇椼仧鏁般倰銈偊銉炽儓
+
+        string[] xlslists = excel_text.split('\n',-1);
+        List<string> xlslist = New list<string>();
+        List<string> codelist = New List<string>();
+        List<Integer> Quantitylist = New List<Integer>();
+        List<string> setlist = New List<string>();
+
+        Map<String, Integer> mp = new Map<String, Integer>();
+        string xlscode;
+        Integer xlsQuantity;
+        string xlset;
+
+        try {
+            for (string xls:xlslists) {
+                if (xls==null || xls=='') {
+                    //null
+                } else {
+                    xlscode = null;
+                    xlsQuantity = null;
+                    xlset = null;
+                    xlslist = xls.split('\t',-1);
+                    Integer iCount = 0;
+                    for (String s:xlslist) {
+                        if (iCount== 1) {
+                            if (s=='' || s==null) {
+                                errorflg = true;
+                                errormessage = System.Label.Error_Message02;
+                                activities = tmpactivities;
+                                return null;
+                            } else {
+                                s = s.trim();
+                                xlsQuantity = Integer.valueOf(s);
+                                Quantitylist.add(xlsQuantity);
+                            }
+                        } else if (iCount== 2) {
+                            if (s=='' || s==null) {
+                                errorflg = true;
+                                errormessage = System.Label.Error_Message02;
+                                activities = tmpactivities;
+                                return null;
+                            } else {
+                                s = s.trim();
+                                setlist.add(s);
+                                xlset = s;
+                            }
+
+                        } else {
+                            if (s=='' || s==null) {
+                                errorflg = true;
+                                errormessage = System.Label.Error_Message02;
+                                activities = tmpactivities;
+                                return null;
+                            } else {
+                                s = s.trim();
+                                codelist.add(s);
+                                xlscode = s;
+                            }
+                        }
+                        iCount++;
+                        if (iCount == 3) {
+                            iCount = 0;
+                        }
+                    }
+                    //mp.put(xlscode, xlsQuantity);
+                    xlscnt++;
+                }
+            }
+        } catch(Exception ex) {
+            activities = tmpactivities;
+            errorflg = true;
+            errormessage = System.Label.Error_Message02;
+            return null;
+        }
+
+system.debug('codelist:::::'+codelist.size());
+system.debug('xlscnt:::::' + xlscnt);
+
+        if (codelist.size()==0 || Quantitylist.size()==0 || setlist.size()==0) {
+            activities = tmpactivities;
+            errorflg = true;
+            errormessage = System.Label.Error_Message02;
+            return null;
+        }
+
+        xlscnt = j + xlscnt;
+        if (xlscnt>quoteEntryMaxLine) {
+            activities = tmpactivities;
+            errorflg = true;
+            errormessage = System.Label.Error_Message03;
+            return null;
+        }
+
+        i = 0;
+        boolean lineflg = false;
+        for (QELine t:tmpactivities) {
+            if (i==j) {
+                Map<String, Product_Search__c> mpProduct2 = new Map<String, Product_Search__c>();                     // key銇孭roductCode銇с仚銆�
+                //List<Product_Search__c> items = [select Id,Name,ProductCode__c,
+                //      ProductDescription__c,ProductStatus__c,Pricebook__c,Product__c 
+                //      FROM Product_Search__c Where Pricebook__c = :pricebook2Id and ProductCode__c In :codelist];
+                List<Product_Search__c> items = [select Id,Name,ProductCode__c,
+                        ProductDescription__c,ProductStatus__c,Product__c 
+                        FROM Product_Search__c Where ProductCode__c In :codelist];
+                List<String> forSelect = new List<String>();
+                for (Product_Search__c prd:items) {
+                    mpProduct2.put(prd.ProductCode__c, prd);
+                    forSelect.add(prd.Product__c);
+                }
+
+                Map<String, PricebookEntry> entries = new Map<String, PricebookEntry>();            // key銇孭roductCode銇с仚銆�
+                List<PricebookEntry> pbes = [
+                    select Id,Product2Id,ProductCode,SalesPrice__c,SalesPriceA__c,SalesPriceB__c,SalesPriceC__c
+                      FROM PricebookEntry where Pricebook2Id = :pricebook2Id
+                       and CurrencyIsoCode =:currencyIsoCode and Product2Id in : forSelect];
+
+                Map<String, String> tempMap = new Map<String, String>();
+
+                for (PricebookEntry pbe:pbes) {
+                    entries.put(pbe.ProductCode, pbe);
+                    tempMap.put(pbe.Product2Id,pbe.Id);
+                }
+
+                for (Integer l=0;l<codelist.size();l++) {
+                    Product_Search__c prd = mpProduct2.get(codelist[l]);
+                    if (prd != null) {
+                        PricebookEntry pbe = entries.get(codelist[l]);
+                        QELine c = null;
+                        if (pbe != null) {
+                            Decimal sp0 = pbe.SalesPrice__c;
+                            Decimal sp1 = pbe.SalesPriceA__c;
+                            Decimal sp2 = pbe.SalesPriceB__c;
+                            Decimal sp3 = pbe.SalesPriceC__c;
+                            c = new QELine(isService, i, prd.Name, prd.ProductCode__c, pbe.Id, pbe.Product2Id, Quantitylist[l],setlist[l], sp0, sp1, sp2, sp3);
+                        } else {
+                            continue;
+                        }
+                        activities.add(c);
+                        i++;
+                        rightcnt++;
+                        lineflg = true;
+                    }
+                }
+                if (lineflg==true) {
+                    i--;
+                } else {
+                    QELine a = New QELine(t, i);
+                    activities.add(a);
+                }
+            } else {
+                QELine a = New QELine(t, i);
+                activities.add(a);
+            }
+            i++;
+            if (i>149) {
+                break;
+            }
+        }
+        // message銈掑嚭銇�
+        errorflg = true;
+        errormessage = '鏁版嵁瀵煎叆缁撴潫锛屽鍏� ' + codelist.size() + ' 浠讹紝鎴愬姛' + rightcnt + ' 浠�';
+*/
+        return null;
+
+    }
+
+     //BackButton
+    public PageReference BackBtn() {
+        String url = baseUrl;
+        if (rtUrl != null && rtUrl.length() > 0) {
+            url += rtUrl.replace('/production', '');
+        } else {
+            url += '\\' + oppid;
+        }
+        return new Pagereference(url);
+    }
+
+    public PageReference Save() {
+
+        system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome to Save class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+        //system.debug('=====save discount:' + discount);
+
+        errorflg = false;
+        errormessage = null;
+        Savepoint sp = Database.setSavepoint();
+
+        try {
+
+            //銉囥兗銈裤儊銈с儍銈�
+            if (dataCheck() ==false) {
+                return null;
+            }
+
+            String url = baseUrl;
+            if (rtUrl != null && rtUrl.length() > 0) {
+                url += rtUrl.replace('/production', '');
+            } else {
+                url += '\\' + oppid;
+            }
+            system.debug('url++++++' + url);
+            PageReference pageRef = new Pagereference(url);
+
+            if (dataEntry()==false) {
+                //msg
+                return null;
+            } else {
+                errorflg = true;
+                if (specialerrorflg) {
+                    errorMessage = String.isBlank(errorMessage) ?System.Label.Info_Message01:System.Label.Info_Message01 +errorMessage;
+                } else {
+                    // errorMessage = System.Label.Info_Message01 ;
+
+                    errorMessage = String.isBlank(errorMessage) ?System.Label.Info_Message01:System.Label.Info_Message01 +errorMessage;
+                    // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '娉ㄦ剰锛侊紒锛�'+errorMessage));
+                }
+                //system.debug('errorMessage20190524' + errorMessage);
+                
+                return null;
+            }
+
+        } catch (DmlException de) {
+            Database.rollback(sp);
+            errorflg = true;
+            errormessage = de.getDmlMessage(0);           // 锛戜欢鐩伄銈ㄣ儵銉笺伄銇胯〃绀�
+            system.debug(Logginglevel.ERROR, de.getMessage());
+            system.debug(Logginglevel.ERROR, de.getStackTraceString());
+        } catch (Exception e) {
+            Database.rollback(sp);
+            errorflg = true;
+            errormessage = e.getMessage();
+            system.debug(Logginglevel.ERROR, e.getMessage());
+            system.debug(Logginglevel.ERROR, e.getStackTraceString());
+        }
+
+        return null;
+
+    }
+
+    //OppReflection button
+    public PageReference OppReflection() {
+        //opp銇敾闈€伄鍊ゃ倰瑷畾
+        setOppFromOppInfo();
+        Savepoint sp = Database.setSavepoint();
+        try {
+            errorflg = false;
+            errormessage = null;
+
+            //銉囥兗銈裤儊銈с儍銈�
+            if (dataCheck() ==false) {
+                return null;
+            }
+
+            String url = baseUrl;
+            if (rtUrl != null && rtUrl.length() > 0) {
+                url += rtUrl.replace('/production', '');
+            } else {
+                url += '\\' + oppid;
+            }
+            PageReference pageRef = new Pagereference(url);
+            if (dataEntry()==false) {
+                //msg
+                return null;
+            } else {
+                //msg
+                return pageRef;
+            }
+        } catch (DmlException de) {
+            Database.rollback(sp);
+            errorflg = true;
+            errormessage = de.getDmlMessage(0);        
+            system.debug(Logginglevel.ERROR, de.getMessage());
+            system.debug(Logginglevel.ERROR, de.getStackTraceString());
+        } catch (Exception e) {
+            Database.rollback(sp);
+            errorflg = true;
+            errormessage = e.getMessage();
+            system.debug(Logginglevel.ERROR, e.getMessage());
+            system.debug(Logginglevel.ERROR, e.getStackTraceString());
+        }
+        
+        return null;
+    }
+
+    public PageReference Decide() {
+        system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome to Decide class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+
+        if (quo.Is_upload__c == true) {
+            errorflg = true;
+            errorMessage = '鎶ヤ环宸茬粡涓婁紶锛屼笉鑳藉啀娆″喅瀹氥�傝鍐嶆姤浠峰悗锛屽喅瀹氬苟涓婁紶鏂扮殑鎶ヤ环銆�';
+            return null;
+        }
+
+        boolean hasDetail = false;
+        if (activities.size()>0) {
+            for (QELine s:activities) {
+                if (s.pageObject.PricebookEntryId != null && s.productName != null && s.productName != '') {
+                    hasDetail = true;
+                    break;
+                }
+            }
+        }
+
+        if (hasDetail == false) {
+            errorflg = true;
+            errorMessage = '涓嶈兘鍐冲畾娌℃湁浜у搧鏄庣粏鐨勬姤浠枫��';
+            return null;
+        }
+        doDecide = true;
+        Save();
+        decideORundecideQuote(quo.Id,true);
+        
+        String url = baseUrl + '/apex/NewQuoteDevide?Id=' + quoId + '&retURL=' + rtUrl;
+        PageReference pageRef = new Pagereference(url);
+
+        if (errorflg == false || errorMessage.startsWith(System.Label.Info_Message01)) {
+            return pageRef;
+        }
+        
+        return null;
+    }
+
+    public PageReference UnDecide() {
+        system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome to unDecide class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+        errorflg = false;
+        errormessage = null;
+        Savepoint sp = Database.setSavepoint();
+
+        try {
+            Quote q = New Quote();
+            q.Id = quo.Id;
+            q.Is_Decided__c = false;
+
+            Opportunity o = New Opportunity();
+            List<Opportunity> os = [select Id From Opportunity Where Id =:oppid];
+            if (os.size()>0) {
+                o = os[0];
+                o.Is_Decided__c = false;
+                o.Quote_Decide_User__c = null;
+            }
+
+            update q;
+            update o;
+            decideORundecideQuote(q.Id,true);
+            String url = baseUrl + '/apex/NewQuoteDevide?Id=' + quoId + '&retURL=' + rtUrl;
+            PageReference pageRef = new Pagereference(url);
+            if (errorflg == false) {
+                return pageRef;
+            }
+        } catch (DmlException de) {
+            Database.rollback(sp);
+            errorflg = true;
+            errormessage = de.getDmlMessage(0);           // 锛戜欢鐩伄銈ㄣ儵銉笺伄銇胯〃绀�
+            system.debug(Logginglevel.ERROR, de.getMessage());
+            system.debug(Logginglevel.ERROR, de.getStackTraceString());
+        } catch (Exception e) {
+            Database.rollback(sp);
+            errorflg = true;
+            errormessage = e.getMessage();
+            system.debug(Logginglevel.ERROR, e.getMessage());
+            system.debug(Logginglevel.ERROR, e.getStackTraceString());
+        }
+
+        return null;
+    }
+
+    public boolean dataEntry() {
+
+        system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome to dataEntry class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+
+        Boolean error = false;
+        Boolean detail = true;
+
+        //Quote-------------------------------------------------------------
+        //List<Quote> maxQuote_No = [select QuoteNumber From Quote Where OpportunityId = :oppid order by QuoteNumber desc NULLS LAST limit 1];
+        //String oppNo;
+        //Integer l = 1;
+        //if (maxQuote_No.size()>0) {
+        //    try {
+        //        oppNo = maxQuote_No[0].QuoteNumber;
+        //        l = Integer.valueOf(oppNo) + 1;
+        //    } catch (System.TypeException e) {
+        //        system.debug('maxQuote_No Error: quote.id=' + maxQuote_No[0].id);
+        //    }
+        //} else {
+        //    system.debug('first Quote');
+        //}
+        //oppNo = String.valueof(l);
+
+        //while (oppNo.length() < 8){
+        //    oppNo = '0' + oppNo;
+        //}
+
+        Quote q = New Quote();
+
+        if (quoId==null) {
+            q = quo.clone();
+            q.OpportunityId = oppId;
+
+            if (detail == true) {
+                if (pricebook2Id==null) {
+                    errormessage = System.Label.Error_Message04;
+                    errorflg = true;
+                    return false;
+                } else {
+                    q.Pricebook2Id = pricebook2Id;
+                }
+            }
+            
+        } else {
+
+            q = quo.clone();
+            q.Id = quoId;
+            if (q.Pricebook2Id ==null) {
+                if (detail == true) {
+                    if (pricebook2Id==null) {
+                        errormessage = System.Label.Error_Message04;
+                        errorflg = true;
+                         return false;
+                    } else {
+                        q.Pricebook2Id = pricebook2Id;
+                    }
+                }
+            }
+        }
+
+        if (quoId==null) {
+            //q.PriceRefreshDate__c = Date.today();
+        }
+        if (productStatusUpdated) {
+            //q.PriceRefreshDate__c = Date.today();
+        }
+        
+        q.Name = quo.name;
+        system.debug(opp.Account.MarketVerticals__c +'@@@@@@@@'+opp.Trade_Type_D__c);
+        if (doDecide == true) {
+            List<Quote> decideQuote = new List<Quote>();
+            //涓嶈兘鍐冲畾澶氫釜鎶ヤ环锛屾埓瀹�
+            decideQuote=[SELECT id FROM Quote WHERE OpportunityId = :opp.Id AND Is_Decided__c = true];
+            if(decideQuote.size() > 0){
+                errorflg = true;
+                errorMessage = '宸插瓨鍦ㄥ喅瀹氱殑鎶ヤ环锛屼笉鑳藉喅瀹氭柊鐨勬姤浠�';
+                return false;
+            }
+            q.Is_Decided__c = true;
+            if(opp.Account.MarketVerticals__c == 'Clinical'&&opp.Trade_Type_D__c == 'Taxation'){
+                if(opp.Dealer__r.DummyDealer__c == true){
+                    String backStr = LicenseCheckUtil.LicenseCheck(opp.AccountId);
+                    system.debug('DummyDealer__c ' + backStr);
+                    if(backStr != '1'){
+                        errorflg = true;
+                        errorMessage = backStr + '锛屼笉鑳藉喅瀹氭姤浠枫��';
+                        return false;
+                    }
+                }else{
+                    String backStr = LicenseCheckUtil.LicenseCheck(opp.Dealer__r.ParentID);
+                    system.debug('Parent' + backStr);
+                    if(backStr != '1'){
+                        errorflg = true;
+                        errorMessage = backStr + '锛屼笉鑳藉喅瀹氭姤浠枫��';
+                        return false;
+                    }
+                }
+            }
+        }else{
+             if(opp.Account.MarketVerticals__c == 'Clinical'&&opp.Trade_Type_D__c == 'Taxation'){
+                if(opp.Dealer__r.DummyDealer__c == true){
+                    String backStr = LicenseCheckUtil.LicenseCheck(opp.AccountId);
+                    system.debug('DummyDealer__c' + backStr);
+                    if(backStr != '1'){
+                        errorMessage = backStr;
+                        specialerrorflg = true;
+
+                    }
+                }else{
+                    String backStr = LicenseCheckUtil.LicenseCheck(opp.Dealer__r.ParentID);
+                    system.debug('Parent' + backStr);
+                    if(backStr != '1'){
+                        errorMessage = backStr;
+                        specialerrorflg = true;
+
+                    }
+                }
+            }
+        }
+        String quoId1 = '';
+        if (quoId==null) {
+            insert q;
+            quoId1 = q.Id;
+            printFlg = true;
+        } else {
+            
+            update q;
+            quoId1 = q.Id;
+        }
+
+        List<QuoteLineItem> qlist = New List<QuoteLineItem>();
+        qlist=[Select Id From QuoteLineItem Where QuoteId =:quoId1];
+        if (qlist.size()>0) {
+            delete qlist;
+        }
+
+        qlist = New List<QuoteLineItem>();
+        List<QuoteLineItem> singleProductList = new List<QuoteLineItem>();
+        Integer i=1;
+
+        if (activities.size()>0) {
+            Decimal all_price = 0.0;
+            Decimal all_discount = 0.0;
+            for (QELine s:activities) {
+                if (is_hidden_all || is_hidden_user == true || is_dealer_user == true && s.hiddenflg == true) {
+                    if (s.pageObject.PricebookEntryId != null &&  s.productName != null && s.productName != '') {
+                        if (String.isBlank(s.pageObject.PricebookEntryId) == false) {
+                            String setName = s.pageObject.Set__c;
+                            Integer qty = 1 ;
+                            //XHL-20190426-UpdateStart
+                            if (!s.pageObject.SingleProduct__c ){
+
+                                String fieldName = setName.substring(3);
+                                fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
+                                Decimal d_qty = (Decimal) quo.get('SetQty' + fieldName + '__c');
+                                // qty = d_qty == null ? 1 : d_qty.intValue();
+                            }
+                            //XHL-20190426-UpdateEnd
+                            
+                            all_price += s.salesPrice * s.pageObject.Quantity * qty;
+                        }
+                    }
+                }
+
+                if (quo.OrderIsChange__c) {
+                    String productCode = s.pageObject.Product2.ProductCode;
+                    if (String.isNotBlank(productCode)) {
+                         
+                        saveStringConcatenation += productCode + '|' +s.pageObject.Quantity;
+                    }
+                    
+                }
+            }
+
+
+            if (all_price > 0) {
+                system.debug('all_price---->'+all_price);
+                all_discount = (all_price - quo.Total_Price_Text__c) * 100 / all_price;
+                system.debug('all_discount---->'+all_discount);
+            }
+
+            if (quo.OrderIsChange__c) {
+                if (initStringConcatenation != saveStringConcatenation) {
+                    verifyProductValidFlag = true;
+                }
+            }
+
+            // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 Start
+            Map<String,Decimal> productIdQuantityMap = new  Map<String,Decimal>();
+            List<String> productIdList = new List<String>();
+            String productSegmentZ5 = opp.ProductSegment__c == 'BS' ? 'LS':opp.ProductSegment__c;
+            // String productSegment = opp.ProductSegment__c == 'BS' ? 'LS':opp.ProductSegment__c;
+
+            String FGSPStr = 'Machine'.equals(opp.Machine_Parts__c) ? 'FG':'SP';
+            // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 End
+            for (QELine s:activities) {
+                if (s.pageObject.PricebookEntryId != null &&  s.productName != null && s.productName != '') {
+                    if (String.isBlank(s.pageObject.PricebookEntryId) == false) {
+                        String setName = s.pageObject.Set__c;
+                        Integer qty = 1;
+                        //XHL-20190426-UpdateStart
+                        if (!s.pageObject.SingleProduct__c && String.isNotBlank(setName)){
+                            String fieldName = setName.substring(3);
+                            fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
+                            Decimal d_qty = (Decimal) quo.get('SetQty' + fieldName + '__c');
+                            qty = d_qty == null ? 1 : d_qty.intValue();
+                        } 
+                        //XHL-20190426-UpdateEnd
+                        QuoteLineItem ql = s.pageObject.clone();
+                        ql.QuoteId = q.Id;
+                        ql.Quantity = ql.Quantity ;
+                        if (is_hidden_all || is_hidden_user == true || is_dealer_user == true && s.hiddenflg == true) {
+                            ql.UnitPrice = s.salesPrice;
+                            ql.Discount = all_discount;
+                            if (s.customPrice != 0) {
+                                ql.Custom_Price__c = s.customPrice;
+                            }
+                        }
+                        ql.Custom_Price__c = ql.Custom_Price__c == null ? 0 : ql.Custom_Price__c;// * qty;
+                        ql.quoLiVerifyProductValid__c = verifyProductValidFlag;
+                        if (s.pageObject.SingleProduct__c) {
+                            singleProductList.add(ql);
+                        } else {
+                            qlist.add(ql);  
+                        }                        
+                        productIdList.add(s.pageObject.Product2Id);
+                        // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 Start
+                        Decimal quantity = ql.Quantity;
+                        if (productIdQuantityMap.containsKey(s.pageObject.Product2Id)) {
+                            quantity += productIdQuantityMap.get(s.pageObject.Product2Id);
+                        }
+                        productIdQuantityMap.put(s.pageObject.Product2Id,quantity);
+                        // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 End
+
+                        i++;
+                    }
+                }
+            }
+            if (productIdList.size() > 0) {
+                // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 Start
+                Map<String,Decimal> productQuantityMap = new  Map<String,Decimal>();
+                List<Product2> getProductList = [SELECT Id,Name,ProductCode,NMPAStatus__c,ProductStatusFormula__c FROM Product2 WHERE Id IN:productIdList AND NMPAStatus__c = '鍋滀骇' AND ProductStatusFormula__c = '1'];
+
+                for (Product2 pro:getProductList) {
+
+                    Decimal productQuantity = productIdQuantityMap.get(pro.Id);
+                    String key = pro.ProductCode +'_'+ productSegmentZ5 +'_'+ FGSPStr;
+                    // String key = pro.ProductCode +'_'+ productSegment +'_'+ FGSPStr;
+                    
+
+                    productQuantityMap.put(key, productQuantity);
+                }
+                if (productQuantityMap.size() > 0) {
+                    String result = OrderWebService.ProductInventoryCheck(productQuantityMap);
+                    if (result != '1') {
+                        if (String.isBlank(errorMessage)) {
+                            errorMessage = '娉ㄦ剰锛侊紒锛� '+ result;
+                        } else {
+                            errorMessage += result; 
+                        }
+                    }    
+                }
+                // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 End
+                
+            }
+            if (singleProductList.size() >0 ){
+                insert singleProductList;
+            }
+
+            if (qlist.size()>0) {
+                insert qlist;
+            }
+            
+            Quote quoUpd = [select id, Discount, Discount_Normal__c, Discount_Special__c,OrderIsChange__c from Quote where Id = : quoId1];
+            Decimal quoDis = quoUpd.Discount == null ? 0 : quoUpd.Discount;
+            Decimal quoDisN = quoUpd.Discount_Normal__c == null ? 0 : quoUpd.Discount_Normal__c;
+            if (productSegment == 'BS') {
+                system.debug('quoDis---->'+quoDis);
+                system.debug('quoDisN---->'+quoDisN);
+                quoUpd.Discount_Special__c = quoDis - quoDisN;
+                system.debug('quoUpd.Discount_Special__c---->'+quoUpd.Discount_Special__c);
+            } else {
+                quoUpd.Discount_Special__c = (quoDis - quoDisN) / (1 - quoDisN / 100);
+            }
+
+            quoUpd.QuoVerifyProductValid__c = verifyProductValidFlag;
+
+            update quoUpd;
+
+            List<QuoteLineItem> itemsRe = 
+                [Select Id,Product2Id,Product2.Name,Product2.ProductCode,Product2.Product_ECCode__c,Quantity,Subtotal,Discount,TotalPrice,PricebookEntryId,UnitPrice,Description,Set__c,Custom_Price__c,
+                        PricebookEntry.SalesPrice__c,PricebookEntry.SalesPriceA__c,PricebookEntry.SalesPriceB__c,PricebookEntry.SalesPriceC__c,Product2.ProductModels__c,PricebookEntry.Hidden_flag__c,
+                        Quote.Discount_Normal__c,SingleProduct__c,SetName__c,DontSingleProduct__c,
+                        Quote.Opportunity.DealerId__c
+                   From QuoteLineItem where Quoteid = :quoId1 Order by Id];
+            activities = new List<QELine>();
+            i=0;
+            QELine c = new QELine(i);
+
+            String includeEspecialProduct = '';
+            is_hidden_all = false;
+            if (itemsRe.size()>0) {
+                for (QuoteLineItem o:itemsRe) {
+
+                    if (o.DontSingleProduct__c != '1') {
+                        if (String.isBlank(includeEspecialProduct)) {
+
+                            includeEspecialProduct = o.DontSingleProduct__c;
+                        } else {
+                            includeEspecialProduct += ',' + o.DontSingleProduct__c;
+                        }
+                        specialerrorflg = true;
+                    }
+                    String setName = o.Set__c;
+                    Integer qty = 1;
+                    //XHL-20190426-UpdateStart
+                    if (!o.SingleProduct__c && String.isNotBlank(setName)) {
+                        String fieldName = setName.substring(3);
+                        fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
+                        Decimal d_qty = (Decimal) quo.get('SetQty' + fieldName + '__c');
+                        qty = d_qty == null ? 1 : d_qty.intValue();
+                    } 
+                    //XHL-20190426-UpdateEnd
+                    c = new QELine(isService, o,i,o.Product2.Name,o.Product2.ProductCode,o.Product2.Product_ECCode__c,qty,o.Product2.ProductModels__c,o.SingleProduct__c,o.SetName__c);
+                    //c = new QELine(isService, o,i,o.Product2.Name,o.Product2.ProductCode,o.Product2.Product_ECCode__c,qty,o.Product2.ProductModels__c,quo.Discount_Normal__c);
+                    //specialDealer =  StaticParameter.specialDealerMap.containsKey(o.Quote.Opportunity.DealerId__c);
+                    specialDealer = IfspecialDealer(o.Quote.Opportunity.DealerId__c);
+                    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇烽�夋嫨鐩爣瀹㈡埛----3>'+o.Quote.Opportunity.DealerId__c));
+                    if (specialDealer || is_hidden_user == true || is_dealer_user == true && c.hiddenflg == true) {
+                        c.pageObject.UnitPrice = 0;
+                        c.totalPrice = 0;
+                        c.customPrice = 0;
+                        system.debug('<---is_hidden_all---01>' + is_hidden_all);
+                        is_hidden_all = true;
+                        discount = 0;
+                    }
+                    activities.add(c);
+                    i++;
+
+                }
+            }
+            if (String.isNotBlank(includeEspecialProduct) && specialerrorflg) {
+                if(!StaticParameter.specialDealerMap1.containsKey(opp.DealerId__c)) {
+                    errormessage += '娉ㄦ剰锛侊紒锛� 鎶ヤ环浜у搧涓寘鍚壒娈婄殑鍗曞搧浜у搧[ ' +includeEspecialProduct+ ' ]';
+                }
+                //system.debug('errormessage__20190523__' + errormessage);
+            }
+
+            for (integer j=i;j<quoteEntryMaxLine;j++) {
+                c = new QELine(j);
+                activities.add(c);
+            }
+
+        }
+        if (quo.OrderIsChange__c) {
+            if (initStringConcatenation != saveStringConcatenation) {
+                verifyProductValidFlag = true;
+            }
+        }
+
+        List<Quote> quoListRe = 
+                [ SELECT Id,Name,QuoteNumber,Account.name,ExpirationDate,Subtotal,Discount,TotalPrice,GrandTotal,PrintPrice__c,ShippingHandling,
+                    DeliveryLeadTime__c,PaymentTerms__c,ValidDate__c,Warranty__c,SetName1__c,Shipment_Term__c,Shipment_Term2__c,
+                    SetName2__c,SetName3__c,SetName4__c,SetName5__c,SetName6__c,SetName7__c,SetName8__c,SetName9__c,SetName10__c,
+                    SetName11__c,SetName12__c,SetName13__c,SetName14__c,SetName15__c,SetName16__c,SetName17__c,SetName18__c,SetName19__c,
+                    SetName20__c,SetName21__c,SetName22__c,SetName23__c,SetName24__c,SetName25__c,SetName26__c,SetName27__c,SetName28__c,SetName29__c,
+                    SetName30__c,SetQty1__c,SetQty2__c,SetQty3__c,SetQty4__c,SetQty5__c,SetQty6__c,SetQty7__c,SetQty8__c,SetQty9__c,SetQty10__c,SetQty11__c,
+                    SetQty12__c,SetQty13__c,SetQty14__c,SetQty15__c,SetQty16__c,SetQty17__c,SetQty18__c,SetQty19__c,SetQty20__c,SetQty21__c,SetQty22__c,SetQty23__c,
+                    SetQty24__c,SetQty25__c,SetQty26__c,SetQty27__c,SetQty28__c,SetQty29__c,SetQty30__c,Comment__c,Custom_Price_Total__c,Custom_Price_Total_Text__c,Quote_Type__c,
+                    Main_Model__c,Main_Serial_Number__c,Service_Type__c,Contract_Number__c,Service_Date__c,Service_Finish_Date__c,Service_Engineer_Sign__c,
+                    Service_Pickup_Sign__c,Service_Check_Sign__c,Service_Location__c,Service_Status__c,Service_Content__c, Is_upload__c, Total_Price_Text__c,
+                    Discount_Normal__c,Discount_Special__c,OrderIsChange__c
+                    FROM Quote Where Id =:quoId1];
+        if (quoListRe.size() > 0) {
+            quo = quoListRe[0];
+        }
+
+system.debug('=====is_hidden_all:' + is_hidden_all);
+        if (is_hidden_all) {
+            discount = quo.totalPrice.setScale(2, System.RoundingMode.HALF_UP);
+        } else {
+            discount = quo.Discount == null ? 0 : quo.Discount;
+            //discount = quo.Discount_Special__c == null ? 0 : quo.Discount_Special__c;
+            discount = discount.setScale(2, System.RoundingMode.HALF_UP);
+        }
+
+system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome Opportunity class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+
+        //Opportunity--------------------------------------------
+        Opportunity o = New Opportunity();
+        List<Opportunity> os = New List<Opportunity>();
+        os = [select Id From Opportunity Where Id =:oppid];
+        if (os.size()>0) {
+            o = os[0];
+            if (decideFlg == false) {
+                o.SyncedQuoteId = quoId1;
+                o.Quote_PaymentTerms_Text__c = paymentTermsMap.get(quo.PaymentTerms__c);
+                o.is_hidden__c = is_hidden_all || specialDealer;
+                if (doDecide == true) {
+                    o.Is_Decided__c = true;
+                    o.Quote_Decide_User__c = UserInfo.getUserId();
+                }
+                o.IE_Discount_Normal__c = quo.Discount_Normal__c;
+                o.IE_Discount_Special__c = quo.Discount_Special__c;
+                system.debug('IE_Discount_Special__c--->'+o.IE_Discount_Special__c);
+                update o;
+            }
+       
+        }
+if (quoId == null) {
+    quoId = quoId1;//q.Id;
+}
+        return true;
+    }
+
+    //opp銇敾闈€伄鍊ゃ倰瑷畾
+    private void setOppFromOppInfo() {
+
+    }
+
+    public PageReference csvExport() {
+        if (fileName == null || fileName == '') {
+            errorflg = true;
+            errormessage = '璇疯緭鍏ラ厤缃鍑烘枃浠跺悕銆�';
+            return null;
+        }
+        Date dExpirationDate = quo.ExpirationDate;
+        strExpirationDate = dExpirationDate == null ? '' : dExpirationDate.format();
+        csv_activities = new List<QELine>();
+        for (QELine s : activities) {
+            if (s.pageObject.PricebookEntryId != null &&  s.productName != null && s.productName != '') {
+                csv_activities.add(s);
+            }
+        }
+        PageReference pr = page.QuoteCSVExport;
+        return pr;
+    }
+
+    public PageReference csvRead() {
+
+        String strFile = '';
+        List<String> listFile = new List<String>();
+        errorflg = false;
+        errormessage = null;
+try {
+        if (contentFile != null) {
+            strFile = contentFile.toString();
+            listFile = strFile.split('\n');
+system.debug('=====strFile:' + strFile);
+        } else {
+            errorflg = true;
+            errormessage = '璇诲彇鍐呭涓虹┖銆�';
+            return null;
+        }
+} catch (Exception ex) {
+    errorflg = true;
+    errormessage = System.Label.Error_Message02;
+    return null;
+}
+for (Integer i = 0; i < listFile.size(); i++) {
+    system.debug('=====listFile_' + i + ':' + listFile[i]);
+}
+        List<String[]> arrayFile = new List<String[]>();
+        String firstline = listFile[0];
+        if (firstline.indexOf('濂楄/鍗曞搧') < 0) {
+            errorflg = true;
+            errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭��';
+            return null;
+        } else {
+            String strReplace = '';
+            List<String> temp = strFile.split('"');
+            for (Integer i = 0; i < temp.size(); i++) {
+                if (math.mod(i, 2) == 1) {
+                    temp[i] = temp[i].replace(',', '#%&');
+                }
+                strReplace += temp[i];
+            }
+system.debug('=====strReplace:' + strReplace);
+            List<String> listReplace = strReplace.split('\n');
+            for (String replace : listReplace) {
+system.debug('=====replace:' + replace);
+                if (replace != '\r' && replace.length() > 0) {
+                    replace = replace.replace('\r', '');
+                    String[] a = replace.split(',', -1);
+                    for (Integer i = 0; i < a.size(); i++) {
+                        if (a[i].indexOf('#%&') > 0) {
+                            a[i] = a[i].replace('#%&', ',');
+                        }
+                    }
+                    if (specialDealer) {
+                        if (a.size() != 4) {
+                            errorflg = true;
+                            errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭�侺ine:' + arrayFile.size();
+                            return null;
+                        }
+                    }  else {
+                        if (a.size() != 5) {
+                            errorflg = true;
+                            errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭�侺ine:' + arrayFile.size();
+                            return null;
+                        }
+
+                    }
+                    //if (a.size() != 5) {
+                    //    errorflg = true;
+                    //    errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭�侺ine:' + arrayFile.size();
+                    //    return null;
+                    //}
+                    arrayFile.add(a);
+                }
+            }
+        }
+
+        List<String> prdCodeList = new List<String>();
+
+        //XHL-20190426-UpdateStart
+        Map<String,String> productSetCodeMap = new Map<String,String>();
+
+        for (Integer i = 1; i < arrayFile.size(); i++) {
+
+            if (arrayFile[i] != null && arrayFile[i].size() > 1 && arrayFile[i][0] != '') {
+                try {
+                    if (String.isNotBlank(arrayFile[i][3])) {
+                        Decimal quantity1 = Decimal.valueOf(arrayFile[i][3]);
+                    }
+                    if (!specialDealer) {
+                        if (String.isNotBlank(arrayFile[i][4])) {
+                            Decimal discount1 = Decimal.valueOf(arrayFile[i][4]);
+                        }
+                    }
+
+                } catch (Exception e) {
+                    errorflg = true;
+                    if (arrayFile[i][0] != singleProduct ) {
+                        errorMap.put(arrayFile[i][1],'[' + arrayFile[i][1] +']閰嶅鐨勬暟閲忔垨鎶樻墸瀛樺湪闈炴暟瀛楋紝璇风‘璁�;');    
+                    } else {
+                        errorMap.put(arrayFile[i][1],'[' + arrayFile[i][1] +']浜у搧鐨勬暟閲忔垨鎶樻墸瀛樺湪闈炴暟瀛楋紝璇风‘璁�;');
+                    } 
+                    continue;
+                }
+                
+                if (arrayFile[i][0] != singleProduct ) {
+
+                    productSetCodeMap.put(arrayFile[i][1], arrayFile[i][3] + ';'+arrayFile[i][4]);    
+                } else {
+
+                    String tmp = '00000000000' + arrayFile[i][1];
+                    prdCodeList.add(tmp);
+                    prdCodeList.add(arrayFile[i][1]);
+                }
+                
+            }
+        }
+
+        activities = new List<QELine>();
+        Integer no =0;
+        emptyData();
+        if (productSetCodeMap.size() > 0) {
+            
+            acquireProductSetId(productSetCodeMap);
+            no =  singleNo == null ? 0 : singleNo;
+        } 
+        //XHL-20190426-UpdateEnd
+        
+
+        
+
+system.debug('=====prdCodeList:' + prdCodeList);
+        //return null;
+        Map<String, Product_Search__c> psMap = new Map<String, Product_Search__c>(); // key銇孭roductCode銇с仚銆�
+        List<String> forSelect = new List<String>();
+        List<Product_Search__c> psList = [
+            select Id, Name, ProductCode__c, Product_ECCode__c, ProductDescription__c, ProductStatus__c, Product__c, ProductModels1__c
+              from Product_Search__c
+             where ProductCode__c in :prdCodeList];
+        String errProduct = '';
+        Map<String,String> errProductMap = new Map<String,String>();
+        for (Product_Search__c ps : psList) {
+            String pc = ps.ProductCode__c;
+            if (pc.startsWith('00000000000')) {
+                pc = pc.substring(11);
+                psMap.put(pc, ps);
+            }
+            psMap.put(ps.ProductCode__c, ps);
+            forSelect.add(ps.Product__c);
+            //system.debug(ps.ProductCode__c + ps.ProductStatus__c+'@@@@@@@->>>');
+            if(ps.ProductStatus__c == '0'){
+                system.debug(ps.ProductCode__c + ps.ProductStatus__c+'@@@@@@@');
+                errorflg = true;
+                errProduct += ps.ProductCode__c + ',';
+                errProductMap.put(ps.ProductCode__c,ps.ProductCode__c);
+            }
+        }
+
+        if (errorflg == true && errProduct != '') {
+            errProduct = errProduct.substring(0, errProduct.length() - 1);
+            errorMessage = '浜у搧鐘舵�佷负鏃犳晥锛屼笉鑳戒娇鐢ㄣ�備骇鍝侊細' + errProduct + '璇风‘璁�;';
+            errorMap.put(errorMessage,errorMessage);
+            //return null;
+        }
+        system.debug('errorflg---->11111'+errorMessage);
+        Map<String, PricebookEntry> pbeMap = new Map<String, PricebookEntry>(); // key銇孭roductCode銇с仚銆�
+        List<PricebookEntry> pbeList = [
+            select Id, Product2Id, ProductCode, Product2.Product_ECCode__c, Product2.Dummy__c, CostPrice__c, SalesPrice__c, SalesPriceA__c, SalesPriceB__c, SalesPriceC__c, Hidden_flag__c
+              from PricebookEntry
+             where Pricebook2Id = :pricebook2Id
+               and CurrencyIsoCode = :currencyIsoCode
+               and Product2.ManualHidden__c = false
+               and Product2Id in :forSelect];
+        system.debug('forSelect_1_1_1_1_1_' + forSelect);
+        system.debug('pbeList_2_2_2_2_2_2_2_' + pbeList);
+        
+        for (PricebookEntry pbe : pbeList) {
+            String pc = pbe.ProductCode;
+            if ((pbe.CostPrice__c == 0 && pbe.Product2.Dummy__c == false) || pbe.SalesPrice__c == 0) {
+                errorflg = true;
+                errProduct += pbe.productCode + ',';
+            } else {
+                if (pc.startsWith('00000000000')) {
+                    pc = pc.substring(11);
+                    pbeMap.put(pc, pbe);
+                }
+                pbeMap.put(pbe.ProductCode, pbe);
+            }
+        }
+
+        if (arrayFile.size() > 1) {
+            //XHL-20190426-UpdateStart
+            for (Integer line = 1; line < arrayFile.size(); line++) {
+                
+                if (arrayFile[line][0] == singleProduct) {
+
+                    Product_Search__c ps = psMap.get(arrayFile[line][1]);
+                    PricebookEntry pbe = pbeMap.get(arrayFile[line][1]);
+                    if (ps == null || pbe == null) {
+                        errorflg = true;
+                        errProduct += arrayFile[line][1] + ',';
+                        errorMap.put(arrayFile[line][2],errProduct);
+                    }    
+                }
+                
+            }
+            
+            if (errorflg) {
+                system.debug('errorflg---->22222'+errorMessage);
+                errorMessage = '';
+                String intermediateVariable = '';
+
+                for (String errorKey :errorMap.keySet()) {
+
+                    errProduct = errorMap.get(errorKey).substring(0, errorMap.get(errorKey).length()-1);
+                    system.debug('ceshi------>' + errProduct);
+                    if (errProduct.endsWith('!!!')) {
+                        errorMessage += errorMap.get(errorKey);
+                    } else if(errProduct.startsWith('error')){
+                        errorMessage += errorMap.get(errorKey);
+                    }else if(errProduct.endsWith('璇风‘璁�')){
+                        errorMessage += errorMap.get(errorKey);
+                    }else {
+                        if (String.isBlank(intermediateVariable)) {
+                            intermediateVariable = errorKey;
+                        } else {
+                            intermediateVariable += ',' + errorKey;
+                        }
+                        
+                    }
+                       
+                }
+                if (String.isNotBlank(intermediateVariable)) {
+                    errorMessage += '[' + intermediateVariable + ']鐨勪骇鍝佷环鏍间俊鎭笉姝g‘锛屼笉鑳戒娇鐢�;'; 
+                }
+                //return null ;
+            }
+            
+            QELine c = new QELine(no);
+            is_hidden_all = false;
+            boolean isSingleProduct = false;
+            for (Integer line = 1; line < arrayFile.size(); line++) {
+                if (arrayFile[line][0] == singleProduct ){
+                    if (errorMap.containsKey(arrayFile[line][2])) {
+                        continue;
+                    }
+
+                    isSingleProduct = true;
+                    Product_Search__c ps = psMap.get(arrayFile[line][1]);
+                    PricebookEntry pbe = pbeMap.get(arrayFile[line][1]);
+                    system.debug('=====key:' + arrayFile[line][1]);
+                    system.debug('=====ps:' + ps);
+                    system.debug('=====pbe:' + pbe);
+                    system.debug('ps.ProductCode__c--->'+ps.ProductCode__c );
+                    system.debug('ps.Product__c--->'+ps.Product__c);
+                    //c = new QELine(isService, no, arrayFile[line][0], ps.Name, ps.ProductCode__c, ps.Product_ECCode__c, ps.Product__c, pbe, arrayFile[line][3], arrayFile[line][4], ps.ProductModels1__c, quo.Discount_Normal__c);
+                    if (errProductMap != null && errProductMap.size() > 0) {
+                        if (errProductMap.containsKey(arrayFile[line][1])) {
+                            continue;
+                        }
+                    }
+                    if (specialDealer) {
+                        c = new QELine(isService, no, singleProduct, ps.Name, ps.ProductCode__c, ps.Product_ECCode__c, ps.Product__c, pbe, arrayFile[line][3],'', ps.ProductModels1__c, isSingleProduct, ps.ProductDescription__c, '');
+                    } else {
+                        c = new QELine(isService, no, singleProduct, ps.Name, ps.ProductCode__c, ps.Product_ECCode__c, ps.Product__c, pbe, arrayFile[line][3], arrayFile[line][4], ps.ProductModels1__c, isSingleProduct, ps.ProductDescription__c, '');
+                    }
+                    //c = new QELine(isService, no, singleProduct, ps.Name, ps.ProductCode__c, ps.Product_ECCode__c, ps.Product__c, pbe, arrayFile[line][3], arrayFile[line][4], ps.ProductModels1__c,isSingleProduct,ps.ProductDescription__c,'');
+                    if (specialDealer || is_hidden_user == true || is_dealer_user == true && c.hiddenflg == true) {
+                        c.pageObject.UnitPrice = 0;
+                        c.totalPrice = 0;
+                        system.debug('<---is_hidden_all--->02' + is_hidden_all);
+                        is_hidden_all = true;
+                        discount = 0;
+                    }
+                    activities.add(c);
+                    
+                    no++;  
+
+                }
+                
+            }
+            //XHL-20190426-UpdateEnd
+            for (integer j = no; j < quoteEntryMaxLine; j++) {
+                c = new QELine(j);
+                activities.add(c);
+            }
+
+        } else {
+            for (no = 0; no < quoteEntryMaxLine; no++) {
+                QELine active_activity = new QELine(no);
+                activities.add(active_activity);
+            }
+        }
+        system.debug('quoName: '+quo.Name);
+        return null;
+    }
+
+    public boolean dataCheck() {
+        system.debug('鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆Welcome to dataCheck class!!鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆鈼嬧棆');
+        errorflg = false;
+        errormessage = null;
+        Boolean error = false;
+        List<String> product2Ids = New List<String>();
+        Map<String,String> mapSet = new Map<String,String> ();
+        Map<Id, Product_Search__c> prd2LatestValMap = new Map<Id, Product_Search__c>();
+
+        //鎶ヤ环浼樺寲 2021-05-08 start
+        String shter = quo.Shipment_Term__c;
+        if(String.isBlank(shter) && opp.Trade_Type_D__c =='Tax Exemption'){
+            errorflg = true;
+            errorMessage = '鍥介檯璐告槗鏉′欢涓嶈兘涓虹┖锛�';
+            return false;
+        }
+
+        String shter2 = quo.Shipment_Term2__c;
+        if(String.isBlank(shter2) && opp.Trade_Type_D__c =='Tax Exemption'){
+            errorflg = true;
+            errorMessage = '鍥介檯璐告槗鏉′欢2涓嶈兘涓虹┖锛�';
+            return false;
+        }
+        //鎶ヤ环浼樺寲 2021-05-08 end
+
+        String qname = quo.Name;
+        if (qname == null || qname.trim().length() == 0) {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ユ姤浠峰悕绉帮紒';
+            return false;
+        }
+        String qpaymentTerms = quo.PaymentTerms__c;
+        if (qpaymentTerms == null || qpaymentTerms.trim().length() == 0) {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ヤ粯娆炬潯浠讹紒';
+            return false;
+        }
+        Decimal qdeliveryLeadTime = quo.DeliveryLeadTime__c;
+        if (qdeliveryLeadTime == null || qdeliveryLeadTime <= 0) {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ヤ氦璐у懆鏈燂紒';
+            return false;
+        }
+        Decimal qwarranty = quo.Warranty__c;
+        if (qwarranty == null || qwarranty <= 0) {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ヤ繚淇湡锛�';
+            return false;
+        }
+        Date qexpirationDate = quo.ExpirationDate;
+        if (qexpirationDate == null) {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ユ姤浠峰埌鏈熸棩鏈燂紒';
+            return false;
+        }
+        Decimal qcustomPriceTotal = quo.Custom_Price_Total_Text__c;
+        if (qcustomPriceTotal == null || qcustomPriceTotal == 0) {
+            errorflg = true;
+            errorMessage = '璇疯緭鍏ュ鎴锋�讳环';
+            return false;
+        }
+
+        if (is_hidden_all) {
+            quo.Total_Price_Text__c = discount;
+            system.debug('discount----->123'+discount);
+        }
+system.debug('=====quo.Total_Price_Text__c:' + quo.Total_Price_Text__c);
+        if (is_hidden_all && (quo.Total_Price_Text__c == null || quo.Total_Price_Text__c <= 0)) {
+            errorflg = true;
+            errorMessage = '鎬讳环涓嶆纭紝璇风‘璁わ紒';
+            return false;
+        }
+
+        if (activities.size()>0) {
+            for (QELine a:activities){
+                if (String.isBlank(a.pageObject.Product2Id) == false) {
+                    product2Ids.add(a.pageObject.Product2Id);
+                }
+                String tmpSet = a.pageObject.Set__c;
+                if (tmpSet != null && tmpSet != '') {
+                    String tmpSetId = tmpSet.substring(2);
+                    if (!mapSet.containsKey(tmpSetId)) {
+                        mapSet.put(tmpSetId,tmpSet);
+                    }
+                }
+            }
+
+            Map<String,String> mapHeaderSet = new Map<String,String> ();
+            Map<String,Decimal> mapHeaderQty = new Map<String,Decimal> ();
+            for (Integer i = 1; i <= 30; i++) {
+                String field = String.valueOf(i);
+                field = '00' + field;
+                field = field.substring(field.length() - 2);
+                mapHeaderSet.put('set' + field, (String) quo.get('SetName' + i + '__c'));
+                mapHeaderQty.put('set' + field, (Decimal) quo.get('SetQty' + i + '__c'));
+            }
+
+            system.debug('mapSet class========>' + mapSet);
+            system.debug('mapSet class========>' + mapSet.size());
+            system.debug('mapHeaderSet class========>' + mapHeaderSet);
+            system.debug('mapHeaderQty class========>' + mapHeaderQty);
+
+            Map<String,String> mapErrSet = new Map<String,String> ();
+
+
+        }
+        
+        if (error==true) {
+            errorflg = true;
+            return false;
+        }
+
+        errorflg = false;
+        errorMessage = null;
+        return true;
+    }
+
+    public PageReference reloadPage() {
+        if (is_hidden_all) {
+            discount = 0;
+        } else {
+            discount = quo.Discount == null ? 0 : quo.Discount;
+            discount = discount.setScale(2, System.RoundingMode.HALF_UP);
+        }
+        return null;
+    }
+
+
+    //瀵煎叆鏁版嵁鏃讹紝鏍规嵁浜у搧閰嶅鐨凜ode鏌ユ壘浜у搧閰嶅
+    public void acquireProductSetId(Map<String,String> productSetCodeMap) {
+        errorflg = false;
+        errormessage = null;
+        system.debug('<---productSetCodeMap--->' + productSetCodeMap );
+        Map<String,Integer> productSetID_QuantityMap = new Map<String,Integer>();
+        List<productSet__c> productSetList;  //= new List<productSet__c>();
+        Map<String,String> codeMap = new Map<String,String>();
+
+        if (productSetCodeMap.size() > 0 ) {
+
+            productSetList = [select Id,Name,Code__c from productSet__c where Code__c in: productSetCodeMap.keyset()];
+        }
+        system.debug('<---productSetList--->' + productSetList.size() );
+        if (productSetList.size() > 0) {
+
+            for (productSet__c productSet :productSetList) {
+
+                codeMap.put(productSet.Code__c, productSet.Code__c);
+                Integer quantity = Integer.valueOf(productSetCodeMap.get(productSet.Code__c).split(';')[0]);
+                productSetID_QuantityMap.put(productSet.Id,quantity);
+
+            }
+
+            queSetNameSetQty(productSetID_QuantityMap,productSetCodeMap);
+            
+        } else {
+
+            for (String keyset : productSetCodeMap.keyset()) { 
+                
+                errorflg = true;    
+                errorMap.put(keyset,'[' + keyset +']閰嶅涓嶅瓨鍦紝璇风‘璁�!!!!;');
+            }
+        }
+        String errorInformation = '';
+
+        for (String keyset : productSetCodeMap.keyset()) { 
+
+            if (!codeMap.containsKey(keyset)) {
+                
+                errorMap.put(keyset,'[' + keyset +']閰嶅涓嶅瓨鍦紝璇风‘璁�!!!!;');
+
+            }
+        }
+         
+    }
+
+    //閫夋嫨浜у搧閰嶅
+    public PageReference setProductEntry () {
+
+        errorflg = false;
+        errormessage = null;
+
+        Map<String,Integer> productSetID_QuantityMap = new Map<String,Integer>();
+        Map<String,String> productSetID_DiscountMap = new Map<String,String>();
+        //褰搒etProduct_text涓虹┖鏃讹紝璁や负鍒犻櫎璇ユ姤浠锋墍鏈夌殑浜у搧閰嶅
+        if (String.isBlank(setProduct_text)) {
+
+            List<QELine> singleProductSuitList = new List<QELine>();
+            for (QELine q :activities) {
+                
+                if ( String.isBlank(q.pageObject.Product2Id) == false && q.pageObject.SingleProduct__c  == true) {
+
+                    singleProductSuitList.add(q);
+                } 
+                
+            }
+
+            activities = new List<QELine>();
+
+            emptyData();
+
+            //灏嗗崟鍝佸瑁呮斁鍦ㄤ骇鍝侀厤濂楀瑁呯殑涓嬮潰
+            Integer singleNo = 0;
+            QELine qeline = new QELine(singleNo);
+
+            for (QELine q :singleProductSuitList) {
+                
+                q.lineNo = singleNo;
+                activities.add(q);
+                singleNo++;
+            }
+            
+            for (integer j = singleNo; j < quoteEntryMaxLine; j++) {
+
+                qeline = new QELine(j);
+                activities.add(qeline);
+            }
+
+            return null;
+        } else {
+            List<String> productSetIdList = new List<String>();
+            Map<String,String> productSetMap = new Map<String,String>();
+            for (String str : setProduct_text.split(';')) {
+                productSetIdList.add(str.split(',')[0]);
+            }
+            if (productSetIdList.size() > 0) {
+                for (productSet__c proSet  :[select Id,Name,Code__c from productSet__c where Id in :productSetIdList]) {
+                    productSetMap.put(proSet.Id, proSet.Code__c);
+                }
+            }
+            for (String str : setProduct_text.split(';')) {
+
+                if (String.isBlank(str.split(',')[1]) == false) {
+
+                    productSetID_QuantityMap.put(str.split(',')[0], Integer.valueOf(str.split(',')[1]));
+                    productSetID_DiscountMap.put(productSetMap.get(str.split(',')[0]), str.split(',')[1]+';'+str.split(',')[2]);
+                    system.debug('productSetID_DiscountMap____' + productSetID_DiscountMap);
+
+                }
+                
+            }
+        }
+
+       //queSetNameSetQty(productSetID_QuantityMap,null);
+       queSetNameSetQty(productSetID_QuantityMap,productSetID_DiscountMap);
+        
+        for (integer j = singleNo; j < quoteEntryMaxLine; j++) {
+
+            QELine qeline = new QELine(j);
+            activities.add(qeline);
+        }
+
+        return null;
+    }
+
+    
+
+    public class QELine {
+        public Integer lineNo { get; set; }
+        public String productName { get; set; }
+        public String productCode { get; set; }
+        public String productEC { get; set; }
+        public QuoteLineItem pageObject { get; set; }
+        public String setName { get; set; }
+        public String productSetNameReference { get; set; }
+        public Double totalPrice { get; set; }
+
+        public Decimal salesPrice { get; set; }
+        public Decimal salesPriceA { get; set; }
+        public Decimal salesPriceB { get; set; }
+        public Decimal salesPriceC { get; set; }
+
+        public boolean isProductModel { get; set; }
+
+        public boolean hiddenflg { get; set; }
+        public Decimal customPrice { get; set; }
+
+        //public Decimal discount { get; set; }
+        private Map<String, String> setNameMap;
+        private void setMap() {
+            Integer quoteEntryMaxSet = Integer.valueOf(System.Label.QuoteEntryMaxSet);
+            String singleProduct  = System.Label.SingleProduct;
+            setNameMap = new Map<String, String>();
+            for (Integer i = 0; i < quoteEntryMaxSet; i++) {
+                if (i < 9) {
+                    setNameMap.put('set0'+ String.valueOf(i+1),'濂楄0'+ String.valueOf(i+1));
+                } else {
+                    setNameMap.put('set'+ String.valueOf(i+1),'濂楄'+ String.valueOf(i+1));
+                }
+            }
+           
+            setNameMap.put(singleProduct,singleProduct);
+        }
+        private void setMap2() {
+            setNameMap = new Map<String, String>();
+            setNameMap.put('set01','闆朵欢璐圭敤');
+            setNameMap.put('set02','鏈嶅姟璐�');
+            setNameMap.put('set03','鍏朵粬璐圭敤');
+        }
+
+        public QELine(Integer i) {
+            this.pageObject = New QuoteLineItem();
+            this.lineNo = i;
+            this.totalPrice = 0;
+
+            this.salesPrice = 0;
+            this.salesPriceA = 0;
+            this.salesPriceB = 0;
+            this.salesPriceC = 0;
+
+            this.isProductModel = true;
+
+            this.hiddenflg = false;
+        }
+
+        //public QELine(boolean isService, QuoteLineItem tmp, Integer i, String pdtName, String pdtCode, String pdtEC, Integer sQty, boolean ispm, Decimal discount_n) {
+        //XHL-20190428-Update isSingleProduct,鍦ㄦ姤浠疯椤圭洰涓婂鍔燬ingleProduct__c瀛楁锛屽尯鍒嗘槸濂楄杩樻槸鍗曞搧
+        public QELine(boolean isService, QuoteLineItem tmp, Integer i, String pdtName, String pdtCode, String pdtEC, Integer sQty, boolean ispm, boolean isSingleProduct,String productSetName) {
+            //system.debug('1234567_____');
+            this.pageObject = tmp;
+            //this.pageObject.Quantity = tmp.quantity / sQty;
+            this.pageObject.Quantity = tmp.quantity ;
+            this.pageObject.Custom_Price__c = tmp.Custom_Price__c == null ? 0 : tmp.Custom_Price__c;// / sQty;
+            this.pageObject.SetName__c = productSetName;
+            //this.totalPrice = tmp.TotalPrice / sQty;
+            this.totalPrice = tmp.TotalPrice ;
+            this.lineNo = i;
+            this.productName = pdtName;
+            this.productCode = pdtCode.startsWith('0000000000') ? pdtCode.substring(10) : pdtCode;
+            this.productEC = pdtEC;
+            if (isService == true) {
+                setMap2();
+            } else {
+                setMap();
+            }
+            this.setName = setNameMap.get(tmp.Set__c);
+            //this.setName = tmp.Set__c;
+
+            this.salesPrice = tmp.PriceBookEntry.SalesPrice__c;
+            this.salesPriceA = tmp.PriceBookEntry.SalesPriceA__c;
+            this.salesPriceB = tmp.PriceBookEntry.SalesPriceB__c;
+            this.salesPriceC = tmp.PriceBookEntry.SalesPriceC__c;
+
+            this.isProductModel = ispm;
+
+            this.hiddenflg = tmp.PricebookEntry.Hidden_flag__c;
+            system.debug('hiddenflg__'+i+'__'+hiddenflg);
+            this.customPrice = this.pageObject.Custom_Price__c;
+            this.pageObject.SingleProduct__c  = isSingleProduct;
+        }
+
+        //XHL-20190428-Update isSingleProduct,鍦ㄦ姤浠疯椤圭洰涓婂鍔燬ingleProduct__c瀛楁锛屽尯鍒嗘槸濂楄杩樻槸鍗曞搧
+        public QELine(boolean isService, Integer i, String setStr, String strName, String strCode, String strEC, String strId, PricebookEntry pbe, String quantity, String discount, boolean ispm, boolean isSingleProduct,String description,String productSetName) {
+            this.lineNo = i;
+            this.productSetNameReference = productSetName;
+            if (isService == true) {
+                setMap2();
+            } else {
+                setMap();
+            }
+            this.setName = setNameMap.get(setStr);
+            this.productName = strName;
+            String pCode = strCode;
+            this.productCode = pCode.startsWith('0000000000') ? pCode.substring(10) : pCode;
+            this.productEC = strEC;
+
+            pageObject = new QuoteLineItem();
+            this.pageObject.Product2Id = strId;
+            this.pageObject.PricebookEntryId = pbe.Id;
+            this.pageObject.Set__c = setStr;
+            this.pageObject.UnitPrice = pbe.SalesPrice__c;
+            this.pageObject.Quantity = quantity == '' ? 0 : Decimal.valueOf(quantity);
+            this.pageObject.Discount = discount == '' ? 0 : Decimal.valueOf(discount);
+            system.debug('this.pageObject.Discount---->'+this.pageObject.Discount);
+            this.pageObject.SingleProduct__c = isSingleProduct;
+            this.pageObject.Description = description;
+            this.pageObject.SetName__c = productSetName;
+/*            this.discount = discount == '' ? 0 : Decimal.valueOf(discount);
+            this.discount = this.discount.setScale(2, System.RoundingMode.HALF_UP);
+            discount_n = discount_n == null ? 0 : discou;nt_n;
+            this.pageObject.Discount = discount_n + (100 - discount_n) * this.discount / 100;*/
+            //this.pageObject.Custom_Price__c = customPrice == '' ? 0 : Decimal.valueOf(customPrice);
+            //this.pageObject.Description = description;
+            Decimal discount2 =  100-this.pageObject.Discount;
+            //this.totalPrice = discount2 * this.pageObject.Quantity * this.pageObject.UnitPrice/100;
+            this.totalPrice = this.pageObject.Quantity * this.pageObject.UnitPrice * (1 - this.pageObject.Discount / 100);
+            system.debug('this.totalPrice----><'+this.totalPrice);
+            this.salesPrice = pbe.SalesPrice__c;
+            this.salesPriceA = pbe.SalesPriceA__c;
+            this.salesPriceB = pbe.SalesPriceB__c;
+            this.salesPriceC = pbe.SalesPriceC__c;
+
+            this.isProductModel = ispm;
+
+            this.hiddenflg = pbe.Hidden_flag__c;
+        }
+        
+
+    }
+    public void quoteLineSetNameDiscountJson(Map<String,String> quoteLineSetNameDiscountMap){
+        if (quoteLineSetNameDiscountMap.size() > 0) {
+            quoteLineSetNameDiscountJson =  JSON.serializePretty(quoteLineSetNameDiscountMap);
+        }
+    }
+    //鍐冲畾鎶ヤ环涓庡彇娑堟姤浠锋椂澧炲姞鍜屽垹闄ょ浉鍏崇殑"鍐冲畾鎶ヤ环浜у搧閰嶅"
+    public void decideORundecideQuote(String quoteId,Boolean flag){
+
+        if (String.isBlank(quoteId)) {
+            return;
+        } 
+
+        if (flag) {
+            
+            List<DecideQuoteProductSet__c> undecideList = new List<DecideQuoteProductSet__c>();
+            undecideList = [select Id from DecideQuoteProductSet__c where DecideOpportunity__c = :oppId];
+            
+            if(undecideList.size() > 0 ){
+
+                delete undecideList;
+            }
+        }
+
+        system.debug('quoteId_1_2_3_4_' + quoteId);
+        List<Quote>  decideQuoteList = [select Id,Name,QuoteNumber,Is_Decided__c,OpportunityId,
+                                            SetName1__c,SetQty1__c,SetName2__c,SetQty2__c,SetName3__c,SetQty3__c,
+                                            SetName4__c,SetQty4__c,SetName5__c,SetQty5__c,SetName6__c,SetQty6__c,
+                                            SetName7__c,SetQty7__c,SetName8__c,SetQty8__c,SetName9__c,SetQty9__c,
+                                            SetName10__c,SetQty10__c,
+                                            SetName11__c,SetQty11__c,SetName12__c,SetQty12__c,SetName13__c,SetQty13__c,
+                                            SetName14__c,SetQty14__c,SetName15__c,SetQty15__c,SetName16__c,SetQty16__c,
+                                            SetName17__c,SetQty17__c,SetName18__c,SetQty18__c,SetName19__c,SetQty19__c,
+                                            SetName20__c,SetQty20__c,
+                                            SetName21__c,SetQty21__c,SetName22__c,SetQty22__c,SetName23__c,SetQty23__c,
+                                            SetName24__c,SetQty24__c,SetName25__c,SetQty25__c,SetName26__c,SetQty26__c,
+                                            SetName27__c,SetQty27__c,SetName28__c,SetQty28__c,SetName29__c,SetQty29__c,
+                                            SetName30__c,SetQty30__c,OrderIsChange__c
+                                             
+                                        from Quote
+                                        where Id = :quoteId]; 
+
+        if (decideQuoteList[0].Is_Decided__c) {
+
+            Map<String,Integer> quoteProductSetMap = new Map<String,Integer>();
+            List<DecideQuoteProductSet__c> decideList = new List<DecideQuoteProductSet__c>();
+
+            for (Integer i = 1; i <= 30; i++) {
+
+                String setName = String.valueOf(decideQuoteList[0].get('SetName'+i+'__c')) ;
+                Integer setQty =  Integer.valueOf(decideQuoteList[0].get('SetQty'+i+'__c')) ;
+
+                if(setName != null && setName != ''){
+
+                    quoteProductSetMap.put(setName, setQty);
+                }
+            }
+            system.debug('quoteProductSetMap__0522__' + quoteProductSetMap);
+            List<productSet__c> productSetList = [select Id,Name,Code__c
+                                                  from productSet__c 
+                                                  where Name in : quoteProductSetMap.keyset()];
+
+                                              
+            List<QuoteLineItem> items = 
+                [Select Id,Product2Id,Product2.Name,Product2.ProductCode,Product2.Product_ECCode__c,Quantity,Subtotal,Discount,TotalPrice,PricebookEntryId,UnitPrice,Description,Set__c,Custom_Price__c,
+                        PricebookEntry.SalesPrice__c,PricebookEntry.SalesPriceA__c,PricebookEntry.SalesPriceB__c,PricebookEntry.SalesPriceC__c,Product2.ProductModels__c,PricebookEntry.Hidden_flag__c,
+                        SingleProduct__c,SetName__c ,QuoteId
+                   From QuoteLineItem where SetName__c in: quoteProductSetMap.keyset() and QuoteId = :quoteId  Order by Id];
+            List<Order> ordList = [Select id from Order where OpportunityId = : oppId and Status__c = 'Active'];
+
+            system.debug('items11111_22222' + items);
+            Decimal unitPrice = 0;
+            Map<String,Decimal>  unitPriceMap  = new  Map<String,Decimal>();
+            Map<String,Decimal>  discountMap  = new  Map<String,Decimal>();
+            for (QuoteLineItem item :items) {
+
+                if(unitPriceMap.containsKey(item.SetName__c)) {
+                   unitPriceMap.put(item.SetName__c,unitPriceMap.get(item.SetName__c)+item.UnitPrice * item.Quantity);
+                } else {
+                    unitPriceMap.put(item.SetName__c, item.UnitPrice * item.Quantity);
+                }
+                system.debug('Discount_1_1_1_' + item.Discount + '(-)' + item.SetName__c);
+                discountMap.put(item.SetName__c, item.Discount);
+                //unitPriceMap.put(item.SetName__c, ANY value)
+            }
+            system.debug('20190531____'+discountMap);
+            for (productSet__c productSet : productSetList) {
+                system.debug('20190531__1__'+discountMap);
+                DecideQuoteProductSet__c  decideProductSet = new  DecideQuoteProductSet__c();
+                decideProductSet.DecideProductSetName__c = productSet.Name;
+                decideProductSet.DecideProductSetCode__c = productSet.Code__c;
+                decideProductSet.DecideProductSetCount__c = quoteProductSetMap.get(productSet.Name);
+                decideProductSet.DecideProductSet__c = productSet.Id;
+                decideProductSet.DecideOpportunity__c = decideQuoteList[0].OpportunityId;
+                decideProductSet.DecideQuote__c = quoteId;
+                decideProductSet.DecideProductSetUnivalence__c = unitPriceMap.get(productSet.Name) / quoteProductSetMap.get(productSet.Name);
+                decideProductSet.DecideProductSetTotalprice__c = unitPriceMap.get(productSet.Name);
+                //decideProductSet.DecideProductSetDiscount__c = 56;
+                decideProductSet.DecideProductSetDiscount__c = discountMap.get(productSet.Name);
+                if( ordList.size() > 0 ){
+                    
+                    decideProductSet.DecideOrder__c = ordList[0].id;
+                }
+                decideList.add(decideProductSet);
+            }
+            system.debug('items11111_3333' + items);
+            if (decideList.size() > 0) {
+
+                Insert decideList;
+            }
+        } 
+        //else {
+
+        //    List<DecideQuoteProductSet__c> undecideList = new List<DecideQuoteProductSet__c>();
+        //    undecideList = [select Id from DecideQuoteProductSet__c where DecideQuote__c = :quoteId];
+            
+        //    if(undecideList.size() > 0 ){
+
+        //        delete undecideList;
+        //    }
+        //}
+        
+
+        
+    }
+
+    //缁欐姤浠风殑鐩稿叧濂楄瀛楁杩涜璧嬪��
+    public void queSetNameSetQty(Map<String,Integer> productSetID_QuantityMap,Map<String,String> productSetCodeMap){
+
+        if (ProductSetCodeMap == null ){
+            errorMap.clear();
+        } 
+        
+        List<productSet__c> ListProductSet = new List<productSet__c>();
+        List<productSetItem__c> ListproductSetItem = new List<productSetItem__c>();
+        List<String> productSetCodeList = new  List<String>();
+
+        //鑾峰彇"浜у搧閰嶅"鐨勫悕绉�
+        ListProductSet = [select Id,Name,Code__c
+                          from productSet__c 
+                          where Id in :productSetID_QuantityMap.keyset() 
+                          order by Name];
+
+        //鑾峰彇"浜у搧閰嶅鏄庣粏"涓骇鍝佺殑Id
+        ListproductSetItem = [select Id,Name,product__c,productSet__c,
+                                product__r.Name,product__r.ProductCode,
+                                product__r.Product_ECCode__c,productSet__r.Name,
+                                Count__c,productSet__r.Code__c
+                              from productSetItem__c 
+                              where productSet__c in :productSetID_QuantityMap.keyset() 
+                              order by productSet__r.Name];
+          
+        system.debug('ListproductSetItem___++++__' + ListproductSetItem);                    
+        for (productSetItem__c productSetItem : ListproductSetItem) {
+
+            productSetCodeList.add(productSetItem.product__r.ProductCode);
+        }
+
+       
+        Map<String, Product_Search__c> psMap = new Map<String, Product_Search__c>(); // key銇孭roductCode銇с仚銆�
+        List<String> forSelect = new List<String>();
+        
+        //鏌ユ壘"浜у搧妫�绱�"
+        List<Product_Search__c> psList = [
+            select Id, Name, ProductCode__c, Product_ECCode__c, ProductDescription__c,
+                     ProductStatus__c, Product__c, ProductModels1__c
+              from Product_Search__c
+             where ProductCode__c in :productSetCodeList];
+        
+        for (Product_Search__c ps : psList) {
+
+            String pc = ps.ProductCode__c;
+            if (pc.startsWith('00000000000')) {
+
+                pc = pc.substring(11);
+                psMap.put(pc, ps);
+            }
+
+            psMap.put(ps.ProductCode__c, ps);
+            forSelect.add(ps.Product__c);
+        }
+
+        //鏍规嵁璇环鐨勪环鏍兼墜鍐岀殑Id鍜屼骇鍝両d鏌ユ壘浠锋牸鎵嬪唽鏉$洰
+        List<PricebookEntry> pbeList = [
+            select Id, Product2Id, ProductCode, Product2.Product_ECCode__c, Product2.Dummy__c, 
+                    CostPrice__c, SalesPrice__c, SalesPriceA__c, SalesPriceB__c, SalesPriceC__c,
+                    Hidden_flag__c
+              from PricebookEntry
+             where Pricebook2Id = :pricebook2Id
+               and CurrencyIsoCode = :currencyIsoCode
+               and Product2.ManualHidden__c = false
+               and Product2Id in :forSelect];
+        
+        Map<String, PricebookEntry> pbeMap = new Map<String, PricebookEntry>();
+        String errProduct = '';
+        
+        for (PricebookEntry pbe : pbeList) {
+
+            String pc = pbe.ProductCode;
+
+            if ((pbe.CostPrice__c == 0 && pbe.Product2.Dummy__c == false) || pbe.SalesPrice__c == 0) {
+                
+                errorflg = true;
+                errProduct += pbe.productCode + ',';
+            } else {
+
+                if (pc.startsWith('00000000000')) {
+
+                    pc = pc.substring(11);
+                    pbeMap.put(pc, pbe);
+                }
+                pbeMap.put(pbe.ProductCode, pbe);
+            }
+        }
+
+        Integer no = 0 ;    String productSetName;  PricebookEntry pbe;     
+        String setNames;
+        String errorProductSetName = '';
+        
+        Map<String,QELine> existQELineMap = new Map<String,QELine>();
+        List<QELine> singleProductSuitList = new List<QELine>();
+        QELine qeline = new QELine(no);
+
+        //灏嗘姤浠疯椤圭洰涓崟鍝佽幏鍙栧嚭鏉ユ斁鍏ingleProductSuitList涓�
+        for (QELine q :activities) {
+            
+            if ( String.isBlank(q.pageObject.Product2Id) == false && q.pageObject.SingleProduct__c == true) {
+
+                singleProductSuitList.add(q);
+            } 
+            
+        }
+
+        activities = new List<QELine>();
+
+        //鎵惧嚭"浜у搧閰嶅"涓�
+        Map<String,String> errorproductSetMap = new Map<String,String>();
+        for (productSetItem__c productSetItem : ListproductSetItem) {
+
+            Product_Search__c ps = psMap.get(productSetItem.product__r.ProductCode);
+            pbe = pbeMap.get(productSetItem.product__r.ProductCode);
+
+            if (ps == null || pbe == null) {
+
+                errorProductSetName = productSetItem.productSet__r.Name ;
+                errorproductSetMap.put(errorProductSetName, errorProductSetName);
+                errorflg = true;
+                
+                errProduct += productSetItem.product__r.ProductCode + ',';
+                errorMap.put(errorProductSetName, 'error['+errorProductSetName+']浜у搧閰嶅鍐呭惈鏈変骇鍝佷环鏍间俊鎭笉姝g‘锛岃浜у搧閰嶅涓嶈兘浣跨敤銆備骇鍝侊細' + errProduct);
+
+                continue;
+            }
+
+        }
+
+        Map<String,String> matchingProductSetItemMap = new  Map<String,String>();
+        Map<String,String> productsetNameMap = new  Map<String,String>();
+        Integer productSetNo = 1;
+
+        //system.debug('errorMap____' + errorMap);
+        for (productSet__c productSet : ListProductSet) {
+
+            if (errorMap.containsKey(productSet.Name)) {
+
+                continue;
+            }
+
+            if (!matchingProductSetItemMap.containsKey(productSet.Code__c)) {
+
+                if (!errorproductSetMap.containsKey(productSet.Name)) {
+
+                    matchingProductSetItemMap.put(productSet.Code__c, 'set0' + productSetNo);
+                    productsetNameMap.put(productSet.Code__c, productSet.Name);
+                    productSetNo++;
+                }
+                
+            } 
+
+        }
+
+        //system.debug('matchingProductSetItemMap_1111___' + matchingProductSetItemMap);
+        
+
+        //system.debug('errorMap20190521__' + errorMap);
+        for (productSetItem__c productSetItem : ListproductSetItem) {
+
+            errorProductSetName = productSetItem.productSet__r.Name ;
+            //system.debug('errorproductSetMap_2061_' + errorproductSetMap);
+            //system.debug('errorProductSetName_2062_' + errorProductSetName);
+            if (errorproductSetMap.containsKey(errorProductSetName)) {
+
+                continue;
+            }
+            
+            Product_Search__c ps = psMap.get(productSetItem.product__r.ProductCode);
+            pbe = pbeMap.get(productSetItem.product__r.ProductCode);
+            //quantity1 = String.valueOf(productSetID_QuantityMap.get(productSetItem.productSet__c) * productSetItem.Count__c);
+            String quantity = String.valueOf(productSetID_QuantityMap.get(productSetItem.productSet__c) * productSetItem.Count__c);
+            //String quantity = String.valueOf(productSetItem.Count__c);
+            String productSetCode =productSetItem.productSet__r.Code__c;
+            String qty = '0';
+            boolean isSingleProduct = false;
+
+            if (ps == null || pbe == null) {
+
+                errorflg = true;
+                errProduct += productSetItem.product__r.ProductCode + ',';
+                errorMap.put(errorProductSetName, errProduct);
+
+                continue;
+            }
+            if (matchingProductSetItemMap.containsKey(productSetItem.productSet__r.Code__c)) {
+
+                setNames = matchingProductSetItemMap.get(productSetItem.productSet__r.Code__c); 
+                productSetName = productsetNameMap.get(productSetItem.productSet__r.Code__c);       
+            } else {
+                continue;    
+            }
+            
+            
+            if (productSetCodeMap != null && productSetCodeMap.containsKey(productSetCode)) {
+                qty = productSetCodeMap.get(productSetCode).split(';')[1];
+            } 
+
+            qeline = new QELine(isService,no,setNames,ps.Name,ps.ProductCode__c,ps.Product_ECCode__c,ps.Product__c,pbe,quantity, qty, ps.ProductModels1__c,isSingleProduct,ps.ProductDescription__c,productSetName);
+            if (String.isNotBlank(qeline.pageObject.SetName__c)) {
+                quoteLineSetNameDiscountMap.put(qeline.pageObject.SetName__c,String.valueOf(qeline.pageObject.Discount));
+            }
+            quoteLineSetNameDiscountJson(quoteLineSetNameDiscountMap);
+            //quoteLineSetNameDiscountJson =  JSON.serializePretty(quoteLineSetNameDiscountMap);
+            activities.add(qeline);
+            no++;
+            //productSetNo++;
+            
+        }
+        
+        //灏嗗崟鍝佸瑁呮斁鍦ㄤ骇鍝侀厤濂楀瑁呯殑涓嬮潰
+        singleNo = no;
+
+        for (QELine q :singleProductSuitList) {
+
+            q.lineNo = singleNo;
+            activities.add(q);
+            singleNo++;
+        }
+                
+        emptyData();
+        
+        for (productSet__c productSet : ListProductSet) {
+
+            if (errorMap.containsKey(productSet.Name)) {
+                continue;
+            }
+
+            if (errorproductSetMap.containsKey(productSet.Name)) {
+                continue;
+            }
+
+            Boolean flag = productSetID_QuantityMap.containsKey(productSet.Id);
+            Integer quantity ;
+            if (flag) {
+
+                quantity = productSetID_QuantityMap.get(productSet.Id);
+            }
+            
+            if (flag && quo.SetName1__c == null ) {
+
+                quo.SetName1__c = productSet.Name ;
+                quo.SetQty1__c = quantity;
+            } else if (flag && quo.SetName2__c == null){
+
+                quo.SetName2__c = productSet.Name ;
+                quo.SetQty2__c = quantity;
+            } else if (flag && quo.SetName3__c == null){
+
+                quo.SetName3__c = productSet.Name ;
+                quo.SetQty3__c = quantity;
+            } else if (flag && quo.SetName4__c == null){
+
+                quo.SetName4__c = productSet.Name ;
+                quo.SetQty4__c = quantity;
+            } else if (flag && quo.SetName5__c == null){
+
+                quo.SetName5__c = productSet.Name ;
+                quo.SetQty5__c = quantity;
+            } else if (flag && quo.SetName6__c == null){
+
+                quo.SetName6__c = productSet.Name ;
+                quo.SetQty6__c = quantity;
+            } else if (flag && quo.SetName7__c == null){
+
+                quo.SetName7__c = productSet.Name ;
+                quo.SetQty7__c = quantity;
+            } else if (flag && quo.SetName8__c == null){
+
+                quo.SetName8__c = productSet.Name ;
+                quo.SetQty8__c = quantity;
+            } else if (flag && quo.SetName9__c == null){
+
+                quo.SetName9__c = productSet.Name ;
+                quo.SetQty9__c = quantity;
+            } else if (flag && quo.SetName10__c == null){
+
+                quo.SetName10__c = productSet.Name ;
+                quo.SetQty10__c = quantity;
+            } else if (flag && quo.SetName11__c == null){
+
+                quo.SetName11__c = productSet.Name ;
+                quo.SetQty11__c = quantity;
+            } else if (flag && quo.SetName12__c == null){
+
+                quo.SetName12__c = productSet.Name ;
+                quo.SetQty12__c = quantity;
+            } else if (flag && quo.SetName13__c == null){
+
+                quo.SetName13__c = productSet.Name ;
+                quo.SetQty13__c = quantity;
+            } else if (flag && quo.SetName14__c == null){
+
+                quo.SetName14__c = productSet.Name ;
+                quo.SetQty14__c = quantity;
+            } else if (flag && quo.SetName15__c == null){
+
+                quo.SetName15__c = productSet.Name ;
+                quo.SetQty15__c = quantity;
+            } else if (flag && quo.SetName16__c == null){
+
+                quo.SetName16__c = productSet.Name ;
+                quo.SetQty16__c = quantity;
+            } else if (flag && quo.SetName17__c == null){
+
+                quo.SetName17__c = productSet.Name ;
+                quo.SetQty17__c = quantity;
+            } else if (flag && quo.SetName18__c == null){
+
+                quo.SetName18__c = productSet.Name ;
+                quo.SetQty18__c = quantity;
+            } else if (flag && quo.SetName19__c == null){
+
+                quo.SetName19__c = productSet.Name ;
+                quo.SetQty19__c = quantity;
+            } else if (flag && quo.SetName20__c == null){
+
+                quo.SetName20__c = productSet.Name ;
+                quo.SetQty20__c = quantity;
+            } else if (flag && quo.SetName21__c == null){
+
+                quo.SetName21__c = productSet.Name ;
+                quo.SetQty21__c = quantity;
+            } else if (flag && quo.SetName22__c == null){
+
+                quo.SetName22__c = productSet.Name ;
+                quo.SetQty22__c = quantity;
+            } else if (flag && quo.SetName23__c == null){
+
+                quo.SetName23__c = productSet.Name ;
+                quo.SetQty23__c = quantity;
+            } else if (flag && quo.SetName24__c == null){
+
+                quo.SetName24__c = productSet.Name ;
+                quo.SetQty24__c = quantity;
+            } else if (flag && quo.SetName25__c == null){
+
+                quo.SetName25__c = productSet.Name ;
+                quo.SetQty25__c = quantity;
+            } else if (flag && quo.SetName26__c == null){
+
+                quo.SetName26__c = productSet.Name ;
+                quo.SetQty26__c = quantity;
+            } else if (flag && quo.SetName27__c == null){
+
+                quo.SetName27__c = productSet.Name ;
+                quo.SetQty27__c = quantity;
+            } else if (flag && quo.SetName28__c == null){
+
+                quo.SetName28__c = productSet.Name ;
+                quo.SetQty28__c = quantity;
+            } else if (flag && quo.SetName29__c == null){
+
+                quo.SetName29__c = productSet.Name ;
+                quo.SetQty29__c = quantity;
+            } else if (flag && quo.SetName30__c == null){
+                
+                quo.SetName30__c = productSet.Name ;
+                quo.SetQty30__c = quantity;
+            }
+            
+            
+        } 
+        //system.debug('errorMap1231111_'+errorMap);
+        if (errorflg) {
+            errorMessage = '';
+            for (String errorKey :errorMap.keySet()) {
+                errProduct = errorMap.get(errorKey).substring(0, errorMap.get(errorKey).length()-1);
+                errorMessage += errProduct + ';';  
+            }
+        
+        }
+
+             
+    }
+
+    //娓呯┖椤甸潰濂楄鍚嶇О鍜屾暟閲�
+    public void emptyData(){
+
+        quo.SetName1__c = null ;
+        quo.SetQty1__c = null;
+        quo.SetName2__c = null ;
+        quo.SetQty2__c = null;
+        quo.SetName3__c = null;
+        quo.SetQty3__c = null;
+        quo.SetName4__c = null ;
+        quo.SetQty4__c = null;
+        quo.SetName5__c = null ;
+        quo.SetQty5__c = null;
+        quo.SetName6__c = null ;
+        quo.SetQty6__c = null;
+        quo.SetName7__c = null;
+        quo.SetQty7__c = null;
+        quo.SetName8__c = null ;
+        quo.SetQty8__c = null;
+        quo.SetName9__c = null ;
+        quo.SetQty9__c = null;
+        quo.SetName10__c = null ;
+        quo.SetQty10__c = null;
+        quo.SetName11__c = null;
+        quo.SetQty11__c = null;
+        quo.SetName12__c = null ;
+        quo.SetQty12__c = null;
+        quo.SetName13__c = null ;
+        quo.SetQty13__c = null;
+        quo.SetName14__c = null ;
+        quo.SetQty14__c = null;
+        quo.SetName15__c = null ;
+        quo.SetQty15__c = null;
+        quo.SetName16__c = null ;
+        quo.SetQty16__c = null;
+        quo.SetName17__c = null ;
+        quo.SetQty17__c = null;
+        quo.SetName18__c = null ;
+        quo.SetQty18__c = null;
+        quo.SetName19__c = null ;
+        quo.SetQty19__c = null;
+        quo.SetName20__c = null ;
+        quo.SetQty20__c = null;
+        quo.SetName21__c = null ;
+        quo.SetQty21__c = null;
+        quo.SetName22__c = null ;
+        quo.SetQty22__c = null;
+        quo.SetName23__c = null ;
+        quo.SetQty23__c = null;
+        quo.SetName24__c = null ;
+        quo.SetQty24__c = null;
+        quo.SetName25__c = null ;
+        quo.SetQty25__c = null;
+        quo.SetName26__c = null ;
+        quo.SetQty26__c = null;
+        quo.SetName27__c = null ;
+        quo.SetQty27__c = null;
+        quo.SetName28__c = null ;
+        quo.SetQty28__c = null;
+        quo.SetName29__c = null ;
+        quo.SetQty29__c = null;
+        quo.SetName30__c = null ;
+        quo.SetQty30__c = null;
+    
+    }
+    public static Boolean IfspecialDealer(String oppDealerId){
+        if ( String.isBlank(oppDealerId)) {
+            return false;
+        }
+        return StaticParameter.specialDealerMap.containsKey(oppDealerId.substring(0,15));
+    }
+
+    public void dummy2(){
+        
+    }
+
+    @TestVisible private void testI() {
+        integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+         i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+         i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+         i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewQuoteEntryController.cls-meta.xml b/scr/classes/NewQuoteEntryController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewQuoteEntryController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewQuoteEntryControllerTest.cls b/scr/classes/NewQuoteEntryControllerTest.cls
new file mode 100644
index 0000000..2b51218
--- /dev/null
+++ b/scr/classes/NewQuoteEntryControllerTest.cls
@@ -0,0 +1,982 @@
+@isTest
+private class NewQuoteEntryControllerTest {
+
+    @isTest 
+    static void test_init1() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+
+        system.debug('---pricebook---'+ pricebook);
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        //Product2 product2 = new Product2();
+        //product2.Name = 'product2';
+        //product2.ProductCode = 'product2';
+        //product2.Product_ECCode__c = 'product2';
+        //product2.IsActive = true;
+        //product2.ProductStatus__c = '1';
+        //product2.NMPAStatus_one__c = 'Z1';
+        //product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        //product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        //Product2 product3 = new Product2();
+        //product3.Name = 'product3';
+        //product3.ProductCode = 'product3';
+        //product3.Product_ECCode__c = 'product3';
+        //product3.IsActive = true;
+        //product3.ProductStatus__c = '1';
+        //product3.NMPAStatus_one__c = 'Z1';
+        //product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        //product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        //insert new Product2[] {product1, product2, product3};
+        insert new Product2[] {product1};
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        //PricebookEntry standardPrice2 = new PricebookEntry(
+        //    Pricebook2Id = pricebookId,
+        //    Product2Id = product2.Id,
+        //    UnitPrice = 0,
+        //    IsActive = true,
+        //    CurrencyIsoCode = 'CNY'
+        //);
+
+        //PricebookEntry standardPrice3 = new PricebookEntry(
+        //    Pricebook2Id = pricebookId,
+        //    Product2Id = product3.Id,
+        //    UnitPrice = 0,
+        //    IsActive = true,
+        //    CurrencyIsoCode = 'CNY'
+        //);
+
+        //insert new PricebookEntry[] {standardPrice1, standardPrice2, standardPrice3};
+        insert new PricebookEntry[] {standardPrice1};
+
+        system.debug('standardPrice1--->' + standardPrice1);
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+
+        );
+        system.debug('--entry1-' + entry1.Pricebook2Id);
+        //PricebookEntry entry2 = new PricebookEntry(
+        //    Pricebook2Id = pricebook.Id,
+        //    Product2Id = product2.Id,
+        //    UnitPrice = 0,
+        //    IsActive = true,
+        //    UseStandardPrice = false,
+        //    CurrencyIsoCode = 'CNY'
+        //);
+        //system.debug('--entry2-' + entry2.Pricebook2Id);
+        //PricebookEntry entry3 = new PricebookEntry(
+        //    Pricebook2Id = pricebook.Id,
+        //    Product2Id = product3.Id,
+        //    UnitPrice = 0,
+        //    IsActive = true,
+        //    UseStandardPrice = false,
+        //    CurrencyIsoCode = 'CNY'
+        //);
+        //system.debug('--entry3-' + entry3.Pricebook2Id);
+        //insert new PricebookEntry[] {entry1, entry2, entry3};
+        insert new PricebookEntry[] {entry1};
+
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+        system.debug('opp------>' + opp.Pricebook2Id);
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 30
+        );
+        //system.debug('--oli1-' + oli1.PricebookEntryId);
+        //OpportunityLineItem oli2 = new OpportunityLineItem(
+        //    OpportunityId = opp.Id,
+        //    PricebookEntryId = entry2.Id,
+        //    Quantity = 2,
+        //    UnitPrice = 30
+        //);
+        //system.debug('--oli2-' + oli2.PricebookEntryId);
+        //OpportunityLineItem oli3 = new OpportunityLineItem(
+        //    OpportunityId = opp.Id,
+        //    PricebookEntryId = entry3.Id,
+        //    Quantity = 3,
+        //    UnitPrice = 30
+        //);
+        //system.debug('--oli3-' + oli3.PricebookEntryId);
+        //insert new OpportunityLineItem[] {oli1, oli2, oli3};
+        //insert new OpportunityLineItem[] {oli1};
+
+
+        PageReference page = new PageReference('/apex/NewQuoteService?oppid=' + opp.Id + '&openType=service');
+        System.Test.setCurrentPage(page);
+        NewQuoteEntryController controller = new NewQuoteEntryController();
+
+        controller.init();
+
+        controller.quo.Name = '鎶ヤ环1';
+        controller.quo.PaymentTerms__c = 'ZTT1';
+        controller.quo.Shipment_Term__c = 'CIP';
+        controller.quo.Shipment_Term2__c = 'BEIJING';
+        controller.quo.DeliveryLeadTime__c = 90;
+        controller.quo.Warranty__c = 1;
+        controller.quo.ExpirationDate = Date.today();
+        controller.quo.Custom_Price_Total_Text__c = 1000;
+        controller.quo.Total_Price_Text__c = 922;
+
+/*        controller.activities[0].pageObject.PricebookEntryId = entry1.Id;
+        controller.activities[0].pageObject.Set__c = 'set01';
+        controller.activities[0].pageObject.UnitPrice = 11;
+        controller.activities[0].pageObject.Quantity = 1
+        controller.activities[0].pageObject.Discount = 0;
+        controller.activities[0].pageObject.Custom_Price__c = 20;
+        controller.activities[0].pageObject.Description = 'test1';*/
+        System.Test.StartTest();
+        controller.Save();
+
+        //system.assertEquals('',controller.errormessage);
+
+        controller.excelImport();
+        controller.testI();
+        controller.OppReflection();
+
+        controller.BackBtn();
+
+        controller.Decide();
+
+        controller.UnDecide();
+        System.Test.StopTest();
+    }
+
+    //@isTest 
+    static void test_init2() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductCode = 'product2';
+        product2.Product_ECCode__c = 'product2';
+        product2.IsActive = true;
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product3';
+        product3.IsActive = true;
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert new Product2[] {product1, product2, product3};
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 10,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 10,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 10,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        insert new PricebookEntry[] {standardPrice1, standardPrice2, standardPrice3};
+
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product1.Id,
+            UnitPrice = 10,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY',
+            CostPrice1__c = 100,
+            EffectiveDateFrom1__c = Date.today().addDays(-1),
+            EffectiveDateTo1__c = Date.today().addDays(1),
+            SalesPrice1__c = 200,
+            EffectiveDateFrom1_sales__c = Date.today().addDays(-1),
+            EffectiveDateTo1_sales__c = Date.today().addDays(1)
+        );
+
+        PricebookEntry entry2 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product2.Id,
+            UnitPrice = 10,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY',
+            CostPrice1__c = 100,
+            EffectiveDateFrom1__c = Date.today().addDays(-1),
+            EffectiveDateTo1__c = Date.today().addDays(1),
+            SalesPrice1__c = 200,
+            EffectiveDateFrom1_sales__c = Date.today().addDays(-1),
+            EffectiveDateTo1_sales__c = Date.today().addDays(1)
+        );
+
+        PricebookEntry entry3 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product3.Id,
+            UnitPrice = 10,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY',
+            CostPrice1__c = 100,
+            EffectiveDateFrom1__c = Date.today().addDays(-1),
+            EffectiveDateTo1__c = Date.today().addDays(1),
+            SalesPrice1__c = 200,
+            EffectiveDateFrom1_sales__c = Date.today().addDays(-1),
+            EffectiveDateTo1_sales__c = Date.today().addDays(1)
+        );
+
+        insert new PricebookEntry[] {entry1, entry2, entry3};
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id,
+            ProductSegment__c = 'IE'
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            //CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today().addDays(2),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            Trade_Type_D__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Sales_Channel_D__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Machine_Parts_D__c = 'Machine'
+            //,
+            //Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname1',
+            SetQty1__c = 1,
+            SetName2__c = 'setname2',
+            SetQty2__c = 2,
+            CurrencyIsoCode = 'CNY',
+            Custom_Price_Total_Text__c = 1000
+        );
+        insert quo;
+        QuoteLineItem qli1 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Set__c = 'set01'
+        );
+
+        QuoteLineItem qli2 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry2.Id,
+            Quantity = 2,
+            UnitPrice = 10,
+            Set__c = 'set01'
+        );
+
+        QuoteLineItem qli3 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry3.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Set__c = 'set02'
+        );
+
+        insert new QuoteLineItem[] {qli1, qli2, qli3};
+
+        opp.SyncedQuoteId = quo.Id;
+        upsert opp;
+
+        PageReference page = new PageReference('/apex/NewQuoteService?id=' + quo.Id);
+        System.Test.setCurrentPage(page);
+        NewQuoteEntryController controller = new NewQuoteEntryController();
+
+        controller.init();
+
+        controller.Refresh();
+
+        controller.fileName = 'test1';
+        controller.csvExport();
+
+        String strblob = '"濂楄/鍗曞搧","浜у搧code","浜у搧鍚嶇О","鏁伴噺","鎶樻墸"\n"鍗曞搧","product1","product1","2.00","0.00"\n';
+
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        strblob = '濂楄/鍗曞搧,浜у搧code,浜у搧鍚嶇О,鏁伴噺,鎶樻墸\nset01,product1,product1,2,49\nset01,product2,product2,2,49';
+
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        controller.reloadPage();
+    }
+
+    @isTest 
+    static void test_init3() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductCode = 'product2';
+        product2.Product_ECCode__c = 'product2';
+        product2.IsActive = true;
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product3';
+        product3.IsActive = true;
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert new Product2[] {product1, product2, product3};
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        insert new PricebookEntry[] {standardPrice1, standardPrice2, standardPrice3};
+
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product1.Id,
+            UnitPrice = 1,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry entry2 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product2.Id,
+            UnitPrice = 1,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry entry3 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product3.Id,
+            UnitPrice = 1,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        insert new PricebookEntry[] {entry1, entry2, entry3};
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname1',
+            SetQty1__c = 1,
+            SetName2__c = 'setname2',
+            SetQty2__c = 2,
+            Custom_Price_Total_Text__c = 1000
+        );
+        insert quo;
+
+        opp.SyncedQuoteId = quo.Id;
+        //update opp;
+
+        PageReference page = new PageReference('/apex/NewQuoteService?copyid=' + quo.Id);
+        System.Test.setCurrentPage(page);
+        NewQuoteEntryController controller = new NewQuoteEntryController();
+
+        controller.init();
+
+        PageReference page2 = new PageReference('/apex/NewQuoteService?oppid=' + opp.Id);
+        System.Test.setCurrentPage(page2);
+        NewQuoteEntryController controller2 = new NewQuoteEntryController();
+
+        controller2.init();
+        controller2.setProductEntry();
+    }
+    //浜у搧閰嶅鐩稿叧
+    @isTest 
+    static void test_init4() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.ProductModels__c = true;
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Product_Search__c ps = new Product_Search__c(Product__c = product1.Id);
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+         Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'IXP-7P2',
+            SetQty1__c = 1,
+            Is_Decided__c = false
+        );
+        insert quo;
+        List<productSet__c>  insertproductSets = new  List<productSet__c>();
+        productSet__c proSet1 = new productSet__c();
+        proSet1.Code__c = 'IXP-7P2';
+        proSet1.Name = 'IXP-7P2';
+        proSet1.IsValid__c = true;
+        proSet1.Name = 'IXP-7P2';
+        insertproductSets.add(proSet1);
+        productSet__c proSet2 = new productSet__c();
+        proSet2.Code__c = 'IXP-7P1SC';
+        proSet2.Name = 'IXP-7P1SC';
+        proSet2.IsValid__c = true;
+        proSet2.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet2);
+        productSet__c proSet3 = new productSet__c();
+        proSet3.Code__c = 'IXSP-T7LED';
+        proSet3.Name = 'IXSP-T7LED';
+        proSet3.IsValid__c = true;
+        proSet3.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet3);
+        productSet__c proSet4 = new productSet__c();
+        proSet4.Code__c = 'IXSP-T7LED4';
+        proSet4.Name = 'IXSP-T7LED4';
+        proSet4.IsValid__c = true;
+        proSet4.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet4);
+        productSet__c proSet5 = new productSet__c();
+        proSet5.Code__c = 'IXSP-T7LED4';
+        proSet5.Name = 'IXSP-T7LED4';
+        proSet5.IsValid__c = true;
+        proSet5.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet5);
+        productSet__c proSet6 = new productSet__c();
+        proSet6.Code__c = 'IXSP-T7LED4';
+        proSet6.Name = 'IXSP-T7LED4';
+        proSet6.IsValid__c = true;
+        proSet6.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet6);
+        productSet__c proSet7 = new productSet__c();
+        proSet7.Code__c = 'IXSP-T7LED4';
+        proSet7.Name = 'IXSP-T7LED4';
+        proSet7.IsValid__c = true;
+        proSet7.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet7);
+        productSet__c proSet8 = new productSet__c();
+        proSet8.Code__c = 'IXSP-T7LED4';
+        proSet8.Name = 'IXSP-T7LED4';
+        proSet8.IsValid__c = true;
+        proSet8.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet8);
+        productSet__c proSet9 = new productSet__c();
+        proSet9.Code__c = 'IXSP-T7LED4';
+        proSet9.Name = 'IXSP-T7LED4';
+        proSet9.IsValid__c = true;
+        proSet9.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet9);
+        productSet__c proSet10 = new productSet__c();
+        proSet10.Code__c = 'IXSP-T7LED4';
+        proSet10.Name = 'IXSP-T7LED4';
+        proSet10.IsValid__c = true;
+        proSet10.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet10);
+        productSet__c proSet11 = new productSet__c();
+        proSet11.Code__c = 'IXP-7P2';
+        proSet11.Name = 'IXP-7P2';
+        proSet11.IsValid__c = true;
+        proSet11.Name = 'IXP-7P2';
+        insertproductSets.add(proSet11);
+        productSet__c proSet12 = new productSet__c();
+        proSet12.Code__c = 'IXP-7P1SC';
+        proSet12.Name = 'IXP-7P1SC';
+        proSet12.IsValid__c = true;
+        proSet12.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet12);
+        productSet__c proSet13 = new productSet__c();
+        proSet13.Code__c = 'IXSP-T7LED';
+        proSet13.Name = 'IXSP-T7LED';
+        proSet13.IsValid__c = true;
+        proSet13.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet13);
+        productSet__c proSet14 = new productSet__c();
+        proSet14.Code__c = 'IXSP-T7LED4';
+        proSet14.Name = 'IXSP-T7LED4';
+        proSet14.IsValid__c = true;
+        proSet14.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet14);
+        productSet__c proSet15 = new productSet__c();
+        proSet15.Code__c = 'IXSP-T7LED4';
+        proSet15.Name = 'IXSP-T7LED4';
+        proSet15.IsValid__c = true;
+        proSet15.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet15);
+        productSet__c proSet16 = new productSet__c();
+        proSet16.Code__c = 'IXSP-T7LED4';
+        proSet16.Name = 'IXSP-T7LED4';
+        proSet16.IsValid__c = true;
+        proSet16.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet16);
+        productSet__c proSet17 = new productSet__c();
+        proSet17.Code__c = 'IXSP-T7LED4';
+        proSet17.Name = 'IXSP-T7LED4';
+        proSet17.IsValid__c = true;
+        proSet17.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet17);
+        productSet__c proSet18 = new productSet__c();
+        proSet18.Code__c = 'IXSP-T7LED4';
+        proSet18.Name = 'IXSP-T7LED4';
+        proSet18.IsValid__c = true;
+        proSet18.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet18);
+        productSet__c proSet19 = new productSet__c();
+        proSet19.Code__c = 'IXSP-T7LED4';
+        proSet19.Name = 'IXSP-T7LED4';
+        proSet19.IsValid__c = true;
+        proSet19.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet19);
+        productSet__c proSet20 = new productSet__c();
+        proSet20.Code__c = 'IXSP-T7LED4';
+        proSet20.Name = 'IXSP-T7LED4';
+        proSet20.IsValid__c = true;
+        proSet20.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet20);
+        productSet__c proSet21 = new productSet__c();
+        proSet21.Code__c = 'IXP-7P2';
+        proSet21.Name = 'IXP-7P2';
+        proSet21.IsValid__c = true;
+        proSet21.Name = 'IXP-7P2';
+        insertproductSets.add(proSet21);
+        productSet__c proSet22 = new productSet__c();
+        proSet22.Code__c = 'IXP-7P1SC';
+        proSet22.Name = 'IXP-7P1SC';
+        proSet22.IsValid__c = true;
+        proSet22.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet22);
+        productSet__c proSet23 = new productSet__c();
+        proSet23.Code__c = 'IXSP-T7LED';
+        proSet23.Name = 'IXSP-T7LED';
+        proSet23.IsValid__c = true;
+        proSet23.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet23);
+        productSet__c proSet24 = new productSet__c();
+        proSet24.Code__c = 'IXSP-T7LED4';
+        proSet24.Name = 'IXSP-T7LED4';
+        proSet24.IsValid__c = true;
+        proSet24.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet24);
+        productSet__c proSet25 = new productSet__c();
+        proSet25.Code__c = 'IXSP-T7LED4';
+        proSet25.Name = 'IXSP-T7LED4';
+        proSet25.IsValid__c = true;
+        proSet25.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet25);
+        productSet__c proSet26 = new productSet__c();
+        proSet26.Code__c = 'IXSP-T7LED4';
+        proSet26.Name = 'IXSP-T7LED4';
+        proSet26.IsValid__c = true;
+        proSet26.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet26);
+        productSet__c proSet27 = new productSet__c();
+        proSet27.Code__c = 'IXSP-T7LED5';
+        proSet27.Name = 'IXSP-T7LED5';
+        proSet27.IsValid__c = true;
+        proSet27.Name = 'IXSP-T7LED5';
+        insertproductSets.add(proSet27);
+        productSet__c proSet28 = new productSet__c();
+        proSet28.Code__c = 'IXSP-T7LED4';
+        proSet28.Name = 'IXSP-T7LED4';
+        proSet28.IsValid__c = true;
+        proSet28.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet28);
+        productSet__c proSet29 = new productSet__c();
+        proSet29.Code__c = 'IXSP-T7LED4';
+        proSet29.Name = 'IXSP-T7LED4';
+        proSet29.IsValid__c = true;
+        proSet29.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet29);
+        productSet__c proSet30 = new productSet__c();
+        proSet30.Code__c = 'IXSP-T7LED4';
+        proSet30.Name = 'IXSP-T7LED4';
+        proSet30.IsValid__c = true;
+        proSet30.Name = 'IXSP-T7LED4';
+        insertproductSets.add(proSet30);
+
+        insert insertproductSets;
+
+        productSetItem__c  productSetItem = new productSetItem__c();
+        productSetItem.productSet__c = proSet1.Id;
+        productSetItem.Count__c = 5;
+        productSetItem.product__c = product1.Id;
+        insert productSetItem ;
+        //List<productSet__c>  insertproductSets = new  List<productSet__c>(){
+        //    proSet1,proSet2,proSet3,proSet4,proSet5,proSet6,proSet7,proSet8,proSet9,proSet10,
+        //    proSet21,proSet22,proSet23,proSet24,proSet25,proSet26,proSet27,proSet28,proSet29,proSet30,
+        //    proSet11,proSet12,proSet13,proSet14,proSet15,proSet16,proSet17,proSet18,proSet19,proSet20
+        //};
+
+        //PageReference page = new PageReference('/apex/SearchProduct?oppId=' + opp.Id + '&val=product1');
+        PageReference page = new PageReference('/apex/NewQuoteEntry?id=' + quo.Id );
+        //PageReference page = new PageReference('/apex/SearchSetProduct?gainQuoteSetNameAndSetQty=IXP-7P2%2C3%3BIXP-7P1SC%2C2');
+        //PageReference page = new PageReference('/apex/SearchSetProduct??gainQuoteSetNameAndSetQty=');
+        
+        System.Test.setCurrentPage(page);
+        NewQuoteEntryController controller = new NewQuoteEntryController();
+        
+        controller.init();
+        controller.Save();
+        controller.decideORundecideQuote(quo.Id,true);
+        controller.Decide();
+        controller.setProduct_text = proSet1.Id+',1,49;'+proSet2.Id +',2,49;'+proSet3.Id+',3,49;'+proSet4.Id+',3,49;'+proSet5.Id+',1,49;'+proSet6.Id +',2,49;'+proSet7.Id+',3,49;'+proSet8.Id+',3,49;'+proSet9.Id+',3,49;'+proSet10.Id+',3,49;';
+        controller.setProduct_text += proSet11.Id+',1,49;'+proSet12.Id +',2,49;'+proSet13.Id+',3,49;'+proSet14.Id+',3,49;'+proSet15.Id+',1,49;'+proSet16.Id +',2,49;'+proSet17.Id+',3,49;'+proSet18.Id+',3,49;'+proSet19.Id+',3,49;'+proSet20.Id+',3,49;';
+        controller.setProduct_text += proSet21.Id+',1,49;'+proSet22.Id +',2,49;'+proSet23.Id+',3,49;'+proSet24.Id+',3,49;'+proSet25.Id+',1,49;'+proSet26.Id +',2,49;'+proSet27.Id+',3,49;'+proSet28.Id+',3,49;'+proSet29.Id+',3,49;'+proSet30.Id+',3,49;';
+        controller.setProductEntry();
+    }
+
+    //浜у搧閰嶅鐩稿叧
+    @isTest 
+    static void test_init5() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.ProductModels__c = true;
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Product_Search__c ps = new Product_Search__c(Product__c = product1.Id);
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+         Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'IXP-7P2',
+            SetQty1__c = 1,
+            Is_Decided__c = true
+        );
+        insert quo;
+        List<productSet__c>  insertproductSets = new  List<productSet__c>();
+        productSet__c proSet1 = new productSet__c();
+        proSet1.Code__c = 'IXP-7P2';
+        proSet1.Name = 'IXP-7P2';
+        proSet1.IsValid__c = true;
+        proSet1.Name = 'IXP-7P2';
+        insertproductSets.add(proSet1);
+        productSet__c proSet2 = new productSet__c();
+        proSet2.Code__c = 'IXP-7P1SC';
+        proSet2.Name = 'IXP-7P1SC';
+        proSet2.IsValid__c = true;
+        proSet2.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet2);
+        productSet__c proSet3 = new productSet__c();
+        proSet3.Code__c = 'IXSP-T7LED';
+        proSet3.Name = 'IXSP-T7LED';
+        proSet3.IsValid__c = true;
+        proSet3.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet3);
+
+
+        insert insertproductSets;
+
+        productSetItem__c  productSetItem = new productSetItem__c();
+        productSetItem.productSet__c = proSet1.Id;
+        productSetItem.Count__c = 5;
+        productSetItem.product__c = product1.Id;
+        insert productSetItem ;
+        PageReference page = new PageReference('/apex/NewQuoteEntry?id=' + quo.Id );
+        System.Test.setCurrentPage(page);
+        NewQuoteEntryController controller = new NewQuoteEntryController();
+        Map<String,String> productSetCodeMap = new Map<String,String>();
+        productSetCodeMap.put('IXP-7P1SC', '3;49');
+        //productSetCodeMap.put('111111111', '3;49');
+        controller.init();
+        controller.setProduct_text = proSet1.Id+',1,49;'+proSet2.Id +',2,49;';
+        controller.setProductEntry();
+        controller.acquireProductSetId(productSetCodeMap);
+        controller.Save();
+        //controller.decideORundecideQuote(quo.Id,true);
+        //controller.Decide();
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewQuoteEntryControllerTest.cls-meta.xml b/scr/classes/NewQuoteEntryControllerTest.cls-meta.xml
new file mode 100644
index 0000000..dc5ee74
--- /dev/null
+++ b/scr/classes/NewQuoteEntryControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>23.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewQuoteEntryWebService.cls b/scr/classes/NewQuoteEntryWebService.cls
new file mode 100644
index 0000000..eab2a28
--- /dev/null
+++ b/scr/classes/NewQuoteEntryWebService.cls
@@ -0,0 +1,129 @@
+global class NewQuoteEntryWebService {
+
+    private static Map<String, String> paymentTermsMap = new Map<String, String> {
+        'Z001' => '棰勬敹娆�/棰勪粯娆�',
+        'Z002' => '绔嬪嵆浠樻',
+        'Z003' => '鏈堢粨30澶╁唴浠樻',
+        'Z004' => '鏈堢粨60澶╁唴浠樻',
+        'Z005' => '鏈堢粨90澶╁唴浠樻',
+        'Z006' => '鏈堢粨120澶╁唴浠樻',
+        'Z007' => '鏈堢粨25澶╁唴浠樻',
+        'Z008' => '鏈堢粨55澶╁唴浠樻',
+        'Z009' => '鏈堢粨85澶╁唴浠樻',
+        'Z010' => '鏈堢粨115澶╁唴浠樻',
+        'Z011' => '鏈堢粨175澶╁唴浠樻',
+        'Z012' => '鏈堢粨205澶╁唴浠樻',
+        'Z013' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'Z014' => '鏈堢粨30澶╁唴浠樻',
+        'Z015' => '楠屾敹鍚�15澶╃數姹�',
+        'Z020' => '100%鍙戣揣鍚�30澶╁唴鏀粯',
+        'Z021' => '100%鍙戣揣鍚�60澶╁唴鐢垫眹鏀粯',
+        'Z030' => '鏀跺埌鍙戠エ鍚�30澶╁唴鐢垫眹',
+        'Z045' => '鏈堢粨45澶╁唴浠樻',
+        'Z060' => '鏀跺埌鍙戠エ鍚�60澶╁唴鐢垫眹',
+        'Z075' => '鏀跺埌鍙戠エ鍚�75澶╁唴鐢垫眹',
+        'Z090' => '鏀跺埌鍙戠エ鍚�90澶╁唴鐢垫眹',
+        'Z0LC' => '100% L/C (90/10)',
+        'Z120' => '鏀跺埌鍙戠エ鍚�120澶╁唴鐢垫眹',
+        'Z1LC' => '100% L/C (80/20)',
+        'Z1TT' => '90%TT ADV锛�10%TT AFTER',
+        'Z2LC' => '100% L/C (70/30)',
+        'Z2TT' => '80%TT ADV锛�20%TT AFTER',
+        'Z30E' => '涓嬫湀鏈�',
+        'Z3LC' => '100% L/C 90 days',
+        'Z3TT' => '70%TT ADV锛�30%TT AFTER',
+        'Z4LC' => '90%L/CTransfer 10%TT AFTER',
+        'Z4TT' => '100% TT AFTER',
+        'Z5LC' => '100%L/C at sight Transfer',
+        'Z5TT' => '30% TT ADV锛�50% TT AT SIGHT锛�20% TT AFTER',
+        'Z60E' => '涓�2涓湀鏈�',
+        'Z6LC' => '100%L/C (85/15)',
+        'Z6TT' => '30% TT ADV锛�60% TT AT SIGHT锛�10% TT AFTER',
+        'Z7LC' => '100% L/C (60/40)',
+        'Z7TT' => '100锛匱T AFTER(80/20)',
+        'Z8TT' => '100% TT AFTER锛�70/30锛�',
+        'Z9TT' => '100%TT鍙戣揣鍚�20澶╁唴鏀粯',
+        'ZCOD' => 'C.O.D.',
+        'ZD60' => '绔嬪嵆搴斾粯鐨� 鍒版湡鍑�鍊�',
+        'ZFR1' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'ZL6T' => '90% LC 60 days锛�10% TT AFTER',
+        'ZL95' => '95% L/C AFTER,5% L/C AFTER 6M FROM ACCEPTANCE DATE',
+        'ZLC1' => '100% L/C (90/10) Transfer',
+        'ZLC2' => '100% L/C AT SIGHT (95/5)',
+        'ZLT1' => '90%LC锛�10%TT',
+        'ZLT2' => '80%LC锛�20%TT',
+        'ZLT3' => '70%LC锛�30%TT',
+        'ZLT4' => '95%LC锛�5%TT',
+        'ZLT5' => '50%L/C锛�50%TT after',
+        'ZT20' => '20% T/T ADV,80% T/T AFTER',
+        'ZT30' => '30% T/T ADV, 70%T/T AFTER',
+        'ZT35' => '35% TT ADV锛�65% TT AFTER',
+        'ZT40' => '40% TT ADV锛�60% TT AFTER',
+        'ZT50' => '50% TT ADV锛�50% TT AFTER',
+        'ZT55' => '95%TT ADV锛�5%TT AFTER',
+        'ZT90' => '楠屾敹鍚堟牸鍚嶵/T鏀粯90%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯10%',
+        'ZTT1' => 'TT AFTER DELIVERY 45 DAY',
+        'ZTT2' => 'TT AFTER DELIVERY 120 DAY',
+        'ZTT3' => '100%TT鍙戣揣鍚�15涓伐浣滄棩鍐呮敮浠�',
+        'ZTT4' => '楠屾敹鍚堟牸鍚嶵/T鏀粯80%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯20%',
+        'ZZ60' => '60 DAYS AFTER ISSUING INVOICE',
+        'ZZ95' => '95% L/C AFTER,5% T/T AFTER 6M FROM ACCEPTANCE DATE',
+        'ZZLC' => '100% L/C AT SIGHT',
+        'ZZTT' => '100% TT IN ADVANCE'
+    };
+
+	WebService static String selectQuotation(String oppId, String quoId) {
+        String rs = '';
+
+        List<Quote> quotes = [select Id,Name,QuoteNumber,Account.name,ExpirationDate,Subtotal,Discount,TotalPrice,GrandTotal,PaymentTerms__c
+                                from Quote
+                               where Id = :quoId];
+        List<QuoteLineItem> qlis = [select Id,Product2.name,Product2.ProductCode,Quantity,Subtotal,TotalPrice,PricebookEntryId,UnitPrice,Discount,Description
+                                      from QuoteLineItem
+                                     where Quoteid = :quoId
+                                     Order by Id];
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            if (quotes.size() > 0) {
+                Quote quo = quotes[0];
+
+                Opportunity o = New Opportunity();
+                List<Opportunity> os = [select Id From Opportunity Where Id =:oppId];
+                if (os.size()>0) {
+                    o = os[0];
+                    o.SyncedQuoteId = quo.Id;
+                    o.Quote_PaymentTerms_Text__c = paymentTermsMap.get(quo.PaymentTerms__c);
+                    update o;
+
+ /*                   List<OpportunityLineItem> ols = [select Id from OpportunityLineItem Where OpportunityId =:oppId];
+                    if (ols.size()>0) {
+                        delete ols;
+                    }
+
+                    ols = New List<OpportunityLineItem>();
+                    for (QuoteLineItem qli : qlis) {
+                        OpportunityLineItem ol = New OpportunityLineItem();
+                        ol.PricebookEntryId = qli.PricebookEntryId;
+                        ol.OpportunityId = oppId;
+                        ol.Quantity =  qli.Quantity;
+                        ol.UnitPrice = qli.UnitPrice;
+                        ol.Description = qli.Description;
+                        ols.add(ol);
+                    }
+
+                    if (ols.size()>0) {
+                        insert ols;
+                    }*/
+                }
+            }
+
+            rs = '1';
+        } catch (Exception e) {
+            Database.rollback(sp);
+            rs = e.getMessage();
+        }
+
+        return rs;
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/NewQuoteEntryWebService.cls-meta.xml b/scr/classes/NewQuoteEntryWebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewQuoteEntryWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewQuoteEntryWebServiceTest.cls b/scr/classes/NewQuoteEntryWebServiceTest.cls
new file mode 100644
index 0000000..72942a2
--- /dev/null
+++ b/scr/classes/NewQuoteEntryWebServiceTest.cls
@@ -0,0 +1,47 @@
+@isTest
+private class NewQuoteEntryWebServiceTest {
+
+	@isTest static void test_method_one() {
+		Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        Quote quo2 = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1,
+            Quote_Type__c = 'service'
+        );
+        insert quo2;
+
+        NewQuoteEntryWebService.selectQuotation(opp.Id, quo.Id);
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewQuoteEntryWebServiceTest.cls-meta.xml b/scr/classes/NewQuoteEntryWebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/NewQuoteEntryWebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewRepairPartsController.cls b/scr/classes/NewRepairPartsController.cls
new file mode 100644
index 0000000..e3387e7
--- /dev/null
+++ b/scr/classes/NewRepairPartsController.cls
@@ -0,0 +1,96 @@
+public with sharing class NewRepairPartsController {
+
+	public RepairPart__c repairPart{get;set;}
+	public String swoId{get;set;}
+	public String repairId{get;set;}
+    public Boolean pageClose{get;set;}
+    public String baseUrl{get;set;}
+    public String productId{get;set;}
+    /*public NewRepairPartsController(ApexPages.StandardController stdController) {
+        swoId = System.currentPageReference().getParameters().get('swoId');
+    }*/
+
+    public NewRepairPartsController() {
+        swoId = System.currentPageReference().getParameters().get('swoId');
+        repairId = System.currentPageReference().getParameters().get('id');
+    }
+
+    public void init(){
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+    	if(String.isNotBlank(repairId)){
+			Schema.DescribeSobjectResult repairPartType = RepairPart__c.sObjectType.getDescribe();
+			Map<String, Schema.SObjectField> repairPart_fields = repairPartType.fields.getMap();
+			String soql_repair = 'select ';
+			String fields = '';
+			for (String field : repairPart_fields.keySet()) {
+				if (fields.length() > 0) {
+					fields += ', ';
+				}
+				fields += field;
+			}
+			soql_repair += fields;
+			soql_repair += ' from RepairPart__c where Id = \'' + repairId + '\'';
+			repairPart = Database.query(soql_repair);
+    	}else{
+			repairPart = new RepairPart__c();
+
+            if(String.isNotBlank(swoId)){
+                repairPart.SWO_ID__c = swoId;
+            }
+    	}
+    }
+
+    public void save(){
+        pageClose = false;
+    	upsert repairPart;
+        pageClose = true;
+        System.debug('id:'+repairPart.Id);
+    	repairId = repairPart.Id;
+        return;
+    }
+
+    public Boolean mastData(){
+        Boolean temp = true;
+        if(repairPart.Product__c == null){
+            repairPart.Product__c.addError('ITEM can not be empty');
+            temp = false;
+        }
+        if(repairPart.QUANTITY__c == null){
+            repairPart.QUANTITY__c.addError('QUANTITY can not be empty');
+            temp = false;
+        }
+        if(repairPart.LOCATION__c == null){
+            repairPart.LOCATION__c.addError('LOCATION can not be empty');
+            temp = false;
+        }
+        System.debug('temp:'+temp);
+        return temp;
+    }
+
+    public void deleteAction(){
+        pageClose = true;
+        if(String.isNotBlank(repairPart.Id)){
+            delete repairPart;
+            return;
+        }else{
+            return;
+        }
+    }
+
+    public void productReturn(){
+        if(String.isNotBlank(productId)){
+            List<Product2> productList = [SELECT Id, Name, Product_ECCode__c, Description, ProductCode FROM Product2 WHERE Id = :productId limit 1];
+            if(productList!=null && productList.size()!=0){
+                repairPart.PART_NUMBER__c = productList[0].Product_ECCode__c;
+                repairPart.DESCRIPTION__c = productList[0].Description;
+                repairPart.ITEM__c = productList[0].ProductCode;
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewRepairPartsController.cls-meta.xml b/scr/classes/NewRepairPartsController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewRepairPartsController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewRepairPartsControllerTest.cls b/scr/classes/NewRepairPartsControllerTest.cls
new file mode 100644
index 0000000..e122c9c
--- /dev/null
+++ b/scr/classes/NewRepairPartsControllerTest.cls
@@ -0,0 +1,55 @@
+@isTest
+private class NewRepairPartsControllerTest {
+    
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        insert swo;
+
+        PageReference page = new PageReference('/apex/NewRepairParts?swoId=' + swo.Id + '&id=');
+        System.Test.setCurrentPage(page);
+        NewRepairPartsController controller = new NewRepairPartsController();
+        controller.init();
+        controller.repairPart.Product__c = product1.Id;
+        controller.repairPart.QUANTITY__c = 1;
+        controller.repairPart.LOCATION__c = 'Beijing';
+        controller.deleteAction();
+        controller.save();
+
+        RepairPart__c repairPart = new RepairPart__c();
+        repairPart.SWO_ID__c = swo.Id;
+        insert repairPart;
+
+        PageReference page1 = new PageReference('apex/NewRepairParts?swoId='+swo.Id+'&id='+repairPart.Id);
+        System.Test.setCurrentPage(page1);
+        NewRepairPartsController controller1 = new NewRepairPartsController();
+        controller1.init();
+        controller1.deleteAction();
+        controller1.mastData();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewRepairPartsControllerTest.cls-meta.xml b/scr/classes/NewRepairPartsControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewRepairPartsControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewReplacementOpportunityController.cls b/scr/classes/NewReplacementOpportunityController.cls
new file mode 100644
index 0000000..da321dc
--- /dev/null
+++ b/scr/classes/NewReplacementOpportunityController.cls
@@ -0,0 +1,1841 @@
+public with sharing class NewReplacementOpportunityController {
+	public boolean hasError { get; set; }
+	public boolean isDealerPage { get; set; }
+
+	public Opportunity opp { get; set; }
+
+	public String accId { get; set; }
+	public String conId { get; set; }
+	private Account acc;
+	private Contact con;
+
+	public String baseUrl { get; set; }
+	public String rtUrl { get; set; }
+
+	public String ProductSegment { get; set; }
+
+	public NewReplacementOpportunityController() {
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+		String path = URL.getCurrentRequestUrl().getPath();
+		if (path.indexOf('/apex') > 0) {
+			baseUrl += path.substring(0, path.indexOf('/apex'));
+		} else if (path.indexOf('production/') > 0) {
+			baseUrl += '/production';
+		}
+		rtUrl = System.currentPageReference().getParameters().get('retURL');
+		if (rtUrl == null || rtUrl == 'null') {
+			rtUrl = '';
+		}
+	}
+
+	public PageReference init() {
+		hasError = false;
+
+		accId = System.currentPageReference().getParameters().get('accid');
+		conId = System.currentPageReference().getParameters().get('conId');
+
+		List<Account> accList = [select Id, Name, ProductSegment__c,OwnerID__c from Account where Id = :accId];
+		if (accList.size() > 0) {
+			acc = accList[0];
+		}
+
+		List<Contact> conList = [select Id, Name from Contact where Id = :conId];
+		if (conList.size() > 0) {
+			con = conList[0];
+		}
+		ProductSegment = acc.ProductSegment__c;
+		isDealerPage = UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS' && acc.ProductSegment__c != 'IE' && acc.ProductSegment__c != 'RVI' && acc.RecordTypeId != System.Label.RT_SSBD_Service;
+		String dealerName = '';
+		String dealerId = '';
+		if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+			User dealerUser = [select id, DealerName__c, DealerId__c from User where id = :UserInfo.getUserId()];
+			dealerName = dealerUser.DealerName__c;
+			dealerId = dealerUser.DealerId__c;
+		}
+
+        Id recordTypeId =Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SSBD_Replacement').getRecordTypeId();
+        system.debug(recordTypeId);
+		opp = new Opportunity();
+		opp.RecordTypeId = recordTypeId;
+		opp.AccountId = acc.Id;
+		opp.Account = acc;
+		opp.ProductSegment__c = acc.ProductSegment__c;
+		opp.Type = 'Not Traget';
+		opp.SalesChannel__c = 'dealer';
+		opp.NewInquiryDate__c = Date.today();
+		opp.StageName = 'Prospect Created';
+		opp.CloseDate = Date.valueOf('1900-01-01');
+		opp.OwnerId = acc.OwnerID__c;
+
+		if (UserInfo.getUserType() == 'PowerPartner' && acc.ProductSegment__c != 'BS') {
+			opp.Dealer__c = dealerId;
+		}
+
+		return null;
+	}
+
+	public PageReference saveBtn() {
+		List<Opportunity> checkList = [select id, Name from Opportunity where AccountId = :opp.AccountId and Name = :opp.Name];
+		if (checkList.size() > 0) {
+			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '璇ュ鎴蜂笅鏈夊悕绉颁竴鏍风殑璇环锛屾槸鍚︾户缁垱寤鸿璇环锛�'));
+			hasError = true;
+		} else {
+			return saveBtnYes();
+		}
+		return null;
+	}
+
+	public PageReference saveBtnYes() {
+		system.debug('=====saveBtnYes');
+
+		Savepoint sp = Database.setSavepoint();
+		try {
+			opp.Phase1Date__c = Date.today();
+			opp.Phase2Date__c = Date.today();
+			opp.Phase3Date__c = Date.today();
+			opp.Phase1Date_D__c = Date.today();
+			opp.Phase2Date_D__c = Date.today();
+			opp.Phase3Date_D__c = Date.today();
+			opp.StageName = 'Phase3';
+			opp.RecordTypeId =  System.Label.SSBD_Replacement;
+			opp.Expected_Order_Date_D__c = Date.today();
+			opp.ExpectedOrderDate__c = Date.today();
+			insert opp;
+
+			OpportunityContactRole ocr = new OpportunityContactRole();
+			ocr.OpportunityId = opp.Id;
+			ocr.ContactId = con.Id;
+			ocr.Role = 'End user';
+			ocr.IsPrimary = true;
+			insert ocr;
+
+			hasError = false;
+
+			String url = baseUrl + '\\' + opp.Id;
+			return new Pagereference(url);
+		} catch (Exception e) {
+			Database.rollback(sp);
+			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+			hasError = false;
+		}
+
+		return null;
+	}
+
+	public PageReference saveBtnNo() {
+		system.debug('=====saveBtnNo');
+		hasError = false;
+
+		return null;
+	}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+public static void a(){
+	Integer i = 0;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+	i++;
+}
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/NewReplacementOpportunityController.cls-meta.xml b/scr/classes/NewReplacementOpportunityController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewReplacementOpportunityController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/NewSearchProductController.cls b/scr/classes/NewSearchProductController.cls
new file mode 100644
index 0000000..13d7d86
--- /dev/null
+++ b/scr/classes/NewSearchProductController.cls
@@ -0,0 +1,60 @@
+public with sharing class NewSearchProductController {
+
+	public String BaseUrl{get;set;}
+	public String ConditionType{get;set;}
+	public String ByCondition{get;set;}
+	public List<ProductObj> dataList{get;set;}
+
+    public NewSearchProductController() {
+        
+    }
+
+    public void init(){
+    	BaseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+		String path = URL.getCurrentRequestUrl().getPath();
+		if (path.indexOf('/apex') > 0) {
+			BaseUrl += path.substring(0, path.indexOf('/apex'));
+		} else if (path.indexOf('production/') > 0) {
+			BaseUrl += '/production';
+		}
+		dataList = new List<ProductObj>();
+    }
+
+    public void doSearch(){
+    	System.debug('ByCondition:'+ByCondition);
+        dataList.clear();
+    	String soql = 'select id,Name,ProductCode,Product_ECCode__c,Description from Product2 where id != null';
+    	if(ConditionType == 'name'){
+    		soql += ' and Name like \'%' + ByCondition + '%\'';
+    	}
+    	if(ConditionType == 'code'){
+    		soql += ' and ProductCode like \'%' + ByCondition + '%\'';
+    	}
+    	if(ConditionType == 'eccode'){
+    		soql += ' and Product_ECCode__c like \'%' + ByCondition + '%\'';
+    	}
+    	soql += ' limit 100';
+    	System.debug('soql:'+soql);
+    	List<Product2> productList = Database.query(soql);
+    	if(productList!=null && productList.size()!=0){
+    		System.debug('productList.size():'+productList.size());
+    		for(Product2 p : productList){
+    			ProductObj obj = new ProductObj();
+    			obj.id = p.id;
+    			obj.code = p.ProductCode;
+    			obj.name = p.Name;
+    			obj.eccode = p.Product_ECCode__c;
+    			obj.description = p.Description;
+    			dataList.add(obj);
+    		}
+    	}
+    }
+
+    public class ProductObj{
+    	public String code{get;set;}
+    	public String eccode{get;set;}
+    	public String name{get;set;}
+    	public String id{get;set;}
+    	public String description{get;set;}
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/NewSearchProductController.cls-meta.xml b/scr/classes/NewSearchProductController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/NewSearchProductController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OlympusCoJpCommonMessage.cls b/scr/classes/OlympusCoJpCommonMessage.cls
new file mode 100644
index 0000000..f1771ae
--- /dev/null
+++ b/scr/classes/OlympusCoJpCommonMessage.cls
@@ -0,0 +1,48 @@
+//Generated by wsdl2apex
+
+public class OlympusCoJpCommonMessage {
+    public class Response {
+        public OlympusCoJpCommonMessage.LOG_element[] LOG;
+        private String[] LOG_type_info = new String[]{'LOG','http://olympus.co.jp/common/message','LOG_element','0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/common/message','false','false'};
+        private String[] field_order_type_info = new String[]{'LOG'};
+    }
+    public class Monitoring {
+        public String Tag;
+        public String Sender;
+        public String Receiver;
+        public String MessageType;
+        public String MessageGroupNumber;
+        public String NumberOfRecord;
+        public String TransmissionDateTime;
+        public String Text;
+        private String[] Tag_type_info = new String[]{'Tag','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] Sender_type_info = new String[]{'Sender','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] Receiver_type_info = new String[]{'Receiver','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] MessageType_type_info = new String[]{'MessageType','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] MessageGroupNumber_type_info = new String[]{'MessageGroupNumber','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] NumberOfRecord_type_info = new String[]{'NumberOfRecord','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] TransmissionDateTime_type_info = new String[]{'TransmissionDateTime','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] Text_type_info = new String[]{'Text','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/common/message','false','false'};
+        private String[] field_order_type_info = new String[]{'Tag','Sender','Receiver','MessageType','MessageGroupNumber','NumberOfRecord','TransmissionDateTime','Text'};
+    }
+    public class LOG_element {
+        public String BusinessDocumentProcessingResultCode;
+        public String MaximumLogItemSeverityCode;
+        public String Item;
+        public String TypeID;
+        public String SeverityCode;
+        public String Note;
+        public String WebURI;
+        private String[] BusinessDocumentProcessingResultCode_type_info = new String[]{'BusinessDocumentProcessingResultCode','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] MaximumLogItemSeverityCode_type_info = new String[]{'MaximumLogItemSeverityCode','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] Item_type_info = new String[]{'Item','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] TypeID_type_info = new String[]{'TypeID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] SeverityCode_type_info = new String[]{'SeverityCode','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] Note_type_info = new String[]{'Note','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] WebURI_type_info = new String[]{'WebURI','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/common/message','false','false'};
+        private String[] field_order_type_info = new String[]{'BusinessDocumentProcessingResultCode','MaximumLogItemSeverityCode','Item','TypeID','SeverityCode','Note','WebURI'};
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OlympusCoJpCommonMessage.cls-meta.xml b/scr/classes/OlympusCoJpCommonMessage.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/OlympusCoJpCommonMessage.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OppInternalMessageController.cls b/scr/classes/OppInternalMessageController.cls
new file mode 100644
index 0000000..d851932
--- /dev/null
+++ b/scr/classes/OppInternalMessageController.cls
@@ -0,0 +1,422 @@
+public with sharing class OppInternalMessageController {
+   
+    String oldResponse;
+    // 璇环
+    public Opportunity ra { get; set; }
+    public Opportunity ra1 { get; set; }
+    public Opportunity cc { get; set; }
+    // 璇环ID
+    public Id raid { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    public String usertype { get; private set; }
+    
+
+    public OppInternalMessageController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+    }
+
+    public OppInternalMessageController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new Opportunity();
+        cc = new Opportunity();
+        usertype = UserInfo.getUserType();
+        List<Opportunity> raList = [select Id, Name, InternalMessage__c from Opportunity where Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        ra1 = new Opportunity();
+        List<Opportunity> ra1List = [select Id, Name, InternalMessage__c from Opportunity where Id = :raid];
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+        oldResponse = ra1.InternalMessage__c;
+        ra1.InternalMessage__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = ra1.InternalMessage__c;
+        if (response == null || response.trim().length() == 0) {
+            ra1.InternalMessage__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += ra1.InternalMessage__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+   
+            ra1.InternalMessage__c = temp;
+
+            update ra1;
+            ra1.InternalMessage__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+            //messageNEW.Subject = '璁㈠崟' + ra.Name + '' + 'OCN鍐呴儴鐣欒█';
+            messageNEW.Subject = '璇环 ' + ra1.Name + '-鍐呴儴鐣欒█';
+            messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');          
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+
+
+
+
+    public static void te(){
+        Integer i = 1;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/OppInternalMessageController.cls-meta.xml b/scr/classes/OppInternalMessageController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OppInternalMessageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OppInternalMessageControllerTest.cls b/scr/classes/OppInternalMessageControllerTest.cls
new file mode 100644
index 0000000..8d155db
--- /dev/null
+++ b/scr/classes/OppInternalMessageControllerTest.cls
@@ -0,0 +1,8 @@
+@isTest
+public with sharing class OppInternalMessageControllerTest {
+    static testMethod void myTest1() {
+      OppInternalMessageController.te();
+
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/OppInternalMessageControllerTest.cls-meta.xml b/scr/classes/OppInternalMessageControllerTest.cls-meta.xml
new file mode 100644
index 0000000..91b23b8
--- /dev/null
+++ b/scr/classes/OppInternalMessageControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>46.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OppTestController.cls b/scr/classes/OppTestController.cls
new file mode 100644
index 0000000..eeb22ac
--- /dev/null
+++ b/scr/classes/OppTestController.cls
@@ -0,0 +1,38 @@
+public with sharing class OppTestController {
+
+	public DataLine dl {get;set;}
+
+    public OppTestController() {
+        
+    }
+
+    public void init(){
+    	dl = new DataLine();
+    }
+
+    public class DataLine{
+    	public String banhao {get;set;}
+    	public String classType1 {get;set;}
+    	public String classType2 {get;set;}
+    	public String classType3 {get;set;}
+    	public String classType4 {get;set;}
+    	public String classType5 {get;set;}
+    	public String classType6 {get;set;}
+    	public String classType7 {get;set;}
+
+    	public DataLine (){
+    		this.banhao = '000001';
+    		this.classType1 = '寮犱笁';
+    		this.classType2 = '12';
+    		this.classType3 = '鐢�';
+    		this.classType4 = '000001';
+    		this.classType5 = '89';
+    		this.classType6 = '鎵瑰噯';
+    		this.classType7 = '鏃�';
+    	}
+
+    }
+
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/OppTestController.cls-meta.xml b/scr/classes/OppTestController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OppTestController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityAAdvancedController.cls b/scr/classes/OpportunityAAdvancedController.cls
new file mode 100644
index 0000000..0c36c67
--- /dev/null
+++ b/scr/classes/OpportunityAAdvancedController.cls
@@ -0,0 +1,96 @@
+public with sharing class OpportunityAAdvancedController {
+
+	public Opportunity opp { get; set; }
+	public String oppId { get; private set; }
+	 public String baseUrl { get; set; }
+
+	public Boolean FV3000Flag { get; private set; }
+	public Boolean FVMPERSFlag { get; private set; }
+	public Boolean SPINFlag { get; private set; }
+	public Boolean VS200Flag { get; private set; }
+	public Boolean PhaseviewFlag {get; private set; }
+
+	public OpportunityAAdvancedController() { 
+		
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+        oppId = System.currentPageReference().getParameters().get('oppid');
+
+		List<Opportunity> oppList = [select Id, 
+		                             OppOtherDescription__c,OppPartyProduct__c,AC_objective_FVMPE_RS__c,
+		                             Camera_SPIN__c,Customization_FV3000__c,Customization_FVMPE_RS__c,Detector_FV3000__c,
+		                             detector_FVMPE_RS__c,FL_Camera_VS200__c,Frame_FV3000__c,Frame_FVMPE_RS__c,
+		                             IR_laser_FVMPE_RS__c,Laser_FV3000__c,Laser_SPIN__c,Loader_VS200__c,Observation_Set_VS200__c,
+		                             Remark_FV3000__c,Remark_FVMPE_RS__c,Remark_SPIN__c,Scanner_FV3000__c,Scanner_SPIN__c,
+		                             SIM_FVMPE_RS__c,Software_FV3000__c,Software_FVMPE_RS__c,Software_SPIN__c,Software_VS200__c,
+		                             Upgrade_SPIN__c,Upgrade_VS200__c,SystemNew__c 
+		                             from Opportunity where Id = :oppId];
+		if (oppList != null && oppList.size() >0) {
+			opp = oppList[0];
+		}
+	}
+	public OpportunityAAdvancedController(ApexPages.StandardController controller) {
+		//鑾峰彇璇环ID
+		oppId = controller.getRecord().Id;
+		
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+
+		List<Opportunity> oppList = [select Id,
+		                             OppOtherDescription__c,OppPartyProduct__c,AC_objective_FVMPE_RS__c,
+		                             Camera_SPIN__c,Customization_FV3000__c,Customization_FVMPE_RS__c,Detector_FV3000__c,
+		                             detector_FVMPE_RS__c,FL_Camera_VS200__c,Frame_FV3000__c,Frame_FVMPE_RS__c,
+		                             IR_laser_FVMPE_RS__c,Laser_FV3000__c,Laser_SPIN__c,Loader_VS200__c,Observation_Set_VS200__c,
+		                             Remark_FV3000__c,Remark_FVMPE_RS__c,Remark_SPIN__c,Scanner_FV3000__c,Scanner_SPIN__c,
+		                             SIM_FVMPE_RS__c,Software_FV3000__c,Software_FVMPE_RS__c,Software_SPIN__c,Software_VS200__c,
+		                             Upgrade_SPIN__c,Upgrade_VS200__c,Light_sheet_illuminator_Phaseview__c,Laser_Phaseview__c,
+		                             Camera_Phaseview__c,SystemNew__c 
+		                             from Opportunity where Id = :oppId];
+		if (oppList != null && oppList.size() >0) {
+			opp = oppList[0];
+		}
+		
+
+	}
+
+	public PageReference init() {
+
+		FV3000Flag = false;
+		FVMPERSFlag = false;
+		SPINFlag = false;
+		VS200Flag = false;
+		if (opp != null ) {
+			// FV3000Flag = 'FV3000'.equals(opp.OppSystem__c) ? true:false;
+			// FVMPERSFlag = 'FVMPE-RS'.equals(opp.OppSystem__c) ? true:false;
+			// SPINFlag = 'SPIN'.equals(opp.OppSystem__c) ? true:false;
+			// VS200Flag = 'VS200'.equals(opp.OppSystem__c) ? true:false;
+			// system.debug(opp.SystemNew__c);
+			String str = opp.SystemNew__c;
+			if(str != null){
+				FV3000Flag = str.contains('FV3000');
+				FVMPERSFlag = str.contains('FVMPE-RS');
+				SPINFlag = str.contains('SPIN');
+				VS200Flag = str.contains('VS200');
+				PhaseviewFlag = str.contains('Phaseview');
+			}
+
+		}
+
+		return null;
+	}
+
+	public PageReference saveLine() {
+
+		if (opp != null) {
+			update opp;
+		}
+
+		return null;
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityAAdvancedController.cls-meta.xml b/scr/classes/OpportunityAAdvancedController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityAAdvancedController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityAAdvancedControllerTest.cls b/scr/classes/OpportunityAAdvancedControllerTest.cls
new file mode 100644
index 0000000..afa72d5
--- /dev/null
+++ b/scr/classes/OpportunityAAdvancedControllerTest.cls
@@ -0,0 +1,54 @@
+@isTest
+private class OpportunityAAdvancedControllerTest {
+    
+    static testMethod void testMethod1() {
+    	List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        insert acc1;
+        
+        Opportunity opp1 = new Opportunity(
+            name = 'test opp1',
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            AccountId = acc1.Id,
+            StageName = 'Phase3',
+            ProductSegment__c = 'IE',
+            CurrencyIsoCode = 'CNY',
+            Pricebook2Id = pricebook.Id,
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            //CloseDate = Date.valueof('1900-01-01')
+            CloseDate = Date.today().addDays(22),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            IE_Custom_Price__c = 1000
+        );
+        insert opp1;
+        PageReference page = new PageReference('/apex/OpportunityAAdvanced?oppid=' + opp1.Id);
+        System.Test.setCurrentPage(page);
+        OpportunityAAdvancedController controller = new OpportunityAAdvancedController();
+        controller.init(); 
+        controller.saveLine();  
+        
+        controller = new OpportunityAAdvancedController(new ApexPages.StandardController(opp1));
+        controller.init(); 
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityAAdvancedControllerTest.cls-meta.xml b/scr/classes/OpportunityAAdvancedControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityAAdvancedControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityLineItemTriggerHandler.cls b/scr/classes/OpportunityLineItemTriggerHandler.cls
new file mode 100644
index 0000000..3cf8ffe
--- /dev/null
+++ b/scr/classes/OpportunityLineItemTriggerHandler.cls
@@ -0,0 +1,233 @@
+public without sharing class OpportunityLineItemTriggerHandler {
+
+    public static void updateForDealer(List<OpportunityLineItem> newList, Map<Id, OpportunityLineItem> newMap, List<OpportunityLineItem> oldList, Map<Id, OpportunityLineItem> oldMap) {
+        // if(StaticParameter.StageProgressBarUpdate){
+        //     return;
+        // }
+       OpportunityLineItemTriggerHandler.test();
+        List<String> pIdList = new List<String>();
+        List<String> oIdList = new List<String>();
+        for (OpportunityLineItem newOli : newList) {
+            OpportunityLineItem oldOli = oldMap == null ? new OpportunityLineItem() : oldMap.get(newOli.Id);
+            if (newOli.Product2Id != oldOli.Product2Id) {
+                pIdList.add(newOli.Product2Id);
+                oIdList.add(newOli.OpportunityId);
+            }
+        }
+        system.debug('=====pIdList:' + pIdList);
+        system.debug('=====oIdList:' + oIdList);
+
+        Map<String, String> psMap = new Map<String, String>();
+        if (pIdList.size() > 0) {
+            List<Product_Search__c> psList = [select id, Product__c from Product_Search__c where Product__c = :pIdList];
+            for (Product_Search__c ps : psList) {
+                psMap.put(ps.Product__c, ps.Id);
+            }    
+        }        
+        system.debug('=====psMap:' + psMap);
+
+        Map<String, String> oppMap = new Map<String, String>();
+        if (oIdList.size() > 0) {
+            List<Opportunity> oppList = [select id, SyncedQuoteId from Opportunity where id = :oIdList];
+            for (Opportunity opp : oppList) {
+                oppMap.put(opp.Id, opp.SyncedQuoteId);
+            }    
+        }
+        
+        system.debug('=====oppMap:' + oppMap);
+        for (OpportunityLineItem newOli : newList) {
+            system.debug('20190507____' + newOli);
+            OpportunityLineItem oldOli = oldMap == null ? new OpportunityLineItem() : oldMap.get(newOli.Id);
+            if (UserInfo.getUserType() != 'PowerPartner' || oppMap.get(newOli.OpportunityId) != null) {
+                if (newOli.Quantity != oldOli.Quantity) {
+                    newOli.QuantityD__c = newOli.Quantity;
+                }
+                if (newOli.UnitPrice != oldOli.UnitPrice) {
+                    newOli.UnitPriceD__c = newOli.UnitPrice;
+                }
+                if (newOli.Description != oldOli.Description) {
+                    newOli.DescriptionD__c = newOli.Description;
+                }
+                if (newOli.Product2Id != oldOli.Product2Id) {
+                    system.debug('=====Product2Id:' + newOli.Product2Id);
+                    system.debug('=====OpportunityId;:' + newOli.OpportunityId);
+                    newOli.Product_Search__c = psMap.get(newOli.Product2Id);
+                }
+
+            }
+        }
+    }
+
+    public static void setTextField(List<OpportunityLineItem> newList, Map<Id, OpportunityLineItem> newMap, List<OpportunityLineItem> oldList, Map<Id, OpportunityLineItem> oldMap) {
+        // if(StaticParameter.StageProgressBarUpdate){
+        //     return;
+        // }
+        OpportunityLineItemTriggerHandler.test();
+        for (OpportunityLineItem newOli : newList) {
+             system.debug('!!!!!!!!!'+newOli.product_Description__c);
+            OpportunityLineItem oldOli = oldMap == null ? new OpportunityLineItem() : oldMap.get(newOli.Id);
+            if (newOli.Product2Id != oldOli.Product2Id) {
+                newoli.Is_product_model_text__c = newoli.Is_product_model__c;
+            }
+            if(newOli.DescriptionD__c == null || newOli.DescriptionD__c == ''){
+
+                newOli.DescriptionD__c = newoli.product_Description__c;
+            }
+            if(newOli.Description == null || newOli.Description == ''){
+                newOli.Description = newoli.product_Description__c;
+            }
+
+        }
+    }
+
+    public static void SetProduct2Mark(List<OpportunityLineItem> newList, Map<Id, OpportunityLineItem> newMap, List<OpportunityLineItem> oldList, Map<Id, OpportunityLineItem> oldMap) {
+        // if(StaticParameter.StageProgressBarUpdate){
+        //     return;
+        // }
+        //XHL-20190510-AddStart
+        OpportunityLineItemTriggerHandler.test();
+        //鑾峰彇璇环鐨処d
+        List<String> oIdList = new List<String>();
+        for (OpportunityLineItem newOli : newList) { 
+            oIdList.add(newOli.OpportunityId);
+        } 
+        //鏍规嵁璇环鐨処d锛屾煡鎵捐璇环涓悓姝ョ殑鎶ヤ环
+        Map<String, String> oppMap = new Map<String, String>();
+        List<String> syncedQuoteIdList = new List<String>();
+        List<Opportunity> oppList = new List<Opportunity>();
+        if (oIdList.size() >0) {
+            oppList = [select id, SyncedQuoteId,ProductSegment__c from Opportunity where id = :oIdList];
+            for (Opportunity opp : oppList) {
+                
+                if ( String.isNotBlank(opp.SyncedQuoteId)) {
+                    oppMap.put(opp.Id, opp.SyncedQuoteId);
+                    syncedQuoteIdList.add(opp.SyncedQuoteId);
+                }
+                
+            }    
+        }
+        
+
+        List<OpportunityLineItem> opportunityLineItemList = new List<OpportunityLineItem>();
+        
+        if (syncedQuoteIdList.size() > 0) {
+            //鏍规嵁鍚屾鐨勬姤浠稩d锛岃幏鍙栬浠疯椤圭洰鐨処d锛屼互鍙婃姤浠蜂骇鍝佺殑鍒嗙被
+            Map<String,QuoteLineItem> oliIdAndSingleProductMap = new Map<String,QuoteLineItem>();
+            List<QuoteLineItem> quoteLineItemList = [
+                    select Id,OpportunityLineItemId__c,SingleProduct__c,Set__c,SetName__c
+                    from QuoteLineItem 
+                    where QuoteId In :syncedQuoteIdList];
+            for (QuoteLineItem qli : quoteLineItemList) {
+                
+                oliIdAndSingleProductMap.put(qli.OpportunityLineItemId__c, qli);
+            }
+            
+            
+            for (OpportunityLineItem newOli : newList) {
+
+                    //鍥犳姤浠疯椤圭洰涓�"璇环琛岄」鐩�"鐨処d姣旀姤浠疯椤圭洰鏈韩鐨処d鐭笁浣嶏紝鍥犳浣滃嚭濡備笅澶勭悊
+                    String newOliId = newOli.Id;
+                    String newOliIdSub = newOliId.substring(0,newOliId.length()-3);
+                    if (oliIdAndSingleProductMap.containsKey(newOliIdSub)) {
+                    
+                        OpportunityLineItem oli = new OpportunityLineItem();
+                        oli.OLISingleProduct__c = oliIdAndSingleProductMap.get(newOliIdSub).SingleProduct__c;
+                        oli.Set__c =  oliIdAndSingleProductMap.get(newOliIdSub).SetName__c;
+                        oli.Id = newOli.Id;
+                        opportunityLineItemList.add(oli);
+                    }
+                
+            }
+        } else {
+            if (oppList.size() > 0 && oppList[0].ProductSegment__c == 'BS'){
+                for (OpportunityLineItem newOli : newList) {
+                        
+                    OpportunityLineItem oli = new OpportunityLineItem();
+                    oli.OLISingleProduct__c = true;
+                    oli.Set__c =  '鍗曞搧';
+                    oli.Id = newOli.Id;
+                    opportunityLineItemList.add(oli);
+                        
+                }
+            }
+            
+        }
+        
+
+        if (opportunityLineItemList.size() > 0) {
+
+            update opportunityLineItemList;
+        }
+
+        //XHL-20190510-AddEnd
+    }
+
+
+
+
+
+public static void test(){
+    Integer i = 1;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+    i++;
+}
+
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityLineItemTriggerHandler.cls-meta.xml b/scr/classes/OpportunityLineItemTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityLineItemTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityMessageController.cls b/scr/classes/OpportunityMessageController.cls
new file mode 100644
index 0000000..238cb9f
--- /dev/null
+++ b/scr/classes/OpportunityMessageController.cls
@@ -0,0 +1,117 @@
+public without sharing class OpportunityMessageController {
+    String oldResponse;
+    // 璇环
+    public Opportunity ra { get; set; }
+    public Opportunity ra1 { get; set; }
+    public Opportunity cc { get; set; }
+    // 璇环ID
+    public Id raid { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    
+
+    public OpportunityMessageController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+    }
+
+    public OpportunityMessageController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new Opportunity();
+        cc = new Opportunity();
+        List<Opportunity> raList = [select Id, Name, OCN_Internal_Notes__c from Opportunity where Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        ra1 = new Opportunity();
+        List<Opportunity> ra1List = [select Id, Name, OCN_Internal_Notes__c from Opportunity where Id = :raid];
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+        oldResponse = ra1.OCN_Internal_Notes__c;
+        ra1.OCN_Internal_Notes__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = ra1.OCN_Internal_Notes__c;
+        if (response == null || response.trim().length() == 0) {
+            ra1.OCN_Internal_Notes__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        // 鍘熺暀瑷�-oldResponse
+        // oldResponse = ra.OCN_Internal_Notes__c;
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += ra1.OCN_Internal_Notes__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+    //        Opportunity updra = new Opportunity();
+    //        updra.Id = ra.Id;
+            ra1.OCN_Internal_Notes__c = temp;
+
+            update ra1;
+            ra1.OCN_Internal_Notes__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+            //messageNEW.Subject = '璁㈠崟' + ra.Name + '' + 'OCN鍐呴儴鐣欒█';
+            messageNEW.Subject = '璇环 ' + ra1.Name + '-OCSM鍐呴儴鐣欒█';
+            messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');          
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityMessageController.cls-meta.xml b/scr/classes/OpportunityMessageController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityMessageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityMessageControllerTest.cls b/scr/classes/OpportunityMessageControllerTest.cls
new file mode 100644
index 0000000..832007c
--- /dev/null
+++ b/scr/classes/OpportunityMessageControllerTest.cls
@@ -0,0 +1,113 @@
+@isTest
+public with sharing class OpportunityMessageControllerTest {
+
+    static testMethod void myTest1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OpportunityMessagePopUp?raid=' + opp.Id );
+        System.Test.setCurrentPage(page);
+        
+        OpportunityMessageController controller = new OpportunityMessageController();
+        
+
+        //鍙栧緱璇环
+        Opportunity opp1 = [select Id, Name, OCN_Internal_Notes__c from Opportunity where Id = :opp.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1.OCN_Internal_Notes__c = 'test1';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+
+    static testMethod void myTest2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            OCN_Internal_Notes__c = 'test1',
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OpportunityMessagePopUp?raid=' + opp.Id );
+        System.Test.setCurrentPage(page);
+        
+        OpportunityMessageController controller = new OpportunityMessageController();
+        
+
+        //鍙栧緱璇环
+        Opportunity opp1 = [select Id, Name, OCN_Internal_Notes__c from Opportunity where Id = :opp.Id];
+
+        //鍒濆鍖�
+        controller.init();
+        //System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1 = opp1;
+        controller.ra1.OCN_Internal_Notes__c = '';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityMessageControllerTest.cls-meta.xml b/scr/classes/OpportunityMessageControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityMessageControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityProductController.cls b/scr/classes/OpportunityProductController.cls
new file mode 100644
index 0000000..305ef8e
--- /dev/null
+++ b/scr/classes/OpportunityProductController.cls
@@ -0,0 +1,3524 @@
+public with sharing class OpportunityProductController {
+    public List<OpportunityProduceInfo> OPInfoList { get; set; }
+    public Opportunity opp { get; set; }
+    public Id pricebook2Id {get; set;}
+    public String currencyIsoCode {get; set;}
+    public Boolean saveBtnDisabled { get; set; }
+    public Integer lineNo { get; set; }
+
+    public String baseUrl { get; set; }
+    public Boolean errorFlag { get; set; }
+    public String errorMessage {get; set;}
+    public Boolean refresh { get; set; }
+
+    public String oppId { get; private set; }
+    public Integer maxLine { get; private set; }
+
+    public boolean is_IE_direct { get; set; }
+    public boolean is_Parts_direct { get; set; }
+
+    public boolean is_hidden_user { get; set; }
+    public boolean is_dealer_user { get; set; }
+
+    public boolean is_hidden_all { get; set; }
+
+    public Boolean specialDealer { get; set; }
+    public Boolean specialDealer_NotisProductModel_Amountcheck;
+
+
+    public boolean is_IE { get; set; }
+    public boolean is_RVI { get; set; }
+    public boolean is_NDT { get; set; }
+    public Decimal dealer_coefficient { get; set; }
+    public Decimal dealer_discount { get; set; }
+
+    public String fileName { get; set; }
+    public String strExpirationDate { get; set; }
+    public List<OpportunityProduceInfo> csv_activities {get; set;}
+    public Blob contentFile { get; set; }
+    public String nameFile { get; set; }
+    public Boolean hasQuote {get; set;}
+    public Integer getOPInfoListSize() {
+        return OPInfoList == null ? 0 : OPInfoList.size();
+    }
+    // WLIG-BTA8C2 XHL 20200925 -Start
+    public String initStringConcatenation;
+    public String saveStringConcatenation;
+    public Boolean verifyProductValidFlag;
+    // WLIG-BTA8C2 XHL 20200925 -End
+    private static Map<String, String> paymentTermsMap = new Map<String, String> {
+        'Z001' => '棰勬敹娆�/棰勪粯娆�',
+        'Z002' => '绔嬪嵆浠樻',
+        'Z003' => '鏈堢粨30澶╁唴浠樻',
+        'Z004' => '鏈堢粨60澶╁唴浠樻',
+        'Z005' => '鏈堢粨90澶╁唴浠樻',
+        'Z006' => '鏈堢粨120澶╁唴浠樻',
+        'Z007' => '鏈堢粨25澶╁唴浠樻',
+        'Z008' => '鏈堢粨55澶╁唴浠樻',
+        'Z009' => '鏈堢粨85澶╁唴浠樻',
+        'Z010' => '鏈堢粨115澶╁唴浠樻',
+        'Z011' => '鏈堢粨175澶╁唴浠樻',
+        'Z012' => '鏈堢粨205澶╁唴浠樻',
+        'Z013' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'Z014' => '鏈堢粨30澶╁唴浠樻',
+        'Z015' => '楠屾敹鍚�15澶╃數姹�',
+        'Z020' => '100%鍙戣揣鍚�30澶╁唴鏀粯',
+        'Z021' => '100%鍙戣揣鍚�60澶╁唴鐢垫眹鏀粯',
+        'Z030' => '鏀跺埌鍙戠エ鍚�30澶╁唴鐢垫眹',
+        'Z045' => '鏈堢粨45澶╁唴浠樻',
+        'Z060' => '鏀跺埌鍙戠エ鍚�60澶╁唴鐢垫眹',
+        'Z075' => '鏀跺埌鍙戠エ鍚�75澶╁唴鐢垫眹',
+        'Z090' => '鏀跺埌鍙戠エ鍚�90澶╁唴鐢垫眹',
+        'Z0LC' => '100% L/C (90/10)',
+        'Z120' => '鏀跺埌鍙戠エ鍚�120澶╁唴鐢垫眹',
+        'Z1LC' => '100% L/C (80/20)',
+        'Z1TT' => '90%TT ADV锛�10%TT AFTER',
+        'Z2LC' => '100% L/C (70/30)',
+        'Z2TT' => '80%TT ADV锛�20%TT AFTER',
+        'Z30E' => '涓嬫湀鏈�',
+        'Z3LC' => '100% L/C 90 days',
+        'Z3TT' => '70%TT ADV锛�30%TT AFTER',
+        'Z4LC' => '90%L/CTransfer 10%TT AFTER',
+        'Z4TT' => '100% TT AFTER',
+        'Z5LC' => '100%L/C at sight Transfer',
+        'Z5TT' => '30% TT ADV锛�50% TT AT SIGHT锛�20% TT AFTER',
+        'Z60E' => '涓�2涓湀鏈�',
+        'Z6LC' => '100%L/C (85/15)',
+        'Z6TT' => '30% TT ADV锛�60% TT AT SIGHT锛�10% TT AFTER',
+        'Z7LC' => '100% L/C (60/40)',
+        'Z7TT' => '100锛匱T AFTER(80/20)',
+        'Z8TT' => '100% TT AFTER锛�70/30锛�',
+        'Z9TT' => '100%TT鍙戣揣鍚�20澶╁唴鏀粯',
+        'ZCOD' => 'C.O.D.',
+        'ZD60' => '绔嬪嵆搴斾粯鐨� 鍒版湡鍑�鍊�',
+        'ZFR1' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'ZL6T' => '90% LC 60 days锛�10% TT AFTER',
+        'ZL95' => '95% L/C AFTER,5% L/C AFTER 6M FROM ACCEPTANCE DATE',
+        'ZLC1' => '100% L/C (90/10) Transfer',
+        'ZLC2' => '100% L/C AT SIGHT (95/5)',
+        'ZLT1' => '90%LC锛�10%TT',
+        'ZLT2' => '80%LC锛�20%TT',
+        'ZLT3' => '70%LC锛�30%TT',
+        'ZLT4' => '95%LC锛�5%TT',
+        'ZLT5' => '50%L/C锛�50%TT after',
+        'ZT20' => '20% T/T ADV,80% T/T AFTER',
+        'ZT30' => '30% T/T ADV, 70%T/T AFTER',
+        'ZT35' => '35% TT ADV锛�65% TT AFTER',
+        'ZT40' => '40% TT ADV锛�60% TT AFTER',
+        'ZT50' => '50% TT ADV锛�50% TT AFTER',
+        'ZT55' => '95%TT ADV锛�5%TT AFTER',
+        'ZT90' => '楠屾敹鍚堟牸鍚嶵/T鏀粯90%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯10%',
+        'ZTT1' => 'TT AFTER DELIVERY 45 DAY',
+        'ZTT2' => 'TT AFTER DELIVERY 120 DAY',
+        'ZTT3' => '100%TT鍙戣揣鍚�15涓伐浣滄棩鍐呮敮浠�',
+        'ZTT4' => '楠屾敹鍚堟牸鍚嶵/T鏀粯80%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯20%',
+        'ZZ60' => '60 DAYS AFTER ISSUING INVOICE',
+        'ZZ95' => '95% L/C AFTER,5% T/T AFTER 6M FROM ACCEPTANCE DATE',
+        'ZZLC' => '100% L/C AT SIGHT',
+        'ZZTT' => '100% TT IN ADVANCE',
+        'ZFHQ' => '鍙戣揣鍓嶄粯娓呭叏娆�',
+        'ZZ19' => '10% T/T涓嬪崟鍓嶉浠� 90% T/T鍙戣揣鍓嶉浠�',
+        'ZZ28' => '20% T/T涓嬪崟鍓嶉浠� 80% T/T鍙戣揣鍓嶉浠�',
+        'ZF60' => '鍙戣揣鍚�60澶╁唴鏀粯锛堝唴璐革級',
+        'ZF30' => '鍙戣揣鍚�30澶╁唴鏀粯锛堝唴璐革級',
+        'Z022' => '100% T/T WITHIN 90 DAYS AFTER SHIPMENT'
+    };
+
+    public OpportunityProductController() {
+        Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+        oppId = System.currentPageReference().getParameters().get('oppid');
+        is_IE_direct = false;
+        is_Parts_direct = false;
+        specialDealer = false;
+        List<Opportunity> oppList = [select Id, Pricebook2Id, ProductSegment__c, ApprovalStatus_D__c, CurrencyIsoCode, Is_Decided__c, Machine_Parts__c, SalesChannel__c, IE_Discount_Normal__c, IE_Discount_Special__c, IE_Custom_Price__c, IE_ShipmentTerm__c, IE_Shipment_Term2__c, IE_Payment_terms__c, IE_Warranty__c, Dealer__r.Dealer_Rank__c,
+                                     IE_Subtotal__c, IE_Discount_final__c, Amount, Quote_TotalPrice__c, Payment_terms__c, IE_ShippingHandling__c, IE_local_cost__c, Subuse__c, IE_dealer_profit__c, IE_dealer_profit_percent__c, Dealer__c,
+                                     DealerId__c, Quote_CustomPrice__c, SyncedQuote_Id__c,Trade_Type_D__c 
+                                     from Opportunity where Id = :oppId];
+        if (oppList.size() > 0) {
+            //specialDealer = oppList[0].DealerId__c
+            //specialDealer = StaticParameter.specialDealerMap.containsKey(oppList[0].DealerId__c);
+            specialDealer = IfspecialDealer(oppList[0].DealerId__c);
+            specialDealer_NotisProductModel_Amountcheck = false;
+            opp = oppList[0];
+            pricebook2Id = opp.pricebook2Id;
+            currencyIsoCode = opp.currencyIsoCode;
+            if (opp.Machine_Parts__c == 'Parts' && opp.SalesChannel__c == 'direct') {
+                is_Parts_direct = true;
+            }
+            if (String.isBlank(opp.Dealer__c) && opp.SalesChannel__c == 'direct') {
+                is_IE_direct = true;
+            }
+            if (opp.IE_Warranty__c == null || opp.IE_Warranty__c == 0) {
+                opp.IE_Warranty__c = 1;
+            }
+            if (opp.SyncedQuote_Id__c == null || opp.SyncedQuote_Id__c == '') {
+                hasQuote = false;
+            } else {
+                hasQuote = true;
+            }
+        }
+    }
+
+    public OpportunityProductController(ApexPages.StandardController controller) {
+        Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+        oppId = controller.getRecord().Id;
+        is_IE_direct = false;
+        is_Parts_direct = false;
+        specialDealer = false;
+        specialDealer_NotisProductModel_Amountcheck = false;
+        List<Opportunity> oppList = [select Id, RecordTypeId, Pricebook2Id, ProductSegment__c, ApprovalStatus_D__c, CurrencyIsoCode, Is_Decided__c, Machine_Parts__c, SalesChannel__c, IE_Discount_Normal__c, IE_Discount_Special__c, IE_Custom_Price__c, IE_ShipmentTerm__c, IE_Shipment_Term2__c, IE_Payment_terms__c, IE_Warranty__c, Dealer__r.Dealer_Rank__c,
+                                     IE_Subtotal__c, IE_Discount_final__c, Amount, Quote_TotalPrice__c, Payment_terms__c, IE_ShippingHandling__c, IE_local_cost__c, Subuse__c, IE_dealer_profit__c, IE_dealer_profit_percent__c, Dealer_Code__c, Province__c, Dealer_Rank__c, Dealer__c, Account.MarketVerticals__c,
+                                     DealerId__c, Quote_CustomPrice__c, SyncedQuote_Id__c, OrderIsChange__c,Trade_Type_D__c 
+                                     from Opportunity where Id = :oppId];
+        if (oppList.size() > 0) {
+            //specialDealer = StaticParameter.specialDealerMap.containsKey(oppList[0].DealerId__c);
+            specialDealer = IfspecialDealer(oppList[0].DealerId__c);
+            opp = oppList[0];
+            pricebook2Id = opp.pricebook2Id;
+            currencyIsoCode = opp.currencyIsoCode;
+            if (opp.Machine_Parts__c == 'Parts' && opp.SalesChannel__c == 'direct') {
+                is_Parts_direct = true;
+            }
+            if (String.isBlank(opp.Dealer__c) && opp.SalesChannel__c == 'direct') {
+                is_IE_direct = true;
+            }
+            if (opp.IE_Warranty__c == null || opp.IE_Warranty__c == 0) {
+                opp.IE_Warranty__c = 1;
+            }
+            if (opp.SyncedQuote_Id__c == null || opp.SyncedQuote_Id__c == '') {
+                hasQuote = false;
+            } else {
+                hasQuote = true;
+            }
+        }
+    }
+
+    public PageReference init() {
+
+        initStringConcatenation = '';
+        saveStringConcatenation = '';
+        verifyProductValidFlag = false;
+        is_hidden_user = false;
+        // String profileid = UserInfo.getProfileId();
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        
+        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {//} || profileId.substring(0, 15) == System.Label.SystemAdmin) {
+            is_hidden_user = true;
+        }
+        is_dealer_user = false;
+        if (UserInfo.getUserType() == 'PowerPartner' || UserInfo.getUserId().substring(0, 15) == '00528000006hJeB') {
+            is_dealer_user = true;
+        }
+
+        saveBtnDisabled = false;
+        refresh = false;
+        if (opp != null && opp.ApprovalStatus_D__c == 'Submit') {
+            saveBtnDisabled = true;
+        }
+        if (opp != null && opp.Is_Decided__c == true) {
+            saveBtnDisabled = true;
+        }
+        String opentype = System.currentPageReference().getParameters().get('opentype');
+        if (opentype == 'order') {
+            saveBtnDisabled = true;
+        }
+
+        is_hidden_all = false;
+
+        is_IE = false;
+        if (opp.ProductSegment__c == 'IE' || opp.ProductSegment__c == 'RVI' || opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI') {
+            is_IE = true;
+        }
+        is_RVI = false;
+        if (opp.ProductSegment__c == 'RVI') {
+            is_RVI = true;
+        }
+        if (opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI') {
+            is_NDT = true;
+        } else {
+            is_NDT = false;
+        }
+        specialDealer = false;
+        //specialDealer = StaticParameter.specialDealerMap.containsKey(opp.DealerId__c);
+        specialDealer = IfspecialDealer(opp.DealerId__c);
+        specialDealer_NotisProductModel_Amountcheck = false;
+        if (specialDealer) {
+            is_hidden_all = true;
+        }
+        if (opp.SyncedQuote_Id__c == null || opp.SyncedQuote_Id__c == '') {
+            hasQuote = false;
+        } else {
+            hasQuote = true;
+        }
+        /*if (is_IE == true) {
+            String dealer_rank = opp.Dealer__r.Dealer_Rank__c;
+            if (dealer_rank == 'A') {
+                dealer_coefficient = is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_A_RVI) / 100 : Decimal.valueOf(System.Label.Dealer_Rank_A) / 100;
+                dealer_coefficient.setScale(2);
+                opp.IE_Discount_Normal__c = 100 - (is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_A_RVI) : Decimal.valueOf(System.Label.Dealer_Rank_A));
+            } else if (dealer_rank == 'B') {
+                dealer_coefficient = is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_B_RVI) / 100 : Decimal.valueOf(System.Label.Dealer_Rank_B) / 100;
+                dealer_coefficient.setScale(2);
+                opp.IE_Discount_Normal__c = 100 - (is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_B_RVI) : Decimal.valueOf(System.Label.Dealer_Rank_B));
+            } else if (dealer_rank == 'C') {
+                dealer_coefficient = is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_C_RVI) / 100 : Decimal.valueOf(System.Label.Dealer_Rank_C) / 100;
+                dealer_coefficient.setScale(2);
+                opp.IE_Discount_Normal__c = 100 - (is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_C_RVI) : Decimal.valueOf(System.Label.Dealer_Rank_C));
+            } else if (dealer_rank == 'D') {
+                dealer_coefficient = is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_D_RVI) / 100 : 1;
+                dealer_coefficient.setScale(2);
+                opp.IE_Discount_Normal__c = 100 - (is_RVI ? Decimal.valueOf(System.Label.Dealer_Rank_D_RVI) : 100);
+            } else {
+                dealer_coefficient = 1;
+                dealer_coefficient.setScale(2);
+                opp.IE_Discount_Normal__c = 0;
+            }
+        }*/
+
+        Map<String, Decimal> ddMap = new Map<String, Decimal>();
+        String key1 = '';
+        String key2 = '';
+        List<Dealer_Discount__c> ddList = [select id, Product_Segment__c, DimensionField1__c, DimensionField2__c, DimensionValue1__c, DimensionValue2__c, Dealer_Rank__c, Dealer_Rank_F__c from Dealer_Discount__c where Product_Segment__c = :opp.ProductSegment__c];
+        for (Dealer_Discount__c dd : ddList) {
+            ddMap.put(dd.DimensionValue1__c + '|' + dd.DimensionValue2__c, dd.Dealer_Rank_F__c);
+            key1 = dd.DimensionField1__c == null ? '' : dd.DimensionField1__c;
+            key2 = dd.DimensionField2__c == null ? '' : dd.DimensionField2__c;
+
+        }
+
+        String keyF = ''; // ((key1 == '' || opp.get(key1) == null) ? 'null' : opp.get(key1)) + '|' + ((key2 == '' || opp.get(key2) == null) ? 'null' : opp.get(key2));
+        if (opp.ProductSegment__c == 'RVI') {
+            keyF = ((key1 == '' || opp.get(key1) == null) ? 'null' : opp.get(key1)) + '|' + ((key2 == '' || opp.get(key2) == null) ? 'null' : opp.get(key2));
+        } else {
+            keyF = ((key1 == '' || opp.get(key1) == null) ? 'null' : opp.get(key1)) + '|' + ((key2 == '' || opp.get(key2) == null) ? 'null' : opp.get(key2));
+        }
+        system.debug(opp.get('Dealer__c'));
+        System.debug(keyF);
+        System.debug(ddMap.get(keyF));
+        if (opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI') {
+            opp.IE_Discount_Normal__c = 100 - (ddMap.get(keyF) == null ? 100.0 : (ddMap.get(keyF) > 100.0 ? 100.0 : ddMap.get(keyF))) ;
+
+        } else {
+            opp.IE_Discount_Normal__c = 100 - (ddMap.get(keyF) == null ? 100.0 : ddMap.get(keyF));
+        }
+
+        if (opp.ProductSegment__c == 'BS') {
+            dealer_coefficient = opp.IE_Discount_Normal__c;
+        } else if (opp.ProductSegment__c == 'IE' || opp.ProductSegment__c == 'RVI') {
+            dealer_coefficient = (ddMap.get(keyF) == null ? 100.0 : ddMap.get(keyF)) / 100;
+        } else {
+            dealer_coefficient = (ddMap.get(keyF) == null ? 100.0 : (ddMap.get(keyF) > 100.0 ? 100.0 : ddMap.get(keyF))) / 100;
+        }
+        system.debug('=====ddMap:' + ddMap);
+        system.debug('=====keyF:' + keyF);
+        system.debug('=====IE_Discount_Normal__c:' + opp.IE_Discount_Normal__c);
+        dealer_discount = (opp.IE_Discount_Normal__c == null ? 0 : opp.IE_Discount_Normal__c) + (opp.IE_Discount_Special__c == null ? 0 : opp.IE_Discount_Special__c);
+
+        maxLine = Integer.valueOf(System.Label.MaxLine);
+        Integer rownum = 0;
+        OPInfoList = new List<OpportunityProduceInfo>();
+        if (oppId != null && oppId.length() > 0) {
+            List<OpportunityLineItem> oliList = [select Id, Discount, Quantity, Product2Id, PricebookEntryId, PricebookEntry.Product2Id, Product_Search__c,
+                                                 Product_Search__r.Name, Product_Search__r.Product__c, QuantityD__c, UnitPriceD__c,
+                                                 IsNew__c, IsDelete__c, DescriptionD__c, PricebookEntry.SalesPrice__c, Product_Search__r.ProductModels1__c, PricebookEntry.Hidden_flag__c,
+                                                 Product_Search__r.ProductCode__c, Product_Search__r.Product_ECCode__c
+                                                 from OpportunityLineItem
+                                                 where OpportunityId = :oppId
+                                                         order by Id];
+            initStringConcatenation = opp.IE_Discount_Special__c + '|';
+            for (OpportunityLineItem oli : oliList) {
+                rownum += 1;
+                if (specialDealer) {
+                    OpportunityProduceInfo opi = new OpportunityProduceInfo(rownum, oli, specialDealer);
+
+                    //if ( specialDealer || (is_dealer_user == true && opi.hiddenflg == true)) {
+                    if ( specialDealer || (is_dealer_user == true && opi.hiddenflg == true)) {
+                        system.debug('opi.isProductModel--->1' + opi.isProductModel);
+                        //opi.oli.UnitPriceD__c = 0;
+                        if (opi.isProductModel) {
+
+                        } else {
+                            opi.oli.UnitPriceD__c = 0;
+                        }
+                        is_hidden_all = true;
+                    }
+                    OPInfoList.add(opi);
+                } else {
+                    OpportunityProduceInfo opi = new OpportunityProduceInfo(rownum, oli);
+
+                    //if ( specialDealer || (is_dealer_user == true && opi.hiddenflg == true)) {
+                    if (is_dealer_user == true && opi.hiddenflg == true) {
+
+                        //opi.oli.UnitPriceD__c = 0;
+                        if (opi.isProductModel) {
+
+                        } else {
+                            opi.oli.UnitPriceD__c = 0;
+                        }
+                        is_hidden_all = true;
+                    }
+                    OPInfoList.add(opi);
+                }
+
+                if (opp.OrderIsChange__c) {
+                    String productCode = oli.Product_Search__r.ProductCode__c;
+                    if (String.isNotBlank(productCode)) {
+
+                        initStringConcatenation += productCode + '|' + oli.Quantity;
+                    }
+
+                }
+                //OpportunityProduceInfo opi = new OpportunityProduceInfo(rownum, oli);
+                //if ( specialDealer || (is_dealer_user == true && opi.hiddenflg == true)) {
+                //    //opi.oli.UnitPriceD__c = 0;
+                //    if(specialDealer && opi.isProductModel){
+
+                //    }else{
+                //        opi.oli.UnitPriceD__c = 0;
+                //    }
+                //    is_hidden_all = true;
+                //}
+                //OPInfoList.add(opi);
+            }
+            system.debug('initStringConcatenation--->' + initStringConcatenation);
+            for (OpportunityProduceInfo opinfo : OPInfoList) {
+                if (opInfo.discount != null && opInfo.discount != 0) {
+                    Decimal ie_discount_n = opp.IE_Discount_Normal__c == null ? 0.00 : opp.IE_Discount_Normal__c;
+                    Decimal tmp_discount = ie_discount_n == 100 ? 0 : (opInfo.discount - ie_discount_n) / (100 - ie_discount_n) * 100;
+                    opinfo.discount = tmp_discount.setScale(2, System.RoundingMode.HALF_UP);
+                    if (is_IE == true) {
+                        opinfo.discount = opp.IE_Discount_Special__c;
+                    } else {
+                        Decimal discount_o = opinfo.oli.discount == null ? 0 : opinfo.oli.discount;
+                        opinfo.discount = discount_o;//(discount_o - ie_discount_n) / (1 - ie_discount_n / 100);
+                        opinfo.discount = opinfo.discount.setScale(2, System.RoundingMode.HALF_UP);
+                    }
+                } else {
+                    opinfo.discount = 0.0;
+                }
+            }
+        }
+        //rownum += 1;
+        //OpportunityProduceInfo opi= new OpportunityProduceInfo(rownum);
+        //OPInfoList.add(opi);
+
+        if (rownum < maxLine) {
+            for (Integer i = rownum; i < maxLine; i++) {
+                if (specialDealer) {
+                    //if (rownum != OPInfoList.size()) {
+                    //    String oliId = OPInfoList[i].oli.id;
+                    //    String pName = OPInfoList[i].productName;
+                    //    String pId = OPInfoList[i].productId;
+                    //    Boolean isProductModel = OPInfoList[i].isProductModel;
+                    //    if (pName != null && pName.length() > 0 && pId != null && pId.length() > 0) {
+                    //        if (oliId != null && oliId.length() > 0 && isProductModel) {
+                    //            OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1,specialDealer);
+                    //            OPInfoList.add(opi);
+                    //        } else {
+                    //            OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1);
+                    //            OPInfoList.add(opi);
+                    //        }
+                    //    }
+                    //} else {
+                    //    OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1);
+                    //    OPInfoList.add(opi);
+                    //}
+                    OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1, specialDealer);
+                    //OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1);
+                    OPInfoList.add(opi);
+
+                } else {
+                    OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1);
+                    OPInfoList.add(opi);
+                }
+                //OpportunityProduceInfo opi = new OpportunityProduceInfo(i + 1);
+                //OPInfoList.add(opi);
+            }
+        }
+
+        return null;
+    }
+
+    public PageReference addLine() {
+        system.debug('=====before add size:' + OPInfoList.size());
+        Integer nowLine = getOPInfoListSize();
+        OpportunityProduceInfo newopi = new OpportunityProduceInfo(nowLine + 1);
+
+        List<OpportunityProduceInfo> temp = new List<OpportunityProduceInfo>();
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            temp.add(opi);
+        }
+        temp.add(newopi);
+        OPInfoList = temp.clone();
+        system.debug('=====after add size:' + OPInfoList.size());
+
+        return null;
+    }
+
+    public PageReference deleteLine() {
+        system.debug('=====before del size:' + OPInfoList.size());
+        Integer rownum = 0;
+        List<OpportunityProduceInfo> temp = new List<OpportunityProduceInfo>();
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            if (opi.lineNo != lineNo) {
+                rownum += 1;
+                OpportunityProduceInfo tmp = new OpportunityProduceInfo(rownum, opi.oli);
+                if ( specialDealer || (is_dealer_user == true && tmp.hiddenflg == true)) {
+                    tmp.oli.UnitPriceD__c = 0;
+                    //if(specialDealer && opi.isProductModel){
+
+                    //}else{
+                    //    opi.oli.UnitPriceD__c = 0;
+                    //}
+                    is_hidden_all = true;
+                }
+                temp.add(tmp);
+            }
+        }
+        OPInfoList = temp.clone();
+        system.debug('=====after del size:' + OPInfoList.size());
+
+        return null;
+    }
+
+    public PageReference saveLine() {
+        specialDealer_NotisProductModel_Amountcheck = false;
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            system.debug( ' opi.oli.UnitPriceD__c--->' + opi.oli.UnitPriceD__c);
+        }
+        system.debug('OPInfoList--->' + OPInfoList);
+        system.debug('=====is_hidden_all11111:' + is_hidden_all);
+        List<PricebookEntry> pbeList = [select Id, Product2Id, Pricebook2Id from PricebookEntry where Pricebook2Id = :opp.Pricebook2Id and CurrencyIsoCode = :opp.CurrencyIsoCode];
+        Map<String, String> pbeMap = new Map<String, String>();
+        for (PricebookEntry pbe : pbeList) {
+            pbeMap.put(pbe.Product2Id, pbe.Id);
+        }
+        system.debug('pbeMap--->' + pbeMap);
+        errorFlag = false;
+
+        if (is_IE && (opp.IE_Custom_Price__c == null || opp.IE_Custom_Price__c == 0)) {
+            opp.IE_Custom_Price__c.addError('璇疯緭鍏ュ鎴蜂环鏍笺��');
+            errorFlag = true;
+        }
+        //澶栬锤璇环浼樺寲2021-05-28 start
+        if (is_IE && opp.IE_ShipmentTerm__c == null && opp.Trade_Type_D__c =='Tax Exemption') {
+            opp.IE_ShipmentTerm__c.addError('璇烽�夋嫨鍥介檯璐告槗鏉′欢銆�');
+            errorFlag = true;
+        }
+        if (is_IE && opp.IE_Shipment_Term2__c == null && opp.Trade_Type_D__c =='Tax Exemption') {
+            opp.IE_Shipment_Term2__c.addError('璇烽�夋嫨鍥介檯璐告槗鏉′欢2銆�');
+            errorFlag = true;
+        }
+        if (is_NDT == false && is_IE == true && opp.Payment_terms__c == null) {
+            opp.Payment_terms__c.addError('璇烽�夋嫨浠樻鏉′欢銆�');
+            errorFlag = true;
+        }
+        if (is_NDT && opp.IE_Payment_terms__c == null) {
+            opp.IE_Payment_terms__c.addError('璇烽�夋嫨浠樻鏉′欢銆�');
+            errorFlag = true;
+        }
+        //澶栬锤璇环浼樺寲2021-05-28 end
+
+
+        Map<String, String> keepIdMap = new Map<String, String>();
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            String pName = opi.productName;
+            String pId = opi.productId;
+            if (pName != null && pName.length() > 0 && pId != null && pId.length() > 0) {
+                if (pbeMap.containsKey(pId) == false) {
+                    opi.oli.Product_Search__c.addError('閫夋嫨浜у搧涓庤浠蜂骇鍝佸垎绫讳笉鍖归厤銆�');
+                    errorFlag = true;
+
+                }
+                if (opi.oli.QuantityD__c == null || opi.oli.QuantityD__c == 0) {
+                    opi.oli.QuantityD__c.addError('璇疯緭鍏ユ暟閲忋��');
+                    errorFlag = true;
+                }
+                if (specialDealer == false && is_hidden_all == false && is_hidden_user == false && opi.hiddenflg == false && (opi.oli.UnitPriceD__c == null || opi.oli.UnitPriceD__c == 0)) {
+                    //if (opi.oli.UnitPriceD__c == null || opi.oli.UnitPriceD__c == 0) {
+                    opi.oli.UnitPriceD__c.addError('璇疯緭鍏ュ崟浠枫��');
+                    errorFlag = true;
+
+                }
+
+                String oliId = opi.oli.id;
+                keepIdMap.put(oliId, oliId);
+            }
+        }
+        /*String dealerId = opp.Dealer__c;
+        dealerId = dealerId.subString(0,dealerId.length()-3);*/
+        if (errorFlag == true /*&& dealerId != '0012800000DUL3i' && dealerId != '0012800000etOTu'*/ ) {
+            return null;
+        }
+
+        List<OpportunityLineItem> upsertList = new List<OpportunityLineItem>();
+        List<OpportunityLineItem> deleteList = new List<OpportunityLineItem>();
+
+        Map<String, Decimal> productIdQuantityMap = new  Map<String, Decimal>();
+
+
+
+        List<OpportunityLineItem> nowOli = [select id from OpportunityLineItem where OpportunityId = :oppId and IsNew__c = true];
+        for (OpportunityLineItem oli : nowOli) {
+            if (keepIdMap.containsKey(oli.id) == false) {
+                deleteList.add(oli);
+            }
+        }
+
+        List<String> pList = new List<String>();
+        saveStringConcatenation = opp.IE_Discount_Special__c + '|';
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            String oliId = opi.oli.id;
+            String pName = opi.productName;
+            String pId = opi.productId;
+            if (pName != null && pName.length() > 0 && pId != null && pId.length() > 0) {
+                pList.add(pId);
+            }
+
+            if (opp.OrderIsChange__c) {
+                // stringConcatenation = opp.IE_Discount_Special__c + '|';
+                // String saveStringConcatenation = '';
+                String productCode = opi.oli.Product_Search__r.ProductCode__c;
+                if (String.isNotBlank(productCode)) {
+
+                    // stringConcatenation += RadiationUtil.getStringConcatenation(productCode,oli.Quantity);
+                    saveStringConcatenation += productCode + '|' + opi.oli.QuantityD__c;
+                }
+
+            }
+        }
+        List<Product_Search__c> psList = new List<Product_Search__c>();
+        psList = [select id, Product__c from Product_Search__c where Product__c = :pList];
+        Map<String, String> psMap = new Map<String, String>();
+        for (Product_Search__c ps : psList) {
+            psMap.put(ps.Product__c, ps.Id);
+        }
+
+        Decimal discount_n = opp.IE_Discount_Normal__c == null ? 0.0 : opp.IE_Discount_Normal__c;
+        //Decimal subtotal = 0.00;
+        //Decimal totalprice = 0.00;
+        Decimal discount_sp = opp.IE_Discount_Special__c == null ? 0.0 : opp.IE_Discount_Special__c;
+
+        List<String> pidList = new List<String>();
+        Decimal specialdiscount = 0.00;
+
+        if (specialDealer) {
+            specialdiscount = Specialdiscount(OPInfoList, opp);
+
+            if (specialDealer_NotisProductModel_Amountcheck) {
+                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鎬讳环瀛楁蹇呭~'));
+                return null;
+            }
+            if (specialdiscount == -1) {
+                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鎶樻墸 蹇呴』鍦� 0 鍒� 100 涔嬮棿'));
+                return null;
+            }
+        }
+        if (opp.OrderIsChange__c) {
+            if (initStringConcatenation != saveStringConcatenation) {
+                verifyProductValidFlag = true;
+            }
+        }
+
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            String oliId = opi.oli.id;
+            String pName = opi.productName;
+            String pId = opi.productId;
+
+            if (opi.oli.IsDelete__c == true) {
+                deleteList.add(opi.oli);
+            } else if (pName != null && pName.length() > 0 && pId != null && pId.length() > 0) {
+                if (oliId != null && oliId.length() > 0) {
+                    opi.oli.Product_Search__c = psMap.get(pId);
+                    //if (opp.ProductSegment__c == 'BS' || opp.ProductSegment__c == 'IE') {
+                    opi.oli.Quantity = opi.oli.QuantityD__c;
+                    if (is_hidden_all == true || is_dealer_user == true && opi.hiddenflg == true) {
+                        //opi.oli.UnitPriceD__c = opi.salesPrice;
+                        system.debug('opi.isProductModel--->3' + opi.isProductModel);
+                        if (specialDealer && opi.isProductModel) {
+
+                        } else {
+                            opi.oli.UnitPriceD__c = opi.salesPrice;
+                        }
+                    }
+                    if (opi.isProductModel == true) {
+                        system.debug('11111111111111111');
+                        opi.oli.UnitPrice = opi.oli.UnitPriceD__c;
+                    } else {
+                        system.debug('222222222222222222');
+                        system.debug(opi.test);
+                        opi.oli.UnitPrice = opi.salesPrice;
+                        opi.oli.UnitPriceD__c = opi.salesPrice;
+                    }
+                    opi.oli.Description = opi.oli.DescriptionD__c;
+                    opi.oli.IsNew__c = false;
+                    if (is_IE) {
+                        //opi.discount = opi.discount == null ? 0.0 : opi.discount;
+                        //opi.oli.Discount = discount_n + (100 - discount_n) / 100 * opi.discount;
+                        Decimal discount = discount_n + (100 - discount_n) / 100 * discount_sp;
+                        opi.oli.Discount = discount.setScale(2, System.RoundingMode.HALF_UP);
+                    } else {
+                        if (specialDealer) {
+                            opi.oli.Discount = specialdiscount;
+                        } else {
+                            opi.oli.Discount = opi.discount;
+                        }
+                        //opi.oli.Discount = opi.discount;
+                        //opi.oli.Discount = discount_n + (100 - discount_n) * opi.discount / 100;
+                    }
+                    opi.oli.oppLiVerifyProductValid__c = verifyProductValidFlag;
+
+                    upsertList.add(opi.oli);
+                    pidList.add(pId);
+                    //subtotal += opi.oli.Quantity * opi.oli.UnitPrice;
+                    //totalprice += opi.oli.Quantity * opi.oli.UnitPrice * (100 - opi.oli.Discount) / 100;
+                } else {
+
+                    //if (opp.ProductSegment__c == 'BS' || opp.ProductSegment__c == 'IE') {
+                    opi.oli.PricebookEntryId = pbeMap.get(pId);
+                    opi.oli.Quantity = opi.oli.QuantityD__c;
+                    if (is_hidden_all == true || is_dealer_user == true && opi.hiddenflg == true) {
+                        system.debug('opi.isProductMode---->4' + opi.isProductModel);
+                        //if(specialDealer && opi.isProductModel){
+                        if (specialDealer ) {
+
+
+                        } else {
+                            //opi.oli.UnitPriceD__c = opi.salesPrice;
+                        }
+                    }
+                    if (opi.isProductModel == true) {
+                        system.debug('11111111111111111');
+                        opi.oli.UnitPrice = opi.oli.UnitPriceD__c;
+                    } else {
+                        system.debug('222222222222222222');
+                        system.debug(opi.test);
+                        opi.oli.UnitPrice = opi.salesPrice;
+                        opi.oli.UnitPriceD__c = opi.salesPrice;
+                    }
+                    opi.oli.Description = opi.oli.DescriptionD__c;
+                    opi.oli.IsNew__c = false;
+                    if (is_IE) {
+                        //opi.discount = opi.discount == null ? 0.0 : opi.discount;
+                        //opi.oli.Discount = discount_n + (100 - discount_n) / 100 * opi.discount;
+                        Decimal discount = discount_n + (100 - discount_n) / 100 * discount_sp;
+                        opi.oli.Discount = discount.setScale(2, System.RoundingMode.HALF_UP);
+                    } else {
+                        if (specialDealer) {
+                            opi.oli.Discount = specialdiscount;
+                        } else {
+                            opi.oli.Discount = opi.discount;
+                        }
+                        //opi.oli.Discount = opi.discount;
+
+                        //opi.oli.Discount = discount_n + (100 - discount_n) * opi.discount / 100;
+                    }
+                    //opi.oli.OLISingleProduct__c = true;
+                    //}
+                    OpportunityLineItem newoli = opi.oli.clone();
+                    newoli.OpportunityId = oppId;
+                    newoli.Product_Search__c = psMap.get(pId);
+                    //XHL-20190513-AddStart
+                    newoli.OLISingleProduct__c = true;
+                    //XHL-20190513-AddEnd
+                    system.debug('12345');
+                    system.debug('newoli.UnitPriceD__c----->' + newoli.UnitPriceD__c);
+
+                    upsertList.add(newoli);
+                    pidList.add(pId);
+                    //subtotal += opi.oli.Quantity * opi.oli.UnitPrice;
+                    //totalprice += opi.oli.Quantity * opi.oli.UnitPrice * (100 - opi.oli.Discount) / 100;
+                }
+
+                // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 Start
+                Decimal quantity = opi.oli.QuantityD__c;
+                if (productIdQuantityMap.containsKey(pId)) {
+                    quantity += productIdQuantityMap.get(pId);
+                }
+                productIdQuantityMap.put(pId, quantity);
+                // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 End
+            }
+        }
+//system.debug('=====subtotal:' + subtotal);
+//system.debug('=====totalprice:' + totalprice);
+        opp.IE_Discount_Normal__c = opp.IE_Discount_Normal__c == null ? 0.0 : opp.IE_Discount_Normal__c;
+        //discount_sp = (subtotal == 0 || opp.IE_Discount_Normal__c == 100) ? 0 : ((1 - totalprice / subtotal) * 100 - opp.IE_Discount_Normal__c) / (100 - opp.IE_Discount_Normal__c) * 100;
+        //discount_sp = discount_sp.setScale(2, System.RoundingMode.HALF_UP);
+//system.debug('=====discount_sp:' + discount_sp);
+
+        Opportunity saveOpp = new Opportunity();
+        saveOpp.Id = opp.Id;
+        saveOpp.IE_Discount_Normal__c = discount_n;
+        saveOpp.IE_Discount_Special__c = discount_sp;
+        saveOpp.IE_Custom_Price__c = opp.IE_Custom_Price__c;
+        saveOpp.IE_ShipmentTerm__c = opp.IE_ShipmentTerm__c;
+        saveOpp.IE_Shipment_Term2__c = opp.IE_Shipment_Term2__c;
+        saveOpp.IE_Payment_terms__c = opp.IE_Payment_terms__c;
+        saveOpp.IE_Warranty__c = opp.IE_Warranty__c;
+        saveOpp.IE_ShippingHandling__c = opp.IE_ShippingHandling__c;
+        saveOpp.IE_local_cost__c = opp.IE_local_cost__c;
+        system.debug('ndt' + is_NDT);
+        if (is_NDT) {
+            saveOpp.Quote_PaymentTerms_Text__c = paymentTermsMap.get(opp.IE_Payment_terms__c);
+        } else {
+            saveOpp.IE_Payment_terms__c = opp.Payment_terms__c;
+            saveOpp.Quote_PaymentTerms_Text__c = paymentTermsMap.get(opp.Payment_terms__c);
+            saveOpp.Payment_terms__c = opp.Payment_terms__c;
+        }
+        // if (opp.OrderIsChange__c) {
+        //     system.debug('saveStringConcatenation--->' +saveStringConcatenation);
+        //     system.debug('initStringConcatenation--->' +initStringConcatenation);
+        //     if (initStringConcatenation != saveStringConcatenation) {
+        saveOpp.VerifyProductValid__c = verifyProductValidFlag;
+        //     }
+        // }
+
+        saveOpp.Amount = opp.Amount;
+
+        system.debug('saveOpp.Amount---->' + saveOpp.Amount);
+        system.debug('opp.Amount---->' + opp.Amount);
+        system.debug('upsertList---->' + upsertList);
+
+        System.debug(pidList);
+        if (pidList.size() > 0 && opp.RecordTypeId == System.Label.SSBD_Replacement) {
+            List<Product2> p1List = new List<Product2>();
+            p1List = [select id from Product2 where isMain__c = true and id in :pidList];
+            System.debug('@@@@@@@@@@@' + p1List);
+            if (p1List.size() > 0) {
+                //opp.addError('鍖呭惈闈為浂閰嶄欢浜у搧锛岃妫�鏌ヤ骇鍝佸唴瀹�');
+                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '鍖呭惈闈為浂閰嶄欢浜у搧锛岃妫�鏌ヤ骇鍝佸唴瀹�'));
+                return null;
+            }
+        }
+
+        if (upsertList.size() > 0) {
+
+            // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 Start
+            if (productIdQuantityMap.size() > 0) {
+                
+                String productSegment = opp.ProductSegment__c == 'BS' ? 'LS' : opp.ProductSegment__c;
+                String FGSPStr = 'Machine'.equals(opp.Machine_Parts__c) ? 'FG' : 'SP';
+                Map<String, Decimal> productQuantityMap = new  Map<String, Decimal>();
+
+                List<Product2> getProductList = [SELECT Id, Name, ProductCode, NMPAStatus__c, ProductStatusFormula__c FROM Product2 WHERE Id IN:productIdQuantityMap.keySet() AND NMPAStatus__c = '鍋滀骇' AND ProductStatusFormula__c = '1'];
+
+                for (Product2 pro : getProductList) {
+                    String productCode = pro.ProductCode.trim();
+                    Decimal productQuantity = productIdQuantityMap.get(pro.Id);
+                    String key = productCode + '_' + productSegment + '_' + FGSPStr;
+                    if (productQuantityMap.containsKey(key)) {
+                        productQuantity += productQuantityMap.get(key); 
+                    }
+                    system.debug('Key---->'+key);
+                    system.debug('value---->'+productQuantity);
+
+                    productQuantityMap.put(key, productQuantity);
+                }
+
+                String result = OrderWebService.ProductInventoryCheck(productQuantityMap);
+                if (result != '1') {
+                    saveOpp.ProductInventoryCheck__c = result;
+                }
+            }
+            // 浜у搧棣栬惀鐘舵�乑5(鍋滀骇) ---XHL 2021/02/07 End
+
+
+            upsert upsertList;
+        }
+        if (deleteList.size() > 0) {
+            delete deleteList;
+        }
+
+        update saveOpp;
+        system.debug('saveOpp.Amount2---->' + saveOpp.Amount);
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            if (specialDealer || (is_dealer_user == true && opi.hiddenflg == true)) {
+                //opi.oli.UnitPriceD__c = 0;
+                //if(specialDealer && opi.isProductModel){
+                system.debug('opi.isProductModel--->6' + opi.isProductModel);
+                if (specialDealer) {
+
+                } else {
+                    opi.oli.UnitPriceD__c = 0;
+                }
+                is_hidden_all = true;
+            }
+        }
+
+        refresh = true;
+
+        return null;
+    }
+
+    public PageReference reloadPage() {
+        system.debug('=====reloadPage,is_hidden_all:' + is_hidden_all);
+
+        return null;
+    }
+
+    public PageReference csvRead() {
+        String strFile = '';
+        List<String> listFile = new List<String>();
+        errorFlag = false;
+        errormessage = null;
+        try {
+            if (contentFile != null) {
+                strFile = contentFile.toString();
+                listFile = strFile.split('\n');
+                system.debug('=====strFile:' + strFile);
+            } else {
+                errorFlag = true;
+                errormessage = '璇诲彇鍐呭涓虹┖銆�';
+                return null;
+            }
+        } catch (Exception ex) {
+            errorFlag = true;
+            errormessage = System.Label.Error_Message02;
+            return null;
+        }
+
+        for (Integer i = 0; i < listFile.size(); i++) {
+            system.debug('=====listFile_' + i + ':' + listFile[i]);
+        }
+
+        List<String[]> arrayFile = new List<String[]>();
+        String firstline = listFile[0];
+        if (firstline.indexOf('濂楄') < 0) {
+            errorFlag = true;
+            errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭��';
+            return null;
+        } else {
+            String strReplace = '';
+            List<String> temp = strFile.split('"');
+            for (Integer i = 0; i < temp.size(); i++) {
+                if (math.mod(i, 2) == 1) {
+                    temp[i] = temp[i].replace(',', '#%&');
+                }
+                strReplace += temp[i];
+            }
+            system.debug('=====strReplace:' + strReplace);
+            List<String> listReplace = strReplace.split('\n');
+            for (String replace : listReplace) {
+                system.debug('=====replace:' + replace);
+                if (replace != '\r' && replace.length() > 0) {
+                    replace = replace.replace('\r', '');
+                    String[] a = replace.split(',', -1);
+                    for (Integer i = 0; i < a.size(); i++) {
+                        if (a[i].indexOf('#%&') > 0) {
+                            a[i] = a[i].replace('#%&', ',');
+                        }
+                    }
+                    if (a.size() != 5) {
+                        errorFlag = true;
+                        errormessage = '璇诲彇鍐呭鏍煎紡涓嶆纭�侺ine:' + arrayFile.size();
+                        return null;
+                    }
+                    arrayFile.add(a);
+                }
+            }
+        }
+
+        for (Integer i = 0; i < arrayFile.size(); i++) {
+            system.debug('=====arrayFile' + i + ':' + arrayFile[i]);
+        }
+
+        List<String> prdCodeList = new List<String>();
+        for (Integer i = 1; i < arrayFile.size(); i++) {
+            if (arrayFile[i] != null && arrayFile[i].size() > 1 && arrayFile[i][0] != '') {
+                if (opp.ProductSegment__c == 'BS') {
+                    errorFlag = true;
+                    errormessage = '姝ら〉闈笉鍙笂浼犱骇鍝侊紝鑻ラ渶涓婁紶璇峰墠寰�鎶ヤ环椤甸潰涓婁紶';
+                    return null;
+                }
+
+                String tmp = '00000000000' + arrayFile[i][1];
+                prdCodeList.add(tmp);
+                prdCodeList.add(arrayFile[i][1]);
+            }
+        }
+        system.debug('=====prdCodeList:' + prdCodeList);
+
+        Map<String, Product_Search__c> psMap = new Map<String, Product_Search__c>(); // key銇孭roductCode銇с仚銆�
+        List<String> forSelect = new List<String>();
+        List<Product_Search__c> psList = [
+                                             select Id, Name, ProductCode__c, Product_ECCode__c, ProductDescription__c, ProductStatus__c, Product__c, ProductModels1__c
+                                             from Product_Search__c
+                                             where ProductCode__c in :prdCodeList];
+        String errProduct = '';
+        for (Product_Search__c ps : psList) {
+            if (ps.ProductStatus__c == '0') {
+                errorFlag = true;
+                errProduct = ps.ProductCode__c + ',';
+            }
+            String pc = ps.ProductCode__c;
+            if (pc.startsWith('00000000000')) {
+                pc = pc.substring(11);
+                psMap.put(pc, ps);
+            }
+            psMap.put(ps.ProductCode__c, ps);
+            forSelect.add(ps.Product__c);
+        }
+
+        if (errorFlag == true) {
+            errProduct = errProduct.substring(0, errProduct.length() - 1);
+            errormessage = '浜у搧鐘舵�佷负鏃犳晥锛屼笉鑳戒娇鐢ㄣ�備骇鍝侊細' + errProduct;
+            return null;
+        }
+        Map<String, PricebookEntry> pbeMap = new Map<String, PricebookEntry>(); // key銇孭roductCode銇с仚銆�
+        List<PricebookEntry> pbeList = [
+                                           select Id, Product2Id, ProductCode, Product2.Product_ECCode__c, Product2.Dummy__c, CostPrice__c, SalesPrice__c, SalesPriceA__c, SalesPriceB__c, SalesPriceC__c, Hidden_flag__c
+                                           from PricebookEntry
+                                           where Pricebook2Id = :pricebook2Id
+                                                   and CurrencyIsoCode = :currencyIsoCode
+                                                           and Product2.ManualHidden__c = false
+                                                                   and Product2Id in :forSelect];
+
+        for (PricebookEntry pbe : pbeList) {
+            String pc = pbe.ProductCode;
+            if ((pbe.CostPrice__c == 0 && pbe.Product2.Dummy__c == false) || pbe.SalesPrice__c == 0) {
+                errorFlag = true;
+                errProduct += pbe.productCode + ',';
+            } else {
+                if (pc.startsWith('00000000000')) {
+                    pc = pc.substring(11);
+                    pbeMap.put(pc, pbe);
+                }
+                pbeMap.put(pbe.ProductCode, pbe);
+            }
+        }
+        if (errorFlag == true) {
+            errProduct = errProduct.substring(0, errProduct.length() - 1);
+            errormessage = '浜у搧浠锋牸淇℃伅涓嶆纭紝涓嶈兘浣跨敤銆備骇鍝侊細' + errProduct;
+            return null;
+        }
+        system.debug('=====psMap:' + psMap);
+        system.debug('=====pbeMap:' + pbeMap);
+        for (Integer i = 1; i < arrayFile.size(); i++) {
+            if (psMap.containsKey(arrayFile[i][1]) == false || pbeMap.containsKey(arrayFile[i][1]) == false) {
+                errorFlag = true;
+                errProduct += arrayFile[i][1] + ',';
+            }
+        }
+        if (errorFlag == true) {
+            errProduct = errProduct.substring(0, errProduct.length() - 1);
+            errormessage = '浜у搧浠锋牸淇℃伅涓嶆纭紝涓嶈兘浣跨敤銆備骇鍝侊細' + errProduct;
+            return null;
+        }
+
+        List<OpportunityProduceInfo> OPInfoList2 = new List<OpportunityProduceInfo>();
+        for (OpportunityProduceInfo opInfo : OPInfoList) {
+            String pName = opInfo.productName;
+            String pId = opInfo.productId;
+            if (pName != null && pName.length() > 0 && pId != null && pId.length() > 0) {
+                OPInfoList2.add(opInfo);
+            }
+        }
+        Integer no = OPInfoList2.size() + 1;
+        if (arrayFile.size() > 1) {
+            OpportunityProduceInfo c = new OpportunityProduceInfo(no);
+            is_hidden_all = false;
+            for (Integer line = 1; line < arrayFile.size(); line++) {
+                Product_Search__c ps = psMap.get(arrayFile[line][1]);
+                PricebookEntry pbe = pbeMap.get(arrayFile[line][1]);
+                system.debug('=====key:' + arrayFile[line][1]);
+                system.debug('=====ps:' + ps);
+                system.debug('=====pbe:' + pbe);
+                c = new OpportunityProduceInfo(no, new OpportunityLineItem(IsNew__c = true, QuantityD__c = Decimal.valueOf(arrayFile[line][3]), UnitPriceD__c =  pbe.SalesPrice__c), ps.Name, true, ps.Product__c, ps.ProductCode__c, ps.Product_ECCode__c, pbe.SalesPrice__c, ps.ProductModels1__c, pbe.Hidden_flag__c, Decimal.valueOf(arrayFile[line][4]));
+                if (specialDealer || (is_dealer_user == true && c.hiddenflg == true)) {
+                    c.oli.UnitPriceD__c = 0;
+                    is_hidden_all = true;
+                }
+                OPInfoList2.add(c);
+                no++;
+            }
+
+            for (integer j = no; j < maxLine; j++) {
+                c = new OpportunityProduceInfo(j);
+                OPInfoList2.add(c);
+            }
+
+        } else {
+            for (no = 0; no < maxLine; no++) {
+                OpportunityProduceInfo active_activity = new OpportunityProduceInfo(no);
+                OPInfoList2.add(active_activity);
+            }
+        }
+        OPInfoList = OPInfoList2;
+
+        return null;
+    }
+
+    public PageReference csvExport() {
+        if (fileName == null || fileName == '') {
+            errorFlag = true;
+            errormessage = '璇疯緭鍏ラ厤缃鍑烘枃浠跺悕銆�';
+            return null;
+        }
+        csv_activities = new List<OpportunityProduceInfo>();
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            String pName = opi.productName;
+            String pId = opi.productId;
+            if (pName != null && pName.length() > 0 && pId != null && pId.length() > 0) {
+                csv_activities.add(opi);
+            }
+        }
+        PageReference pr = page.OpportunityCSVExport;
+        return pr;
+    }
+
+    class OpportunityProduceInfo {
+        public Integer lineNo { get; set; }
+        public OpportunityLineItem oli { get; set; }
+        public String productName { get; set; }
+        public Boolean isNew { get; set; }
+        public String productId { get; set; }
+        public String productCode { get; set; }
+        public String productEC { get; set; }
+
+        public Decimal salesPrice { get; set; }
+        public boolean isProductModel { get; set; }
+        public boolean hiddenflg { get; set; }
+
+        public Decimal discount { get; set; }
+        public Decimal test {get; set;}
+
+        public OpportunityProduceInfo(Integer line) {
+            lineNo = line;
+            oli = new OpportunityLineItem(IsNew__c = true);
+            productName = '';
+            isNew = true;
+            productId = '';
+            productCode = '';
+            productEC = '';
+
+            salesPrice = 0;
+            isProductModel = false;
+
+            hiddenflg = false;
+
+            //discount = 0.00;
+        }
+
+        public OpportunityProduceInfo(Integer line, Boolean specialDealer) {
+            lineNo = line;
+            oli = new OpportunityLineItem(IsNew__c = true);
+            productName = '';
+            isNew = true;
+            productId = '';
+            productCode = '';
+            productEC = '';
+
+            isProductModel = true;
+            hiddenflg = false;
+
+            //discount = 0.00;
+        }
+
+        public OpportunityProduceInfo(Integer line, OpportunityLineItem lineItem) {
+            lineNo = line;
+            oli = lineItem;
+            productName = lineItem.Product_Search__r.Name;
+            isNew = lineItem.IsNew__c;
+            productId = lineItem.Product_Search__r.Product__c;
+            String pCode = lineItem.Product_Search__r.ProductCode__c;
+            productCode = pCode == null ? '' : (pCode.startsWith('0000000000') ? pCode.substring(10) : pCode);
+            productEC = lineItem.Product_Search__r.Product_ECCode__c;
+
+            salesPrice = lineItem.PricebookEntry.SalesPrice__c;
+            isProductModel = lineItem.Product_Search__r.ProductModels1__c;
+            hiddenflg = lineItem.PricebookEntry.Hidden_flag__c;
+
+            discount = lineItem.Discount;
+        }
+
+        public OpportunityProduceInfo(Integer line, OpportunityLineItem lineItem, Boolean specialDealer) {
+            lineNo = line;
+            oli = lineItem;
+            productName = lineItem.Product_Search__r.Name;
+            isNew = lineItem.IsNew__c;
+            productId = lineItem.Product_Search__r.Product__c;
+            String pCode = lineItem.Product_Search__r.ProductCode__c;
+            productCode = pCode == null ? '' : (pCode.startsWith('0000000000') ? pCode.substring(10) : pCode);
+            productEC = lineItem.Product_Search__r.Product_ECCode__c;
+            isProductModel = lineItem.Product_Search__r.ProductModels1__c;
+            hiddenflg = lineItem.PricebookEntry.Hidden_flag__c;
+            salesPrice = lineItem.PricebookEntry.SalesPrice__c;
+
+            discount = lineItem.Discount;
+        }
+
+        public OpportunityProduceInfo(Integer in_line, OpportunityLineItem in_lineItem, String in_productName, Boolean in_isNew, String in_productId, String in_productCode, String in_productEC, Decimal in_salesPrice, Boolean in_isProductModel, Boolean in_hiddenflg, Decimal in_discount) {
+            lineNo = in_line;
+            oli = in_lineItem;
+            productName = in_productName;
+            isNew = in_isNew;
+            productId = in_productId;
+            String pCode = in_productCode;
+            productCode = pCode == null ? '' : (pCode.startsWith('0000000000') ? pCode.substring(10) : pCode);
+            productEC = in_productEC;
+
+            salesPrice = in_salesPrice;
+            isProductModel = in_isProductModel;
+            hiddenflg = in_hiddenflg;
+
+            //discount = in_discount;
+        }
+    }
+    //鐗规畩浠g悊鍟嗙殑鐗规畩鎶樻墸澶勭悊(涓獕銆佷桨璇�)
+    public Decimal Specialdiscount(List<OpportunityProduceInfo> OPInfoList, Opportunity opp) {
+        Decimal discount = 0.00;
+        Decimal all_price1 = 0.00;
+        Decimal cut_rate_price = 0.00;
+        Boolean temp = false;
+        for (OpportunityProduceInfo opi : OPInfoList) {
+            String oliId = opi.oli.id;
+            String pName = opi.productName;
+            String pId = opi.productId;
+            if (opi.oli.IsDelete__c == true) {
+
+            } else if (pName != null && pName.length() > 0  && pId.length() > 0) {
+                if (opi.isProductModel == false) {
+                    all_price1 += opi.salesPrice * opi.oli.QuantityD__c;
+                } else {
+                    all_price1 += opi.oli.UnitPriceD__c * opi.oli.QuantityD__c;
+                }
+                if (!opi.isProductModel) {
+                    temp = true;
+                }
+            }
+
+        }
+        system.debug('all_price1--->' + all_price1);
+        system.debug('opp.Amount--->' + opp.Amount);
+
+        if (temp && (opp.Amount == null || opp.Amount == 0)) {
+            specialDealer_NotisProductModel_Amountcheck = true;
+        }
+        if (all_price1 > 0) {
+
+            Decimal amo = opp.Amount == null || opp.Amount == 0 ? all_price1 : opp.Amount;
+            cut_rate_price = all_price1 - amo;
+            if (cut_rate_price >= 0) {
+                discount = (all_price1 - amo) * 100 / all_price1;
+            } else {
+                discount = -1;
+            }
+
+        }
+        return discount;
+
+    }
+
+
+    public static Boolean IfspecialDealer(String oppDealerId) {
+        if (String.isBlank(oppDealerId)) {
+            return false;
+        }
+        return StaticParameter.specialDealerMap.containsKey(oppDealerId.substring(0, 15)) && UserInfo.getUserType() == 'PowerPartner';
+    }
+
+
+    @TestVisible private void testI() {
+        integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+
+
+
+
+
+
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityProductController.cls-meta.xml b/scr/classes/OpportunityProductController.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityProductController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityProductControllerTest.cls b/scr/classes/OpportunityProductControllerTest.cls
new file mode 100644
index 0000000..55b2793
--- /dev/null
+++ b/scr/classes/OpportunityProductControllerTest.cls
@@ -0,0 +1,333 @@
+@ isTest (SeeAllData = true)
+private class OpportunityProductControllerTest {
+
+
+    static testMethod void myUnitTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductStatus__c = '1';
+        product2.IsActive = true;
+        product2.ProductCode = 'product2';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductStatus__c  = '1';
+        product3.IsActive = true;
+        product3.ProductCode = 'product3';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert new Product2[] {product1,product2,product3};
+        
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        //List<Pricebook2> pris = [select Id from Pricebook2 where IsStandard  = true And isActive = true limit 1];
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+            
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        insert acc1;
+        
+        Opportunity opp1 = new Opportunity(
+            name = 'test opp1',
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            AccountId = acc1.Id,
+            StageName = 'Phase3',
+            ProductSegment__c = 'IE',
+            CurrencyIsoCode = 'CNY',
+            Pricebook2Id = pricebook.Id,
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            //CloseDate = Date.valueof('1900-01-01')
+            CloseDate = Date.today().addDays(22),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            IE_Custom_Price__c = 1000
+        );
+        insert opp1;
+        
+        // 璇环浜у搧鏂板缓test
+        PageReference page = new PageReference('/apex/OpportunityProduct?oppid=' + opp1.Id);
+        System.Test.setCurrentPage(page);
+        OpportunityProductController controller = new OpportunityProductController();
+        System.assertEquals(opp1.Id, controller.opp.id);
+        
+        controller.init();
+        //controller.addLine();
+        //controller.lineNo = 1;
+        //controller.deleteLine();
+        
+        controller.OPInfoList[0].productName = product1.Name;
+        controller.OPInfoList[0].productId = product1.Id;
+        controller.OPInfoList[0].productCode = product1.ProductCode;
+        controller.OPInfoList[0].oli.QuantityD__c = 2;
+        controller.OPInfoList[0].oli.UnitPriceD__c = 111;
+        controller.OPInfoList[0].oli.DescriptionD__c = 'test1';
+        
+        controller.OPInfoList[1].productName = product2.Name;
+        controller.OPInfoList[1].productId = product2.Id;
+        controller.OPInfoList[1].productCode = product2.ProductCode;
+        controller.OPInfoList[1].oli.QuantityD__c = 1;
+        controller.OPInfoList[1].oli.UnitPriceD__c = 200;
+        controller.OPInfoList[1].oli.DescriptionD__c = 'test2';
+
+        controller.opp.IE_Custom_Price__c = 1000;
+        
+        controller.saveLine();
+        
+        List<OpportunityLineItem> oppList = [select Id, Product2Id from OpportunityLineItem where OpportunityId = :opp1.Id order by DescriptionD__c];
+        //System.assertEquals(2, oppList.size());
+        //System.assertEquals(product1.Id, oppList[0].Product2Id);
+        //System.assertEquals(product2.Id, oppList[1].Product2Id);
+        
+        //璇环浜у搧鏇存柊test
+        controller = new OpportunityProductController(new ApexPages.StandardController(opp1));
+        controller.init();
+        controller.testI();
+        controller.OPInfoList[0].productName = product3.Name;
+        controller.OPInfoList[0].productId = product3.Id;
+        controller.OPInfoList[0].productCode = product3.ProductCode;
+        controller.OPInfoList[0].oli.QuantityD__c = 3;
+        controller.OPInfoList[0].oli.UnitPriceD__c = 111;
+        controller.OPInfoList[0].oli.DescriptionD__c = 'test3';
+
+        controller.OPInfoList[1].oli.IsDelete__c = true;
+        
+        controller.saveLine();
+        
+        List<OpportunityLineItem> oppList2 = [select Id, Product2Id, DealerSelectProduct__c from OpportunityLineItem where OpportunityId = :opp1.Id];
+        //System.assertEquals(1, oppList2.size());
+        //System.assertEquals(product3.Id, oppList2[0].Product2Id);
+    }
+
+    @isTest static void test_init2() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.ProductStatus__c  = '1';
+
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductCode = 'product2';
+        product2.Product_ECCode__c = 'product2';
+        product2.IsActive = true;
+        product2.ProductStatus__c  = '1';
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product3';
+        product3.IsActive = true;
+        product3.ProductStatus__c  = '1';
+
+        insert new Product2[] {product1, product2, product3};
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        insert new PricebookEntry[] {standardPrice1, standardPrice2, standardPrice3};
+
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY',
+            CostPrice1__c = 100,
+            EffectiveDateFrom1__c = Date.today().addDays(-1),
+            EffectiveDateTo1__c = Date.today().addDays(1),
+            SalesPrice1__c = 200,
+            EffectiveDateFrom1_sales__c = Date.today().addDays(-1),
+            EffectiveDateTo1_sales__c = Date.today().addDays(1)
+        );
+
+        PricebookEntry entry2 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY',
+            CostPrice1__c = 100,
+            EffectiveDateFrom1__c = Date.today().addDays(-1),
+            EffectiveDateTo1__c = Date.today().addDays(1),
+            SalesPrice1__c = 200,
+            EffectiveDateFrom1_sales__c = Date.today().addDays(-1),
+            EffectiveDateTo1_sales__c = Date.today().addDays(1)
+        );
+
+        PricebookEntry entry3 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY',
+            CostPrice1__c = 100,
+            EffectiveDateFrom1__c = Date.today().addDays(-1),
+            EffectiveDateTo1__c = Date.today().addDays(1),
+            SalesPrice1__c = 200,
+            EffectiveDateFrom1_sales__c = Date.today().addDays(-1),
+            EffectiveDateTo1_sales__c = Date.today().addDays(1)
+        );
+
+        insert new PricebookEntry[] {entry1, entry2, entry3};
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        PageReference page = new PageReference('/apex/OpportunityProduct?oppid=' + opp.Id);
+        System.Test.setCurrentPage(page);
+        OpportunityProductController controller = new OpportunityProductController();
+
+        controller.init();
+
+        String strblob = '"濂楄","浜у搧code","浜у搧鍚嶇О","鏁伴噺","鎶樻墸"\n"set02","product1","product1","2.00","0.00"\n';
+
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+
+        strblob = '濂楄,浜у搧code,浜у搧鍚嶇О,鏁伴噺,鎶樻墸\nset01,product1,product1,2,49\nset01,product2,product2,2,49';
+
+        controller.contentFile = Blob.valueOf(strblob);
+
+        controller.csvRead();
+        controller.testI();
+
+        controller.fileName = 'aaa';
+        controller.csvExport();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityProductControllerTest.cls-meta.xml b/scr/classes/OpportunityProductControllerTest.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityProductControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityStageProgressBarUpdate.cls b/scr/classes/OpportunityStageProgressBarUpdate.cls
new file mode 100644
index 0000000..978116c
--- /dev/null
+++ b/scr/classes/OpportunityStageProgressBarUpdate.cls
@@ -0,0 +1,14 @@
+public without sharing class OpportunityStageProgressBarUpdate {
+  
+  public static void updateProgressBar(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+    for (Opportunity newOpp : newList) {
+      Opportunity oldOpp = oldMap.get(newOpp.Id);
+            if (UserInfo.getUserType() != 'PowerPartner') {
+                if (newOpp.Cancel_Fail_Approve__c != oldOpp.Cancel_Fail_Approve__c && newOpp.Cancel_Fail_Approve__c == 'Pass') {
+                    StaticParameter.StageProgressBarUpdate = true;
+                }
+                
+            }
+    }
+  }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityStageProgressBarUpdate.cls-meta.xml b/scr/classes/OpportunityStageProgressBarUpdate.cls-meta.xml
new file mode 100644
index 0000000..8b061c8
--- /dev/null
+++ b/scr/classes/OpportunityStageProgressBarUpdate.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityStockAnswer.cls b/scr/classes/OpportunityStockAnswer.cls
new file mode 100644
index 0000000..1444bda
--- /dev/null
+++ b/scr/classes/OpportunityStockAnswer.cls
@@ -0,0 +1,23 @@
+public class OpportunityStockAnswer {
+
+    public static void SummaryStockAnswerUpdate(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
+    if (Trigger.isBefore && Trigger.isUpdate) {
+       
+                for (Opportunity newOpp : newList) {
+                     Opportunity oldOpp = oldMap.get(newOpp.Id);
+                     if (newOpp.Stock_Answer__c != oldOpp.Stock_Answer__c) {
+                        Datetime dt = Datetime.now();
+                        String temp = '';
+                        temp += '******' + dt.format() + '******\n';
+                        temp += newOpp.Stock_Answer__c;
+                        if (oldOpp.StockAnswerSummary__c != null && oldOpp.StockAnswerSummary__c.trim().length() > 0) {
+                        temp += '\n\n' + oldOpp.StockAnswerSummary__c;
+                        }
+                        newOpp.StockAnswerSummary__c = temp;
+                        
+            }
+        } 
+    
+    }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityStockAnswer.cls-meta.xml b/scr/classes/OpportunityStockAnswer.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/OpportunityStockAnswer.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityTriggerHandler.cls b/scr/classes/OpportunityTriggerHandler.cls
new file mode 100644
index 0000000..e00eca2
--- /dev/null
+++ b/scr/classes/OpportunityTriggerHandler.cls
@@ -0,0 +1,1512 @@
+public without sharing class OpportunityTriggerHandler {
+
+    public static void updateStageLimit(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
+        system.debug('=====updateStageLimit');
+        
+        //鍙湁绠$悊鍛樺拰閫氳繃鐐瑰嚮鐘舵�佹寜閽墠鑳芥洿鏂拌浠风姸鎬�
+        Opportunity old = null;
+        // String profileId = UserInfo.getProfileId().substring(0, 15);
+        //鏂扮殑鑾峰彇浜哄憳绠�妗D
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        //if (newList[0].RecordTypeId != System.Label.SSBD_Replacement && profileId != System.Label.SystemAdmin && profileId != System.Label.SystemAdmin2 && profileId != System.Label.SystemAdmin_GPI && StaticParameter.StageProgressBarUpdate == false) {
+        if (newList[0].RecordTypeId != System.Label.SSBD_Replacement 
+            && new_profileId != System.Label.SystemAdmin && new_profileId != System.Label.SystemAdmin2 && new_profileId != System.Label.SystemAdmin_GPI
+            && StaticParameter.StageProgressBarUpdate == false) {
+            for (Opportunity opp : newList) {
+                if (Trigger.isUpdate) {
+                    old = oldMap.get(opp.Id);
+                }
+                if (Trigger.isInsert && opp.StageName != 'Prospect Created') {
+                    opp.StageName.addError('鏂板缓璇环鏃讹紝璇环鐘舵�佸彧鑳戒负Prospect Created銆�');
+                }
+                if (Trigger.isUpdate && opp.StageName != old.StageName) {
+                    opp.StageName.addError('涓嶈兘鐩存帴缂栬緫鏇存柊璇环鐘舵�併��');
+                }
+            }
+        }   
+    }
+    
+    public static void autoSet(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        system.debug('=====autoSet');
+        
+        for (Opportunity opp : newList) {
+            //close浠ュ鐨勬椂鍊欙紝棰勫畾涓嬪崟鏃ヨ嚜鍔ㄦ嫹璐濆埌缁撴潫鏃ユ湡
+            if (opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost' && opp.StageName != 'Closed Cancel') {
+                if (opp.ExpectedOrderDate__c != null) {
+                    opp.CloseDate = opp.ExpectedOrderDate__c;
+                } else {
+                    opp.CloseDate = opp.NewInquiryDate__c == null ? Date.today().addMonths(6) : opp.NewInquiryDate__c.addMonths(6);
+                }
+            }
+            if (opp.ProductSegmentCompetitor__c != opp.ProductSegment__c) {
+                opp.ProductSegmentCompetitor__c = opp.ProductSegment__c;
+            }
+            if (opp.DealerNameF__c != opp.DealerNameText__c) {
+                opp.DealerNameText__c = opp.DealerNameF__c;
+            }
+
+            Opportunity oldOpp = oldMap == null ? new Opportunity() : oldMap.get(opp.Id);
+system.debug('=====' + opp.IE_Discount_Special__c      + '|' + oldOpp.IE_Discount_Special__c);
+system.debug('=====' + opp.IE_Custom_Price__c          + '|' + oldOpp.IE_Custom_Price__c);
+system.debug('=====' + opp.IE_local_cost__c            + '|' + oldOpp.IE_local_cost__c);
+system.debug('=====' + opp.IE_Subtotal__c              + '|' + oldOpp.IE_Subtotal__c);
+system.debug('=====' + opp.IE_ShippingHandling__c      + '|' + oldOpp.IE_ShippingHandling__c);
+system.debug('=====' + opp.IE_Payment_terms__c         + '|' + oldOpp.IE_Payment_terms__c);
+            String item_text = opp.OpportunityLineItem_text__c;
+            item_text = item_text == null ? '' : item_text.replace('\r', '').replace('\n', '');
+            String item_text2 = oldOpp.OpportunityLineItem_text__c;
+            item_text2 = item_text2 == null ? '' : item_text2.replace('\r', '').replace('\n', '');
+
+            String item_textot = opp.OpportunityLineItemOT_text__c;
+            item_textot = item_textot == null ? '' : item_textot.replace('\r', '').replace('\n', '');
+            String item_textot2 = oldOpp.OpportunityLineItemOT_text__c;
+            item_textot2 = item_textot2 == null ? '' : item_textot2.replace('\r', '').replace('\n', '');
+system.debug('=====' + item_text);
+system.debug('=====' + item_text2);
+            boolean changed = opp.IE_Discount_Special__c      != oldOpp.IE_Discount_Special__c      ||
+                              //opp.OpportunityLineItem_text__c != oldOpp.OpportunityLineItem_text__c ||
+                              item_textot.equals(item_textot2)    == false                              ||
+                              //item_text.equals(item_text2)    == false                              ||                            
+                              opp.IE_Custom_Price__c          != oldOpp.IE_Custom_Price__c          ||
+                              opp.IE_local_cost__c            != oldOpp.IE_local_cost__c            ||
+                              opp.IE_Subtotal__c              != oldOpp.IE_Subtotal__c              ||
+                              opp.IE_ShippingHandling__c      != oldOpp.IE_ShippingHandling__c      ||
+                              opp.IE_Payment_terms__c         != oldOpp.IE_Payment_terms__c;
+            if (changed && OrderDivisionController.OrderDivision == false) {
+                opp.SpecialPriceApproveStatus__c = 'Draft';
+                //opp.test1__c = '1111';
+                system.debug('@@@@@@autoSet');
+                System.debug(item_textot+'@@@@@@@@@@@@@@@@'+ item_textot2);
+                System.debug(item_textot.equals(item_textot2) );
+            }
+        }
+    }
+    
+    public static void setIsNew(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        system.debug('=====setIsNew');
+        
+        for (Opportunity newOpp : newList) {
+            //鐜嬮箯浼熸柊鍔犲紑濮� 鏂板缓璇环鏃舵鏌ヤ唬鐞嗗晢
+            String customerIds = System.label.CreateOppCustom;
+            if(String.isNotBlank(customerIds) && !StaticParameter.StageProgressBarUpdate){
+                List<String> customerIds_list = customerIds.split(',');
+                if(customerIds_list!=null && customerIds_list.size()!=0 && newOpp.DealerId__c != null){
+                    Boolean is_have = customerIds_list.contains(newOpp.DealerId__c.substring(0,15));
+                    if(is_have){
+                        newOpp.addError('浠g悊鍟嗕笉鍏佽鏂板缓璇环锛�');
+                    }
+                }
+            }
+            if(newOpp.DealerSelectOwner__c != null){
+                newOpp.OwnerId = newOpp.DealerSelectOwner__c;
+            }
+            //鐜嬮箯浼熸柊鍔犵粨鏉� 鏂板缓璇环鏃舵鏌ヤ唬鐞嗗晢
+            if (UserInfo.getUserType() == 'PowerPartner' && newOpp.ProductSegment__c != 'BS' && newOpp.ProductSegment__c != 'IE' && newOpp.ProductSegment__c != 'RVI' && newOpp.RecordTypeId != System.Label.RT_SSBD_Service && newOpp.RecordTypeId != System.Label.SSBD_Replacement && StaticParameter.StageProgressBarUpdate == false) {
+                newOpp.IsNew__c = true;
+                // 澶栬锤閫佽揪鏂归粯璁や负澶栬锤鍏徃
+                if (newOpp.Trade_Type_D__c == 'Tax Exemption') {
+                    newOpp.SpecialDeliveryAddress_D__c = newOpp.ForeignTradeCompany_D__c;
+                }
+            } else {
+                //newOpp.Amount_D__c = newOpp.Amount;
+                //newOpp.TotalOpportunityQuantity_D__c = newOpp.TotalOpportunityQuantity;
+                newOpp.LeadSource_D__c = newOpp.LeadSource;
+                //newOpp.CloseDate_D__c = newOpp.CloseDate;
+                //newOpp.StageName_D__c = newOpp.StageName;
+                newOpp.Budget_Amount_D__c = newOpp.BudgetAmount__c;
+                newOpp.Cancel_Reason_Text_D__c = newOpp.CancelReasonText__c;
+                newOpp.Competitor_Company_D__c = newOpp.CompetitorCompany__c;
+                newOpp.Cancel_Reason_D__c = newOpp.CancelReason__c;
+                newOpp.Competitor_Product_D__c = newOpp.Competitor_Product__c;
+                newOpp.Competitor_Product2_D__c = newOpp.Competitor_Product2__c;
+                newOpp.Competitor_Product3_D__c = newOpp.Competitor_Product3__c;
+                newOpp.Competitor_Product4_D__c = newOpp.Competitor_Product4__c;
+                newOpp.Competitor_Product5_D__c = newOpp.Competitor_Product5__c;
+                newOpp.Competitor_Product6_D__c = newOpp.Competitor_Product6__c;
+                newOpp.Competitor_Product7_D__c = newOpp.Competitor_Product7__c;
+                newOpp.Competitor_Product8_D__c = newOpp.Competitor_Product8__c;
+                newOpp.Competitor_Product_Code_D__c = newOpp.CompetitorProductCode__c;
+                newOpp.Competitor_Product_Code2_D__c = newOpp.CompetitorProductCode2__c;
+                newOpp.Competitor_Product_Code3_D__c = newOpp.CompetitorProductCode3__c;
+                newOpp.Competitor_Product_Code4_D__c = newOpp.CompetitorProductCode4__c;
+                newOpp.Competitor_Product_Code5_D__c = newOpp.CompetitorProductCode5__c;
+                newOpp.Competitor_Product_Code6_D__c = newOpp.CompetitorProductCode6__c;
+                newOpp.Competitor_Product_Code7_D__c = newOpp.CompetitorProductCode7__c;
+                newOpp.Competitor_Product_Code8_D__c = newOpp.CompetitorProductCode8__c;
+                newOpp.Dealer_Sales_Staff_Name_D__c = newOpp.DealerSalesStaffName__c;
+                newOpp.Dealer_Service_D__c = newOpp.DealerService__c;
+                newOpp.Expected_Delivery_Date_D__c = newOpp.ExpectedDeliveryDate__c;
+                newOpp.Expected_Order_Date_D__c = newOpp.ExpectedOrderDate__c;
+                newOpp.Inquiry_Result_D__c = newOpp.InquiryResult__c;
+                newOpp.Inquiry_Result_Cancel_D__c = newOpp.InquiryResultCancel__c;
+                newOpp.Inquiry_Result_Lost_D__c = newOpp.InquiryResultLost__c;
+                newOpp.Inquiry_Result_Order_D__c = newOpp.InquiryResultOrder__c;
+                newOpp.Lost_Amount_D__c = newOpp.LostAmount__c;
+                newOpp.Lost_Competitor_Product_D__c = newOpp.LostCompetitorProduct__c;
+                newOpp.LostReasonText_D__c = newOpp.LostReasonText__c;
+                newOpp.LostReason_D__c = newOpp.Lostreason__c;
+                newOpp.New_Inquiry_Date_D__c = newOpp.NewInquiryDate__c;
+                newOpp.Phase1Date_D__c = newOpp.Phase1Date__c;
+                newOpp.Phase2Date_D__c = newOpp.Phase2Date__c;
+                newOpp.Phase3Date_D__c = newOpp.Phase3Date__c;
+                newOpp.Sales_Channel_D__c = newOpp.SalesChannel__c;
+                newOpp.Sub_Dealer_D__c = newOpp.SubDealer__c;
+                newOpp.Trade_Type_D__c = newOpp.TradeType__c;
+                newOpp.Machine_Parts_D__c = newOpp.Machine_Parts__c;
+                // 澶栬锤閫佽揪鏂归粯璁や负澶栬锤鍏徃
+                if (newOpp.Trade_Type_D__c == 'Tax Exemption') {
+                    newOpp.SpecialDeliveryAddress__c = newOpp.ForeignTradeCompany__c;
+                }
+                newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
+                newOpp.ForeignTradeCompany_D__c = newOpp.ForeignTradeCompany__c;
+                newOpp.SpecialDeliveryContact_D__c = newOpp.SpecialDeliveryContact__c;
+                if (UserInfo.getUserType() != 'PowerPartner') {
+                    newOpp.DealerSelectOwner__c = newOpp.OwnerId;
+                }
+                Boolean specialDealer =  StaticParameter.specialDealerMap1.containsKey(newOpp.DealerId__c);
+                Boolean control = newOpp.IS_Control__c;
+                System.debug(newOpp.IS_Control__c);
+                /*if(control == true){
+                    newOpp.OwnerId = newOpp.DealerSelectOwner__c;
+                }*/
+                //newOpp.CrossCooperativeProject__c 璺ㄥ尯閿�鍞爣璁�
+                if(specialDealer == false && control == false && newOpp.CrossCooperativeProject__c != true){
+                    newOpp.ApprovalStatus_D__c = 'Pass';
+                }
+            }
+        }
+    }
+    
+    public static void setPriceBook(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        system.debug('=====setPriceBook');
+        
+        Map<String, String> pricebookMap1 = new Map<String, String>();
+        Map<String, String> pricebookMap2 = new Map<String, String>();
+        Boolean needUpdate = false;
+
+        for (Opportunity opp : newList) {
+            
+            Opportunity old = oldMap == null ? new Opportunity() : oldMap.get(opp.Id);
+            system.debug('opp____'+opp.Pricebook2Id);
+            system.debug('old____'+old.Pricebook2Id);
+            if (trigger.isInsert || opp.Pricebook2Id != old.Pricebook2Id || opp.ProductSegment__c != old.ProductSegment__c ||
+                opp.TradeType__c != old.TradeType__c || opp.Trade_Type_D__c != old.Trade_Type_D__c ||
+                opp.SalesChannel__c != old.SalesChannel__c || opp.Sales_Channel_D__c != old.Sales_Channel_D__c ||
+                opp.Machine_Parts__c != old.Machine_Parts__c || opp.Machine_Parts_D__c != old.Machine_Parts_D__c || opp.needUpdate__c == true) {
+
+               needUpdate = true;
+               system.debug('<---needUpdate--->'+ needUpdate);
+            } else {
+                continue;
+            }
+        }
+
+        if(needUpdate){
+            List<PriceBook2> pbeList = [select id, Name, ProductSegment__c, TradeType__c, SalesChannel__c, MachineParts__c from PriceBook2 where IsStandard = false];
+            for (PriceBook2 pbe : pbeList) {
+                pricebookMap1.put(pbe.ProductSegment__c + '-' + pbe.TradeType__c + '-' + pbe.SalesChannel__c + '-' + pbe.MachineParts__c, pbe.Id);
+                pricebookMap2.put(pbe.Name, pbe.Id);
+            }
+    system.debug('=====pricebookMap1:' + pricebookMap1);
+    system.debug('=====pricebookMap2:' + pricebookMap2);
+
+            List<String> accIds = new List<String>();
+            for (Opportunity opp : newList) {
+                accIds.add(opp.AccountId);
+            }
+            List<Account> accList = [select Id, ProductSegmentF__c from Account where Id = :accIds];
+            Map<String, String> acc2psMap = new Map<String, String>();
+            for (Account acc : accList) {
+                acc2psMap.put(acc.Id, acc.ProductSegmentF__c);
+            }
+    system.debug('=====acc2psMap:' + acc2psMap);
+            for (Opportunity opp : newList) {
+                Opportunity old = oldMap == null ? new Opportunity() : oldMap.get(opp.Id);
+                if (trigger.isInsert || opp.Pricebook2Id != old.Pricebook2Id || opp.ProductSegment__c != old.ProductSegment__c ||
+                    opp.TradeType__c != old.TradeType__c || opp.Trade_Type_D__c != old.Trade_Type_D__c ||
+                    opp.SalesChannel__c != old.SalesChannel__c || opp.Sales_Channel_D__c != old.Sales_Channel_D__c ||
+                    opp.Machine_Parts__c != old.Machine_Parts__c || opp.Machine_Parts_D__c != old.Machine_Parts_D__c || opp.needUpdate__c == true) {
+                    // 鏄鐞嗗璞�
+                } else {
+    system.debug('=====continue');
+                    continue;
+                }
+                if (opp.ProductSegment__c != acc2psMap.get(opp.AccountId)) {
+                    opp.ProductSegment__c = acc2psMap.get(opp.AccountId);
+                }
+    system.debug('=====ProductSegmentF__c:' + opp.AccountId + '|' + acc2psMap.get(opp.AccountId));
+                String pbid = '';
+                if (acc2psMap.get(opp.AccountId) == 'NDT' || acc2psMap.get(opp.AccountId) == 'ANI') {
+                    /*String key = opp.ProductSegment__c;
+                    pbid = pricebookMap2.get(key);*/
+                    String key = opp.ProductSegment__c + '-' + opp.TradeType__c + '-' + opp.SalesChannel__c + '-' + opp.Machine_Parts__c;
+                    if (opp.TradeType__c == null || opp.SalesChannel__c == null || opp.Machine_Parts__c == null) {
+                        key = opp.ProductSegment__c + '-' + opp.Trade_Type_D__c + '-' + opp.Sales_Channel_D__c + '-' + opp.Machine_Parts_D__c;
+                    }
+                    pbid = pricebookMap1.get(key);
+    system.debug('=====key:' + key);
+                } else if (acc2psMap.get(opp.AccountId) == 'BS' || acc2psMap.get(opp.AccountId) == 'IE' || acc2psMap.get(opp.AccountId) == 'RVI') {
+                    String key = opp.ProductSegment__c + '-' + opp.TradeType__c + '-' + opp.SalesChannel__c + '-' + opp.Machine_Parts__c;
+                    system.debug('=====key-BS-IE-key1:' + key);
+                    if (opp.TradeType__c == null || opp.SalesChannel__c == null || opp.Machine_Parts__c == null) {
+                        key = opp.ProductSegment__c + '-' + opp.Trade_Type_D__c + '-' + opp.Sales_Channel_D__c + '-' + opp.Machine_Parts_D__c;
+                    }
+                    pbid = pricebookMap1.get(key);
+    system.debug('=====key-BS-IE-key2:' + key);
+                }
+    system.debug('=====pbid:' + pbid);
+    system.debug('=====Pricebook2Id:' + opp.Pricebook2Id);
+                if (opp.Pricebook2Id != pbid) {
+                    if (opp.ProductCount__c > 0 && opp.needUpdate__c == false) {
+                        //鏂扮殑鑾峰彇浜哄憳绠�妗D
+                        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+                        // String profileId = UserInfo.getProfileId().subString(0,15);
+                        if (new_profileId.substring(0, 15) != System.Label.SystemAdmin && new_profileId.substring(0, 15) != System.Label.SystemAdmin2) {
+                            opp.addError('璇环涓湁浜у搧鏃讹紝涓嶈兘鏇存敼浠锋牸鎵嬪唽鍜屽喅瀹氫环鏍兼墜鍐岀殑椤圭洰銆�');
+                        }
+                    } else{
+                        opp.Pricebook2Id = pbid;
+                        opp.needUpdate__c = false;
+                        system.debug('!!!!'+opp);
+                    }
+                }
+                opp.needUpdate__c = false;
+            }
+        }
+    }
+    
+    public static void updateForDealer(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        system.debug('=====updateForDealer');
+        
+        for (Opportunity newOpp : newList) {
+            Opportunity oldOpp = oldMap.get(newOpp.Id);
+
+            //newOpp.Amount_D__c != oldOpp.Amount_D__c;
+            //newOpp.TotalOpportunityQuantity_D__c != oldOpp.TotalOpportunityQuantity_D__c;
+            if (newOpp.LeadSource_D__c != oldOpp.LeadSource_D__c || 
+            //newOpp.CloseDate_D__c != oldOpp.CloseDate_D__c;
+            //newOpp.StageName_D__c != oldOpp.StageName_D__c;
+                newOpp.AmountD__c != oldOpp.AmountD__c && (newOpp.ProductSegment__c != 'BS' && newOpp.ProductSegment__c != 'IE' && newOpp.ProductSegment__c != 'RVI' && newOpp.RecordTypeId != System.Label.RT_SSBD_Service ) || 
+                newOpp.Budget_Amount_D__c != oldOpp.Budget_Amount_D__c || 
+                newOpp.Cancel_Reason_Text_D__c != oldOpp.Cancel_Reason_Text_D__c || 
+                newOpp.Cancel_Reason_D__c != oldOpp.Cancel_Reason_D__c || 
+                newOpp.Competitor_Company_D__c != oldOpp.Competitor_Company_D__c || 
+                newOpp.Competitor_Product_D__c != oldOpp.Competitor_Product_D__c || 
+                newOpp.Competitor_Product2_D__c != oldOpp.Competitor_Product2_D__c || 
+                newOpp.Competitor_Product3_D__c != oldOpp.Competitor_Product3_D__c || 
+                newOpp.Competitor_Product4_D__c != oldOpp.Competitor_Product4_D__c || 
+                newOpp.Competitor_Product5_D__c != oldOpp.Competitor_Product5_D__c || 
+                newOpp.Competitor_Product6_D__c != oldOpp.Competitor_Product6_D__c || 
+                newOpp.Competitor_Product7_D__c != oldOpp.Competitor_Product7_D__c || 
+                newOpp.Competitor_Product8_D__c != oldOpp.Competitor_Product8_D__c || 
+                newOpp.Competitor_Product_Code_D__c != oldOpp.Competitor_Product_Code_D__c || 
+                newOpp.Competitor_Product_Code2_D__c != oldOpp.Competitor_Product_Code2_D__c || 
+                newOpp.Competitor_Product_Code3_D__c != oldOpp.Competitor_Product_Code3_D__c || 
+                newOpp.Competitor_Product_Code4_D__c != oldOpp.Competitor_Product_Code4_D__c || 
+                newOpp.Competitor_Product_Code5_D__c != oldOpp.Competitor_Product_Code5_D__c || 
+                newOpp.Competitor_Product_Code6_D__c != oldOpp.Competitor_Product_Code6_D__c || 
+                newOpp.Competitor_Product_Code7_D__c != oldOpp.Competitor_Product_Code7_D__c || 
+                newOpp.Competitor_Product_Code8_D__c != oldOpp.Competitor_Product_Code8_D__c || 
+                newOpp.Dealer_Sales_Staff_Name_D__c != oldOpp.Dealer_Sales_Staff_Name_D__c || 
+                newOpp.Dealer_Service_D__c != oldOpp.Dealer_Service_D__c || 
+                newOpp.Expected_Delivery_Date_D__c != oldOpp.Expected_Delivery_Date_D__c || 
+                newOpp.Expected_Order_Date_D__c != oldOpp.Expected_Order_Date_D__c || 
+                newOpp.Inquiry_Result_D__c != oldOpp.Inquiry_Result_D__c || 
+                newOpp.Inquiry_Result_Cancel_D__c != oldOpp.Inquiry_Result_Cancel_D__c || 
+                newOpp.Inquiry_Result_Lost_D__c != oldOpp.Inquiry_Result_Lost_D__c || 
+                newOpp.Inquiry_Result_Order_D__c != oldOpp.Inquiry_Result_Order_D__c || 
+                newOpp.Lost_Amount_D__c != oldOpp.Lost_Amount_D__c || 
+                newOpp.Lost_Competitor_Product_D__c != oldOpp.Lost_Competitor_Product_D__c || 
+                newOpp.LostReasonText_D__c != oldOpp.LostReasonText_D__c || 
+                newOpp.LostReason_D__c != oldOpp.Lostreason_D__c || 
+                newOpp.New_Inquiry_Date_D__c != oldOpp.New_Inquiry_Date_D__c || 
+                newOpp.Phase1Date_D__c != oldOpp.Phase1Date_D__c || 
+                newOpp.Phase2Date_D__c != oldOpp.Phase2Date_D__c || 
+                newOpp.Phase3Date_D__c != oldOpp.Phase3Date_D__c || 
+                newOpp.Sales_Channel_D__c != oldOpp.Sales_Channel_D__c || 
+                newOpp.Sub_Dealer_D__c != oldOpp.Sub_Dealer_D__c || 
+                newOpp.Trade_Type_D__c != oldOpp.Trade_Type_D__c || 
+                newOpp.Machine_Parts_D__c != oldOpp.Machine_Parts_D__c ||
+                newOpp.SpecialDeliveryAddress_D__c != oldOpp.SpecialDeliveryAddress_D__c ||
+                newOpp.ForeignTradeCompany_D__c != oldOpp.ForeignTradeCompany_D__c ||
+                newOpp.SpecialDeliveryContact_D__c != oldOpp.SpecialDeliveryContact_D__c ||
+                newOpp.DealerSelectOwner__c != oldOpp.DealerSelectOwner__c) {
+                if (UserInfo.getUserType() == 'PowerPartner' && newOpp.ProductSegment__c != 'BS' && newOpp.ProductSegment__c != 'IE' && newOpp.ProductSegment__c != 'RVI'  && newOpp.RecordTypeId != System.Label.RT_SSBD_Service && newOpp.RecordTypeId != System.Label.SSBD_Replacement && OrderDivisionController.OrderDivision == false) {
+                    newOpp.ApprovalStatus_D__c = 'Draft';
+                    if(newOpp.ProductSegment__c == 'NDT' || newOpp.ProductSegment__c == 'ANI'){
+                      newOpp.IsNew__c = true;
+                    }
+                    if (newOpp.Trade_Type_D__c == 'Tax Exemption' && newOpp.ForeignTradeCompany_D__c != oldOpp.ForeignTradeCompany_D__c) {
+                        newOpp.SpecialDeliveryAddress_D__c = newOpp.ForeignTradeCompany_D__c;
+                    }
+                }
+            }
+            
+                //newOpp.Amount_D__c = newOpp.Amount;
+                //newOpp.TotalOpportunityQuantity_D__c = newOpp.TotalOpportunityQuantity;
+            if (newOpp.LeadSource != oldOpp.LeadSource) {
+                newOpp.LeadSource_D__c = newOpp.LeadSource;
+            }
+                //newOpp.CloseDate_D__c = newOpp.CloseDate;
+                //newOpp.StageName_D__c = newOpp.StageName;
+            if (newOpp.BudgetAmount__c != oldOpp.BudgetAmount__c) {
+                newOpp.Budget_Amount_D__c = newOpp.BudgetAmount__c;
+            }
+            if (newOpp.CancelReasonText__c != oldOpp.CancelReasonText__c) {
+                newOpp.Cancel_Reason_Text_D__c = newOpp.CancelReasonText__c;
+            }
+            if (newOpp.CancelReason__c != oldOpp.CancelReason__c) {
+                newOpp.Cancel_Reason_D__c = newOpp.CancelReason__c;
+            }
+            if (newOpp.CompetitorCompany__c != oldOpp.CompetitorCompany__c) {
+                newOpp.Competitor_Company_D__c = newOpp.CompetitorCompany__c;
+            }
+            if (newOpp.Competitor_Product__c != oldOpp.Competitor_Product__c) {
+                newOpp.Competitor_Product_D__c = newOpp.Competitor_Product__c;
+            }
+            if (newOpp.Competitor_Product2__c != oldOpp.Competitor_Product2__c) {
+                newOpp.Competitor_Product2_D__c = newOpp.Competitor_Product2__c;
+            }
+            if (newOpp.Competitor_Product3__c != oldOpp.Competitor_Product3__c) {
+                newOpp.Competitor_Product3_D__c = newOpp.Competitor_Product3__c;
+            }
+            if (newOpp.Competitor_Product4__c != oldOpp.Competitor_Product4__c) {
+                newOpp.Competitor_Product4_D__c = newOpp.Competitor_Product4__c;
+            }
+            if (newOpp.Competitor_Product5__c != oldOpp.Competitor_Product5__c) {
+                newOpp.Competitor_Product5_D__c = newOpp.Competitor_Product5__c;
+            }
+            if (newOpp.Competitor_Product6__c != oldOpp.Competitor_Product6__c) {
+                newOpp.Competitor_Product6_D__c = newOpp.Competitor_Product6__c;
+            }
+            if (newOpp.Competitor_Product7__c != oldOpp.Competitor_Product7__c) {
+                newOpp.Competitor_Product7_D__c = newOpp.Competitor_Product7__c;
+            }
+            if (newOpp.Competitor_Product8__c != oldOpp.Competitor_Product8__c) {
+                newOpp.Competitor_Product8_D__c = newOpp.Competitor_Product8__c;
+            }
+            if (newOpp.CompetitorProductCode__c != oldOpp.CompetitorProductCode__c) {
+                newOpp.Competitor_Product_Code_D__c = newOpp.CompetitorProductCode__c;
+            }
+            if (newOpp.CompetitorProductCode2__c != oldOpp.CompetitorProductCode2__c) {
+                newOpp.Competitor_Product_Code2_D__c = newOpp.CompetitorProductCode2__c;
+            }
+            if (newOpp.CompetitorProductCode3__c != oldOpp.CompetitorProductCode3__c) {
+                newOpp.Competitor_Product_Code3_D__c = newOpp.CompetitorProductCode3__c;
+            }
+            if (newOpp.CompetitorProductCode4__c != oldOpp.CompetitorProductCode4__c) {
+                newOpp.Competitor_Product_Code4_D__c = newOpp.CompetitorProductCode4__c;
+            }
+            if (newOpp.CompetitorProductCode5__c != oldOpp.CompetitorProductCode5__c) {
+                newOpp.Competitor_Product_Code5_D__c = newOpp.CompetitorProductCode5__c;
+            }
+            if (newOpp.CompetitorProductCode6__c != oldOpp.CompetitorProductCode6__c) {
+                newOpp.Competitor_Product_Code6_D__c = newOpp.CompetitorProductCode6__c;
+            }
+            if (newOpp.CompetitorProductCode7__c != oldOpp.CompetitorProductCode7__c) {
+                newOpp.Competitor_Product_Code7_D__c = newOpp.CompetitorProductCode7__c;
+            }
+            if (newOpp.CompetitorProductCode8__c != oldOpp.CompetitorProductCode8__c) {
+                newOpp.Competitor_Product_Code8_D__c = newOpp.CompetitorProductCode8__c;
+            }
+            if (newOpp.DealerSalesStaffName__c != oldOpp.DealerSalesStaffName__c) {
+                newOpp.Dealer_Sales_Staff_Name_D__c = newOpp.DealerSalesStaffName__c;
+            }
+            if (newOpp.DealerService__c != oldOpp.DealerService__c) {
+                newOpp.Dealer_Service_D__c = newOpp.DealerService__c;
+            }
+            if (newOpp.ExpectedDeliveryDate__c != oldOpp.ExpectedDeliveryDate__c) {
+                newOpp.Expected_Delivery_Date_D__c = newOpp.ExpectedDeliveryDate__c;
+            }
+            if (newOpp.ExpectedOrderDate__c != oldOpp.ExpectedOrderDate__c) {
+                newOpp.Expected_Order_Date_D__c = newOpp.ExpectedOrderDate__c;
+            }
+            if (newOpp.InquiryResult__c != oldOpp.InquiryResult__c) {
+                newOpp.Inquiry_Result_D__c = newOpp.InquiryResult__c;
+            }
+            if (newOpp.InquiryResultCancel__c != oldOpp.InquiryResultCancel__c) {
+                newOpp.Inquiry_Result_Cancel_D__c = newOpp.InquiryResultCancel__c;
+            }
+            if (newOpp.InquiryResultLost__c != oldOpp.InquiryResultLost__c) {
+                newOpp.Inquiry_Result_Lost_D__c = newOpp.InquiryResultLost__c;
+            }
+            if (newOpp.InquiryResultOrder__c != oldOpp.InquiryResultOrder__c) {
+                newOpp.Inquiry_Result_Order_D__c = newOpp.InquiryResultOrder__c;
+            }
+            if (newOpp.LostAmount__c != oldOpp.LostAmount__c) {
+                newOpp.Lost_Amount_D__c = newOpp.LostAmount__c;
+            }
+            if (newOpp.LostCompetitorProduct__c != oldOpp.LostCompetitorProduct__c) {
+                newOpp.Lost_Competitor_Product_D__c = newOpp.LostCompetitorProduct__c;
+            }
+            if (newOpp.LostReasonText__c != oldOpp.LostReasonText__c) {
+                newOpp.LostReasonText_D__c = newOpp.LostReasonText__c;
+            }
+            if (newOpp.Lostreason__c != oldOpp.Lostreason__c) {
+                newOpp.LostReason_D__c = newOpp.Lostreason__c;
+            }
+            if (newOpp.NewInquiryDate__c != oldOpp.NewInquiryDate__c) {
+                newOpp.New_Inquiry_Date_D__c = newOpp.NewInquiryDate__c;
+            }
+            if (newOpp.Phase1Date__c != oldOpp.Phase1Date__c) {
+                newOpp.Phase1Date_D__c = newOpp.Phase1Date__c;
+            }
+            if (newOpp.Phase2Date__c != oldOpp.Phase2Date__c) {
+                newOpp.Phase2Date_D__c = newOpp.Phase2Date__c;
+            }
+            if (newOpp.Phase3Date__c != oldOpp.Phase3Date__c) {
+                newOpp.Phase3Date_D__c = newOpp.Phase3Date__c;
+            }
+            if (newOpp.SalesChannel__c != oldOpp.SalesChannel__c) {
+                newOpp.Sales_Channel_D__c = newOpp.SalesChannel__c;
+            }
+            if (newOpp.SubDealer__c != oldOpp.SubDealer__c) {
+                newOpp.Sub_Dealer_D__c = newOpp.SubDealer__c;
+            }
+            if (newOpp.TradeType__c != oldOpp.TradeType__c) {
+                newOpp.Trade_Type_D__c = newOpp.TradeType__c;
+            }
+             if (newOpp.Machine_Parts__c != oldOpp.Machine_Parts__c) {
+                newOpp.Machine_Parts_D__c = newOpp.Machine_Parts__c;
+            }
+            if (newOpp.SpecialDeliveryAddress__c != oldOpp.SpecialDeliveryAddress__c) {
+                newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
+            }
+            if (newOpp.ForeignTradeCompany__c != oldOpp.ForeignTradeCompany__c) {
+                newOpp.ForeignTradeCompany_D__c = newOpp.ForeignTradeCompany__c;
+                // 澶栬锤閫佽揪鏂归粯璁や负澶栬锤鍏徃
+                if (newOpp.Trade_Type_D__c == 'Tax Exemption') {
+                    newOpp.SpecialDeliveryAddress__c = newOpp.ForeignTradeCompany__c;
+                    newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
+                }
+            }
+            if (newOpp.SpecialDeliveryContact__c != oldOpp.SpecialDeliveryContact__c) {
+                newOpp.SpecialDeliveryContact_D__c = newOpp.SpecialDeliveryContact__c;
+            }
+            if (newOpp.OwnerId != oldOpp.OwnerId) {
+                newOpp.DealerSelectOwner__c = newOpp.OwnerId;
+            }
+        }
+    }
+    
+    public static void dealerOpportunityApproval(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        system.debug('=====dealerOpportunityApproval');
+        
+        for (Opportunity newOpp : newList) {
+            Opportunity oldOpp = oldMap.get(newOpp.Id);
+            
+            if (newOpp.ApprovalStatus_D__c != oldOpp.ApprovalStatus_D__c) {
+                if (newOpp.ApprovalStatus_D__c == 'Pass') {
+                    // 鎵瑰噯杩囩▼鑲畾鏄竴鏉′竴鏉℃壒鍑嗙殑锛屾墍浠ヨ繖閲屽啀寰幆涓啓浜唖elect鏂�
+                    List<Account> accList = [select Id, IsNew__c, AccountStatus__c from Account where Id = :newOpp.AccountId];
+                    if (accList.size() > 0) {
+                        Account acc = accList[0];
+                        if (acc.IsNew__c == true || acc.AccountStatus__c == 'Cancel') {
+                            newOpp.addError('瀹㈡埛鏃犳晥鎴栨湭閫氳繃瀹℃壒锛屼笉鑳芥壒鍑嗗綋鍓嶈浠枫��');
+                        }
+                    }
+                    //List<OpportunityContactRole> ocrList = [select Id, OpportunityId, Contact.isNew__c, Contact.ContactStatus__c from OpportunityContactRole where OpportunityId = :newOpp.Id];
+                    //for (OpportunityContactRole ocr : ocrList) {
+                    //    if (ocr.Contact.isNew__c == true || ocr.Contact.ContactStatus__c == 'Cancel') {
+                    //        newOpp.addError('鑱旂郴浜烘棤鏁堟垨鏈�氳繃瀹℃壒锛屼笉鑳芥壒鍑嗗綋鍓嶈浠枫��');
+                    //    }
+                    //}
+                    //newOpp.Amount = newOpp.Amount_D__c;
+                    //newOpp.TotalOpportunityQuantity = newOpp.TotalOpportunityQuantity_D__c;
+                    newOpp.LeadSource = newOpp.LeadSource_D__c;
+                    //newOpp.CloseDate = newOpp.CloseDate_D__c;
+                    //newOpp.StageName = newOpp.StageName_D__c;
+                    newOpp.BudgetAmount__c = newOpp.Budget_Amount_D__c;
+                    newOpp.CancelReasonText__c = newOpp.Cancel_Reason_Text_D__c;
+                    newOpp.CancelReason__c = newOpp.Cancel_reason_D__c;
+                    newOpp.CompetitorCompany__c = newOpp.Competitor_Company_D__c;
+                    newOpp.Competitor_Product__c = newOpp.Competitor_Product_D__c;
+                    newOpp.Competitor_Product2__c = newOpp.Competitor_Product2_D__c;
+                    newOpp.Competitor_Product3__c = newOpp.Competitor_Product3_D__c;
+                    newOpp.Competitor_Product4__c = newOpp.Competitor_Product4_D__c;
+                    newOpp.Competitor_Product5__c = newOpp.Competitor_Product5_D__c;
+                    newOpp.Competitor_Product6__c = newOpp.Competitor_Product6_D__c;
+                    newOpp.Competitor_Product7__c = newOpp.Competitor_Product7_D__c;
+                    newOpp.Competitor_Product8__c = newOpp.Competitor_Product8_D__c;
+                    newOpp.CompetitorProductCode__c = newOpp.Competitor_Product_Code_D__c;
+                    newOpp.CompetitorProductCode2__c = newOpp.Competitor_Product_Code2_D__c;
+                    newOpp.CompetitorProductCode3__c = newOpp.Competitor_Product_Code3_D__c;
+                    newOpp.CompetitorProductCode4__c = newOpp.Competitor_Product_Code4_D__c;
+                    newOpp.CompetitorProductCode5__c = newOpp.Competitor_Product_Code5_D__c;
+                    newOpp.CompetitorProductCode6__c = newOpp.Competitor_Product_Code6_D__c;
+                    newOpp.CompetitorProductCode7__c = newOpp.Competitor_Product_Code7_D__c;
+                    newOpp.CompetitorProductCode8__c = newOpp.Competitor_Product_Code8_D__c;
+                    newOpp.DealerSalesStaffName__c = newOpp.Dealer_Sales_Staff_Name_D__c;
+                    newOpp.DealerService__c = newOpp.Dealer_Service_D__c;
+                    newOpp.ExpectedDeliveryDate__c = newOpp.Expected_delivery_date_D__c;
+                    newOpp.ExpectedOrderDate__c = newOpp.Expected_Order_Date_D__c;
+                    newOpp.InquiryResult__c = newOpp.Inquiry_result_D__c;
+                    newOpp.InquiryResultCancel__c = newOpp.Inquiry_result_cancel_D__c;
+                    newOpp.InquiryResultLost__c = newOpp.Inquiry_result_lost_D__c;
+                    newOpp.InquiryResultOrder__c = newOpp.Inquiry_result_order_D__c;
+                    newOpp.LostAmount__c = newOpp.Lost_amount_D__c;
+                    newOpp.LostCompetitorProduct__c = newOpp.Lost_competitor_product_D__c;
+                    newOpp.LostReasonText__c = newOpp.LostReasonText_D__c;
+                    newOpp.LostReason__c = newOpp.Lostreason_D__c;
+                    newOpp.NewInquiryDate__c = newOpp.New_Inquiry_Date_D__c;
+                    newOpp.Phase1Date__c = newOpp.Phase1Date_D__c;
+                    newOpp.Phase2Date__c = newOpp.Phase2Date_D__c;
+                    newOpp.Phase3Date__c = newOpp.Phase3Date_D__c;
+                    newOpp.SalesChannel__c = newOpp.Sales_Channel_D__c;
+                    newOpp.SubDealer__c = newOpp.Sub_Dealer_D__c;
+                    newOpp.TradeType__c = newOpp.Trade_Type_D__c;
+                    newOpp.Machine_Parts__c = newOpp.Machine_Parts_D__c;
+                    newOpp.SpecialDeliveryAddress__c = newOpp.SpecialDeliveryAddress_D__c;
+                    newOpp.ForeignTradeCompany__c = newOpp.ForeignTradeCompany_D__c;
+                    newOpp.SpecialDeliveryContact__c = newOpp.SpecialDeliveryContact_D__c;
+                    if (newOpp.IsNew__c = true) {
+                        newOpp.IsNew__c = false;
+                    }
+                    
+                    newOpp.OwnerId = newOpp.DealerSelectOwner__c;
+                    
+                    if (newOpp.Inquiry_result_order_D__c != null) {
+                        newOpp.StageName = 'Closed Won';
+                    } else if (newOpp.Inquiry_result_lost_D__c != null) {
+                        newOpp.StageName = 'Closed Lost';
+                    } else if (newOpp.Inquiry_result_cancel_D__c != null) {
+                        newOpp.StageName = 'Closed Cancel';
+                    } else if (newOpp.Phase3Date_D__c != null) {
+                        newOpp.StageName = 'Phase3';
+                    } else if (newOpp.Phase2Date_D__c != null) {
+                        newOpp.StageName = 'Phase2';
+                    } else if (newOpp.Phase1Date_D__c != null) {
+                        newOpp.StageName = 'Phase1';
+                    } else {
+                        newOpp.StageName = 'Prospect Created';
+                    }
+                }
+                Boolean specialDealer =  StaticParameter.specialDealerMap1.containsKey(newOpp.DealerId__c);
+            
+                if (newOpp.ApprovalStatus_D__c == 'Reject' && newOpp.IsNew__c == false && specialDealer == false) {
+                    //newOpp.Amount_D__c = newOpp.Amount;
+                    //newOpp.TotalOpportunityQuantity_D__c = newOpp.TotalOpportunityQuantity;
+                    newOpp.LeadSource_D__c = newOpp.LeadSource;
+                    //newOpp.CloseDate_D__c = newOpp.CloseDate;
+                    //newOpp.StageName_D__c = newOpp.StageName;
+                    newOpp.Budget_Amount_D__c = newOpp.BudgetAmount__c;
+                    newOpp.Cancel_Reason_Text_D__c = newOpp.CancelReasonText__c;
+                    newOpp.Cancel_Reason_D__c = newOpp.CancelReason__c;
+                    newOpp.Competitor_Company_D__c = newOpp.CompetitorCompany__c;
+                    newOpp.Competitor_Product_D__c = newOpp.Competitor_Product__c;
+                    newOpp.Competitor_Product2_D__c = newOpp.Competitor_Product2__c;
+                    newOpp.Competitor_Product3_D__c = newOpp.Competitor_Product3__c;
+                    newOpp.Competitor_Product4_D__c = newOpp.Competitor_Product4__c;
+                    newOpp.Competitor_Product5_D__c = newOpp.Competitor_Product5__c;
+                    newOpp.Competitor_Product6_D__c = newOpp.Competitor_Product6__c;
+                    newOpp.Competitor_Product7_D__c = newOpp.Competitor_Product7__c;
+                    newOpp.Competitor_Product8_D__c = newOpp.Competitor_Product8__c;
+                    newOpp.Competitor_Product_Code_D__c = newOpp.CompetitorProductCode__c;
+                    newOpp.Competitor_Product_Code2_D__c = newOpp.CompetitorProductCode2__c;
+                    newOpp.Competitor_Product_Code3_D__c = newOpp.CompetitorProductCode3__c;
+                    newOpp.Competitor_Product_Code4_D__c = newOpp.CompetitorProductCode4__c;
+                    newOpp.Competitor_Product_Code5_D__c = newOpp.CompetitorProductCode5__c;
+                    newOpp.Competitor_Product_Code6_D__c = newOpp.CompetitorProductCode6__c;
+                    newOpp.Competitor_Product_Code7_D__c = newOpp.CompetitorProductCode7__c;
+                    newOpp.Competitor_Product_Code8_D__c = newOpp.CompetitorProductCode8__c;
+                    newOpp.Dealer_Sales_Staff_Name_D__c = newOpp.DealerSalesStaffName__c;
+                    newOpp.Dealer_Service_D__c = newOpp.DealerService__c;
+                    newOpp.Expected_Delivery_Date_D__c = newOpp.ExpectedDeliveryDate__c;
+                    newOpp.Expected_Order_Date_D__c = newOpp.ExpectedOrderDate__c;
+                    newOpp.Inquiry_Result_D__c = newOpp.InquiryResult__c;
+                    newOpp.Inquiry_Result_Cancel_D__c = newOpp.InquiryResultCancel__c;
+                    newOpp.Inquiry_Result_Lost_D__c = newOpp.InquiryResultLost__c;
+                    newOpp.Inquiry_Result_Order_D__c = newOpp.InquiryResultOrder__c;
+                    newOpp.Lost_Amount_D__c = newOpp.LostAmount__c;
+                    newOpp.Lost_Competitor_Product_D__c = newOpp.LostCompetitorProduct__c;
+                    newOpp.LostReasonText_D__c = newOpp.LostReasonText__c;
+                    newOpp.LostReason_D__c = newOpp.Lostreason__c;
+                    newOpp.New_Inquiry_Date_D__c = newOpp.NewInquiryDate__c;
+                    newOpp.Phase1Date_D__c = newOpp.Phase1Date__c;
+                    newOpp.Phase2Date_D__c = newOpp.Phase2Date__c;
+                    newOpp.Phase3Date_D__c = newOpp.Phase3Date__c;
+                    newOpp.Sales_Channel_D__c = newOpp.SalesChannel__c;
+                    newOpp.Sub_Dealer_D__c = newOpp.SubDealer__c;
+                    newOpp.Trade_Type_D__c = newOpp.TradeType__c;
+                    newOpp.Machine_Parts_D__c = newOpp.Machine_Parts__c;
+                    newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
+                    newOpp.ForeignTradeCompany_D__c = newOpp.ForeignTradeCompany__c;
+                    newOpp.SpecialDeliveryContact_D__c = newOpp.SpecialDeliveryContact__c;
+                    newOpp.DealerSelectOwner__c = newOpp.OwnerId;
+                }
+                //21.6.4 WLIG-C3LA3U 銆愬鎵樸�慡SBG-LS鐗规畩浠g悊鍟嗕腑瑾夎浠疯椹冲洖鍚庤嚜鍔ㄥ彇娑�
+                String IdList = System.label.zhongyuID;
+                if(IdList != null && newOpp.DealerId__c != null){
+                    if (newOpp.ApprovalStatus_D__c == 'Reject' && IdList.contains(newOpp.DealerId__c.substring(0,15))){
+                        newOpp.StageName = 'Closed Cancel';
+                        newOpp.Cancel_Fail_Approve__c = 'Pass';
+                        newOpp.Cancel_reason_D__c = 'Other';
+                        newOpp.Cancel_Reason_Text_D__c = '鍏朵粬';
+                        newOpp.CancelReasonText__c = '鍏朵粬';
+                        newOpp.CancelReason__c = 'Other';
+                    }
+                }
+            }
+        }
+    }
+    
+    public static void dealerOpportunityApproval2(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+       
+        List<String> oppIdList = new List<String>();
+        
+        system.debug('=====dealerOpportunityApproval2');
+        //List<String> passOppList = new List<String>();
+        //List<String> rejectOppList = new List<String>();
+        for (Opportunity newOpp : newList) {
+            Opportunity oldOpp = oldMap.get(newOpp.Id);
+            if (newOpp.ApprovalStatus_D__c != oldOpp.ApprovalStatus_D__c) {
+                if (newOpp.ApprovalStatus_D__c == 'Pass') {
+                    //passOppList.add(newOpp.Id);
+                    oppIdList.add(newOpp.Id);
+                }
+                if (newOpp.ApprovalStatus_D__c == 'Reject' && newOpp.IsNew__c == false) {
+                    //rejectOppList.add(newOpp.Id);
+                }
+            }
+        }
+        if (oppIdList.size() > 0) {
+            List<OpportunityShare> osList = [select Id, OpportunityId, UserOrGroupId, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId = :oppIdList and RowCause = 'Team' and OpportunityAccessLevel = 'Read'];
+            for (OpportunityShare os : osList) {
+                os.OpportunityAccessLevel = 'Edit';
+            }
+            if (osList.size() > 0) {
+                update osList;
+            }
+        }
+        
+/*        List<OpportunityLineItem> updList = new List<OpportunityLineItem>();
+        List<OpportunityLineItem> delList = new List<OpportunityLineItem>();
+        if (passOppList.size() > 0) {
+            List<OpportunityLineItem> oliList = [select id,Quantity,UnitPrice,Description,QuantityD__c,UnitPriceD__c,DescriptionD__c,IsNew__c,IsDelete__c from OpportunityLineItem where OpportunityId in :passOppList];
+            for (OpportunityLineItem oli : oliList) {
+                if (oli.IsDelete__c) {
+                    delList.add(oli);
+                } else {
+                    oli.Quantity = oli.QuantityD__c;
+                    oli.UnitPrice = oli.UnitPriceD__c;
+                    oli.Description = oli.DescriptionD__c;
+                    if (oli.IsNew__c == true) {
+                        oli.IsNew__c = false;
+                    }
+                    updList.add(oli);
+                }
+            }
+        }
+        if (rejectOppList.size() > 0) {
+            List<OpportunityLineItem> oliList = [select id,Quantity,UnitPrice,Description,QuantityD__c,UnitPriceD__c,DescriptionD__c,IsNew__c,IsDelete__c from OpportunityLineItem where OpportunityId in :rejectOppList];
+            for (OpportunityLineItem oli : oliList) {
+                if (oli.IsNew__c == false) {
+                    oli.QuantityD__c = oli.Quantity;
+                    oli.UnitPriceD__c = oli.UnitPrice;
+                    oli.DescriptionD__c = oli.Description;
+                    if (oli.IsDelete__c == true) {
+                        oli.IsDelete__c = false;
+                    }
+                    updList.add(oli);
+                } else {
+                    delList.add(oli);
+                }
+            }
+        }
+        
+        if (updList.size() > 0) {
+            update updList;
+        }
+        if (delList.size() > 0) {
+            delete delList;
+        }*/
+    }
+    
+    public static void setDealerGroup(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        List<String> groupIdList = new List<String>();
+        List<String> oppIdList = new List<String>();
+        
+        List<String> specialDealerList = new List<String>();
+        for (Opportunity newOpp : newList) {
+            oppIdList.add(newOpp.Id);
+            String dealerId = newOpp.Dealer__c;
+            String groupId = StaticParameter.dealerGroupMap.get(dealerId == null ? '' : dealerId.substring(0, 15));
+            Boolean flag = StaticParameter.specialDealerList.contains(dealerId == null ? '' : dealerId.substring(0, 15));
+            if(flag){
+                specialDealerList.add(newOpp.Id);
+            }
+            if (groupId == null || groupId.length() == 0) {
+                continue;
+            }
+            groupIdList.add(groupId);
+        }
+        List<GroupMember> gmList = [select id, groupId, userOrGroupId from GroupMember where groupId = :groupIdList];
+        
+        List<OpportunityTeamMember> insertList = new list<OpportunityTeamMember>();
+
+        for (Opportunity newOpp : newList) {
+            if(newOpp.RecordTypeId != '0120l000000eXDu'){
+                String dealerId = newOpp.Dealer__c;
+                String groupId = StaticParameter.dealerGroupMap.get(dealerId == null ? '' : dealerId.substring(0, 15));
+                if(specialDealerList.contains(newOpp.Id)){
+                    OpportunityTeamMember otm = new OpportunityTeamMember();
+                    otm.opportunityId = newOpp.Id;
+                    otm.userId = newOpp.CreatedById;
+                    otm.teamMemberRole = 'Sales Manager';
+                    insertList.add(otm);
+                    continue;
+                }
+                if (groupId == null || groupId.length() == 0) {
+                    continue;
+                }
+                for (GroupMember gm : gmList) {
+                    if (gm.groupId == groupId) {
+                        OpportunityTeamMember otm = new OpportunityTeamMember();
+                        otm.opportunityId = newOpp.Id;
+                        otm.userId = gm.userOrGroupId;
+                        otm.teamMemberRole = 'Sales Manager';
+                        insertList.add(otm);
+                    }
+                }
+            }
+        }
+        if (insertList.size() > 0) {
+            insert insertList;
+        }
+        
+        List<OpportunityShare> osList = new List<OpportunityShare>();
+        osList = [select Id, OpportunityId, UserOrGroupId, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId = :oppIdList and RowCause = 'Team'];
+        for (OpportunityShare os : osList) {
+            os.OpportunityAccessLevel = 'Edit';
+        }
+        if (osList.size() > 0) {
+            update osList;
+        }
+    }
+
+// Added by wangshuo for Opportunity BusinessDepOwner check
+
+  public static void setReceiver(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap)
+   {
+        if (StaticParameter.OpportunityTriggerHandler_setReceiver) {
+            return;
+        }
+        
+        List<String> ownerIdList = new List<String>();
+        Map<String,String> opportunityToOwner = new Map<String,String>();
+
+        For (Opportunity opp: newList) {
+            ownerIdList.add(opp.DealerSelectOwner__c);
+            opportunityToOwner.put(opp.Id, opp.DealerSelectOwner__c);
+        }
+
+        Map<Id, User> copyUserMap = new Map<Id, User>([SELECT Id, Name,BS_AsistGenManger__c,AsistGenManger__c, BusinessDepOwner_Tax__c,BusinessDepOwner_WithoutTax__c,SalesWindow__c,Department__c,SalesManager__c FROM User 
+            WHERE Id IN :ownerIdList ]);
+
+           for (Opportunity opp: newList)
+           {  User u = copyUserMap.get(OpportunityToOwner.get(opp.Id));
+                if (u != null && ( u.BusinessDepOwner_Tax__c != null || u.BusinessDepOwner_WithoutTax__c != null ))
+                 {
+                    opp.BusinessDepOwnerWithoutTax__c = u.BusinessDepOwner_WithoutTax__c == null ? u.Id : u.BusinessDepOwner_WithoutTax__c;
+                    opp.BusinessDepOwnerTax__c = u.BusinessDepOwner_Tax__c == null ? u.Id : u.BusinessDepOwner_Tax__c;
+                }
+                //鐜嬮箯浼熸柊鍔� 鐗逛环瀹℃壒娴佺▼璋冩暣 寮�濮�
+                if(u!=null && (u.SalesWindow__c != null || u.Department__c !=null)){
+                    opp.IESalesManage__c = u.SalesManager__c != null ? u.SalesManager__c : u.Id;
+                    opp.IESalesManageWindow__c  = u.SalesWindow__c != null ? u.SalesWindow__c : u.Id;
+                    opp.DepartmentPrincipal__c = u.Department__c != null ? u.Department__c : u.Id;
+                    opp.AsistGenMangerIE__c = u.AsistGenManger__c != null ? u.AsistGenManger__c : u.Id;
+                }
+                //缁撴潫
+                //璺ㄥ尯閿�鍞坊鍔犲壇閮ㄩ暱
+                if(u != null && u.BS_AsistGenManger__c != null){
+                    opp.AsistGenManger__c = u.BS_AsistGenManger__c;
+                }
+            }  
+            StaticParameter.OpportunityTriggerHandler_setReceiver = true;     
+        }
+
+    public static void setTextField(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+         
+        List<String> targetList = new List<String>();
+        Map<Id,Id> manager = new Map<Id,Id>();
+        Map<Id,Id> association = new Map<Id,Id>();
+        List<Id> oldId = new List<Id>();
+        Map<Id,Id> nullList = new Map<Id,Id>();
+        for (Opportunity newOpp : newList) {
+            Opportunity oldOpp = oldMap.get(newOpp.Id);
+            // if (newOpp.DealerSelectOwner__c != null){
+            // WLIG-BVP4L2 瑙﹀彂101 淇敼浜嗕笂闈㈢殑鍒ゆ柇鏉′欢锛屾敼涓轰笅闈㈢殑鍒ゆ柇渚濇嵁锛屽悓鏃跺姞涓婁簡if (userid.size() > 0)
+            if((newOpp.DealerSelectOwner__c != null && newOpp.DealerSelectOwner__c != oldOpp.DealerSelectOwner__c) || newOpp.Manager__c  == null ){
+                manager.put(newOpp.DealerSelectOwner__c , oldOpp.Id);
+            }
+            //鐢ㄤ簬鍏宠仈璇环
+            if(newOpp.Have_Computer__c == false && newOpp.Association_Opportunity__c != null && newOpp.Association_Opportunity__c != oldOpp.Association_Opportunity__c && StaticParameter.OppCanChangeOpp == false){
+                newOpp.addError('璇峰湪鍖呭惈鐢佃剳鐨勮浠蜂腑閫夋嫨涓绘満璇环銆�');
+                
+            }else if(newOpp.Have_Computer__c == true && newOpp.Association_Opportunity__c == null){
+                newOpp.addError('璇烽�夋嫨鍏宠仈璇环銆�');
+            }else if(newOpp.CanChangeOpp__c == false && newOpp.Association_Opportunity__c != oldOpp.Association_Opportunity__c){
+                newOpp.addError('鍚堝悓宸茬粡鎻愪氦瀹℃壒鎴栧凡缁忔壒鍑嗭紝涓嶈兘淇敼鍏宠仈璇环');
+            }else if(StaticParameter.OppChangeopp == false){
+                if(newOpp.Association_Opportunity__c != null && newOpp.Association_Opportunity__c != oldOpp.Association_Opportunity__c){
+                    association.put(newOpp.Association_Opportunity__c, newOpp.Id);
+                    if(oldOpp.Association_Opportunity__c != null){
+                        oldId.add(oldOpp.Association_Opportunity__c);
+                    }
+                }else if(newOpp.Association_Opportunity__c == null && oldOpp.Association_Opportunity__c != null){
+                    nullList.put(oldOpp.Association_Opportunity__c,oldOpp.Id);
+                }
+
+            }
+            if (oldOpp.SyncedQuoteId == null && newOpp.SyncedQuoteId == null) {
+                targetList.add(newOpp.Id);
+            }
+             if(newOpp.OppShipping__c == null && newOpp.OppIntake__c != null){
+                newOpp.OppShipping__c = newOpp.OppIntake__c.addDays(90);
+                //Date.addDays(Integer days)
+            }
+
+            //鐜嬮箯浼� 璁板綍闈炲畾鏃朵换鍔℃洿鏂拌浠风殑鏈�鍚庢洿鏂版椂闂翠互鍙婃洿鏂扮敤鎴�
+            if(UserInfo.getUserId().substring(0,15) != '00528000004ooQW' && UserInfo.getUserId().substring(0,15) != '00528000006hJeB' ){
+                newOpp.OppUpdateDateTime__c = Datetime.now();
+                newOpp.OppUpdateUser__c = UserInfo.getUserId();
+                if(newOpp.ProductSegment__c != 'NDT' && newOpp.ProductSegment__c != 'ANI'){
+                    newOpp.IsUpdate__c = true;
+                    newOpp.OppUpdateDate__c = Date.today();
+                    newOpp.ThreeMonths__c = false;
+                    newOpp.SixMonths__c = false;
+                    newOpp.NineMonths__c = false;
+                    newOpp.OneYear__c = false;
+                }
+            }
+        }
+        List<Opportunity> updateList = new List<Opportunity>();
+        List<Order> updateOrdList = new List<Order>();
+        if(association.size() > 0){
+
+            for(Id ass : association.keySet()){
+                Opportunity opp = new Opportunity();
+                opp.Id =ass; 
+                opp.Association_Opportunity__c = association.get(ass);
+                updateList.add(opp);
+            }
+            for(Id id : oldId){
+                Opportunity opp = new Opportunity();
+                opp.Id = id;
+                opp.Association_Opportunity__c = null;
+                updateList.add(opp);
+            }
+            List<Id> ordIdList = new List<Id>();
+            ordIdList.addAll(association.keySet());
+            ordIdList.addAll(oldId);
+
+            List<Order> ordList = new List<Order>();
+            ordList = [select id,opportunityId from Order where opportunityId in : ordIdList and Status__c = 'Active'];
+            Map<Id,Id> ord_oppMap = new Map<Id,Id>();
+            List<Id> oldOrd = new List<Id>();
+            if(ordList.size() >0){
+                for(Order o : ordList){
+                    if(association.keySet().contains(o.OpportunityId)){
+                        if (newMap.get(association.get(o.OpportunityId)).OrderId__c != null) {
+                            Order ordnew = new Order();
+                            ordnew.Id = newMap.get(association.get(o.OpportunityId)).OrderId__c;
+                            ordnew.Association_Order__c = o.Id;
+                            order ordold = new Order();
+                            ordold.Id = o.Id;
+                            ordold.Association_Order__c = newMap.get(association.get(o.OpportunityId)).OrderId__c;
+                            updateOrdList.add(ordnew);
+                            updateOrdList.add(ordold);
+                        }
+                    }
+                    if(oldId.contains(o.OpportunityId)){
+                        Order ordnull = new Order();
+                        ordnull.Id = o.Id;
+                        ordnull.Association_Order__c = null;
+                        updateOrdList.add(ordnull);
+                    }
+                }
+            }
+        }
+        if(nullList.size() > 0 ){
+
+            for(Id id : nullList.keySet()){
+                Opportunity opp = new Opportunity();
+                opp.Id = id;
+                opp.Association_Opportunity__c = null;
+                updateList.add(opp);
+            }
+            List<Order> ordList = [select id,opportunityId from Order where opportunityId in : nullList.keySet() and Status__c = 'Active'];
+            if(ordList.size() > 0){
+                for (Order o : ordList) {
+                    if(nullList.keySet().contains(o.OpportunityId)){
+                        if (newMap.get(nullList.get(o.OpportunityId)).OrderId__c != null) {
+                            Order ord1 = new Order();
+                            ord1.Id = newMap.get(nullList.get(o.OpportunityId)).OrderId__c;
+                            ord1.Association_Order__c = null;
+                            Order ord2 = new Order();
+                            ord2.Id = o.Id;
+                            ord2.Association_Order__c = null;
+                            updateOrdList.add(ord1);
+                            updateOrdList.add(ord2);
+                        }
+                    }
+                }
+            }
+        }
+        StaticParameter.OppChangeopp = true;
+        StaticParameter.OppCanChangeOpp = true;
+        StaticParameter.temp = true;
+        if(updateList.size() > 0){
+            // StaticParameter.OppChangeopp = true;
+            // StaticParameter.OppCanChangeOpp = true;
+            update updateList;
+        }
+        if(updateOrdList.size() > 0){
+           //  StaticParameter.temp = true;
+            update updateOrdList;
+        }
+        List<User> userList = new List<User>();
+        Set<Id> userid = new Set<Id>();
+        userid.addAll(manager.keySet());
+        system.debug(manager);
+        if (userid.size() > 0) {
+            userList = [select id,SalesManager__c,BS_AsistGenManger__c from User where id in :userid];
+            system.debug(userList);
+            if(userList.size() > 0){
+                for(User use : userList){
+
+                    Id accid = manager.get(use.Id);
+                    system.debug(accid);
+                    system.debug(newMap);
+                    newMap.get(accid).Manager__c = use.BS_AsistGenManger__c == null ? use.SalesManager__c : use.BS_AsistGenManger__c;
+
+                }
+            }
+        }
+        
+        if(targetList.size() > 0){
+            List<OpportunityLineItem> oliList = [select Id, Name, ProductCode, ECCode__c, Quantity, OpportunityId, Opportunity.Amount,ProductName__c from OpportunityLineItem where OpportunityId = :targetList order by OpportunityId, Id];
+            Map<String, String> itemMap = new Map<String, String>();
+            Map<String, Decimal> amountMap = new Map<String, Decimal>();
+            Map<String, String> otitemMap = new Map<String, String>();
+            //鐜嬮箯浼熸柊鍔爈istitemMap 璇环鐨勪骇鍝侀厤缃竻鍗曪紙浜у搧鍚嶇О銆乁8 CODE銆乁PC CODE銆佹暟閲忥級璇环璺熻繘
+            Map<String, String> listitemMap = new Map<String,String>();
+            for (OpportunityLineItem oli : oliList) {
+                if (itemMap.containsKey(oli.OpportunityId) == false) {
+                    itemMap.put(oli.OpportunityId, oli.ECCode__c + '|' + oli.Quantity);
+                    otitemMap.put(oli.OpportunityId, oli.ProductCode + '|' + oli.Quantity);
+                    listitemMap.put(oli.OpportunityId,oli.ProductName__c+'|'+ oli.ProductCode + '|' + oli.ECCode__c + '|' + oli.Quantity);
+                    amountMap.put(oli.OpportunityId, oli.Opportunity.Amount);
+                } else {
+                    String tmp = itemMap.get(oli.OpportunityId);
+                    String tmp1 = otitemMap.get(oli.OpportunityId);
+                    String tmp2 = listitemMap.get(oli.OpportunityId);
+                    itemMap.put(oli.OpportunityId, tmp + ',\r\n' + oli.ECCode__c + '|' + oli.Quantity);
+                    otitemMap.put(oli.OpportunityId, tmp1 + ',\r\n' + oli.ProductCode + '|' + oli.Quantity);
+                    listitemMap.put(oli.OpportunityId, tmp2 + ',\r\n' + oli.ProductName__c+'|'+ oli.ProductCode + '|' + oli.ECCode__c + '|' + oli.Quantity);
+                }
+            }
+
+
+            for (Opportunity newOpp : newList) {
+                Opportunity oldOpp = oldMap.get(newOpp.Id);
+                if (oldOpp.SyncedQuoteId == null && newOpp.SyncedQuoteId == null) {
+                    newOpp.OpportunityLineItem_text__c = itemMap.get(newOpp.Id);
+                    newopp.OpportunityAmount_text__c = amountMap.get(newOpp.Id);
+                    newopp.OpportunityLineItemOT_text__c = otitemMap.get(newOpp.Id);
+                    newopp.OpportunityLineItemLIST_text__c = listitemMap.get(newOpp.Id);
+                }
+            }
+        }
+
+        // IE鐗逛环鐢宠鐘舵�侀噸缃�
+        for (Opportunity newOpp : newList) {
+            Opportunity oldOpp = oldMap.get(newOpp.Id);
+            if ((newOpp.ProductSegment__c == 'IE' || newOpp.ProductSegment__c == 'RVI'|| newOpp.ProductSegment__c == 'NDT'|| newOpp.ProductSegment__c == 'ANI') && OrderDivisionController.OrderDivision == false) {
+                if (newOpp.IE_Discount_Special__c != oldOpp.IE_Discount_Special__c ||
+                    //newOpp.OpportunityLineItem_text__c != oldOpp.OpportunityLineItem_text__c ||
+                    newOpp.OpportunityLineItemOT_text__c != oldOpp.OpportunityLineItemOT_text__c ||
+                    newOpp.IE_Custom_Price__c != oldOpp.IE_Custom_Price__c ||
+                    newOpp.IE_local_cost__c != oldOpp.IE_local_cost__c ||
+                    newOpp.IE_Subtotal__c != oldOpp.IE_Subtotal__c ||
+                    newOpp.IE_ShippingHandling__c != oldOpp.IE_ShippingHandling__c ||
+                    newOpp.IE_Payment_terms__c != oldOpp.IE_Payment_terms__c) {
+                    newOpp.SpecialPriceApproveStatus__c = 'Draft';
+                    //newOpp.test1__c = '2222';
+                    newOpp.IE_need_business_approve__c = false;
+                    System.debug(newOpp.OpportunityLineItemOT_text__c +'@@@@@@@@@@@@@@@@@@'+ oldOpp.OpportunityLineItemOT_text__c);
+                    System.debug( newOpp.OpportunityLineItemOT_text__c != oldOpp.OpportunityLineItemOT_text__c);
+                    system.debug('@@@@@IE鐗逛环鐢宠鐘舵�侀噸缃�');
+                }
+            }
+            //鐜嬮箯浼� 鏂板姞锛岃浠锋槸鍚︽洿鏂版墦鍕撅紝璁板綍鏇存柊鏃堕棿 寮�濮� 璇环璺熻繘
+            if((newOpp.Visit_Notes__c != oldOpp.Visit_Notes__c || 
+                newOpp.StageName != oldOpp.StageName || 
+                newOpp.OpportunityLineItemLIST_text__c != oldOpp.OpportunityLineItemLIST_text__c) && 
+                (newOpp.ProductSegment__c == 'NDT' || newOpp.ProductSegment__c == 'ANI')){
+
+                newOpp.IsUpdate__c = true;
+                newOpp.OppUpdateDate__c = Date.today();
+                newOpp.ThreeMonths__c = false;
+                newOpp.SixMonths__c = false;
+            }
+            //鐜嬮箯浼� 鏂板姞锛岃浠锋槸鍚︽洿鏂版墦鍕撅紝璁板綍鏇存柊鏃堕棿 缁撴潫
+        }
+    }
+
+
+    public static void setOrderFields(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        System.debug('Opportunity1 StaticParameter.OpportunityTriggerIsUpdate:'+StaticParameter.OpportunityTriggerIsUpdate);
+        if(StaticParameter.OpportunityTriggerIsUpdate || StaticParameter.StageProgressBarUpdate){
+            System.debug('Opportunity2 StaticParameter.OpportunityTriggerIsUpdate:'+StaticParameter.OpportunityTriggerIsUpdate);
+            StaticParameter.OpportunityTriggerIsUpdate = false;
+            
+            return;
+        }
+        List<String> targetList = new List<String>();
+        List<String> targetList2 = new List<String>();
+        List<String> targetList3 = new List<String>();
+        String targetList4 = '';
+        String quoId = '';
+        Map<String, boolean> changedMap = new Map<String, boolean>();
+        for (Opportunity opp : newList) {   
+            Opportunity oldOpp = oldMap.get(opp.Id);
+            if ((opp.ProductSegment__c == 'IE' || opp.ProductSegment__c == 'RVI'|| opp.ProductSegment__c == 'NDT'|| opp.ProductSegment__c == 'ANI') && opp.StageName != 'Closed Cancel' && opp.StageName != 'Closed Lost') {
+                targetList.add(opp.Id);
+                String item_text = opp.OpportunityLineItem_text__c;
+                String item_textot = opp.OpportunityLineItemOT_text__c;
+
+                item_text = item_text == null ? '' : item_text.replace('\r', '').replace('\n', '');
+                item_textot = item_textot == null ? '' : item_textot.replace('\r', '').replace('\n', '');
+
+                String item_text2 = oldOpp.OpportunityLineItem_text__c;
+                String item_textot2 = oldOpp.OpportunityLineItemOT_text__c;
+                
+                item_text2 = item_text2 == null ? '' : item_text2.replace('\r', '').replace('\n', '');
+                item_textot2 = item_textot2 == null ? '' : item_textot2.replace('\r', '').replace('\n', '');
+                
+                boolean changed = opp.IE_Discount_Special__c      != oldOpp.IE_Discount_Special__c      ||
+                                  //item_text                       != item_text2                         ||
+                                  item_textot                     != item_textot2                         ||     
+                                  opp.IE_Custom_Price__c          != oldOpp.IE_Custom_Price__c          ||
+                                  opp.IE_local_cost__c            != oldOpp.IE_local_cost__c            ||
+                                  opp.IE_Subtotal__c              != oldOpp.IE_Subtotal__c              ||
+                                  opp.IE_ShippingHandling__c      != oldOpp.IE_ShippingHandling__c      ||
+                                  opp.IE_Payment_terms__c         != oldOpp.IE_Payment_terms__c;
+                changedMap.put(opp.Id, oldOpp.SpecialPriceApproveStatus__c == 'Pass' && changed);
+            }
+            if (opp.OwnerId != oldOpp.OwnerId) {
+                targetList2.add(opp.Id);
+            }
+            //寮�濮� 鐜嬮箯浼熸坊鍔犱唬鐮� 璇环璐告槗绠$悊瀹㈡埛鍒嗙被鍙樻洿鏃讹紝鍚堝悓璐告槗绠$悊瀹㈡埛鍒嗙被鍚屾鍙樻洿 
+            if(opp.customerType__c != oldOpp.customerType__c){
+                StaticParameter.OrderTriggerIsUpdate = true;
+                if(!targetList2.contains(opp.Id)){
+                    targetList2.add(opp.Id);
+                }
+            }
+            //缁撴潫 鐜嬮箯浼熸坊鍔犱唬鐮� 璇环璐告槗绠$悊瀹㈡埛鍒嗙被鍙樻洿鏃讹紝鍚堝悓璐告槗绠$悊瀹㈡埛鍒嗙被鍚屾鍙樻洿 
+            //娣诲姞鏃ユ湡:2019-1-3鏃�
+            //娣诲姞鍘熷洜:鍦ㄨ浠风殑鍚屾鎶ヤ环淇敼鏃�,灏嗗悓姝ユ姤浠风殑浠樻鏂瑰紡璧嬪�煎埌鍚堝悓涓�.        
+            if(opp.Quote_PaymentTerms__c != oldOpp.Quote_PaymentTerms__c && opp.Quote_PaymentTerms__c != null){
+                targetList3.add(opp.Id);
+            }
+            system.debug('%%%%%%%%%%%'+opp.Dealer__c);
+            if((opp.SyncedQuoteId != oldOpp.SyncedQuoteId || oldOpp.SyncedQuoteId == null) && (opp.Dealer__c != '0012800001HoORb' && opp.Dealer__c != '0012800001HoPY4' && opp.Dealer__c != '0012800001HoPaz')){
+               system.debug('@@@111');
+               quoId = opp.SyncedQuoteId; 
+            }
+            if(opp.ProductSegment__c == 'BS' && opp.StageName == 'Phase3' && opp.Is_Decided__c == true && oldOpp.Is_Decided__c == false){
+                system.debug(opp.SyncedQuoteId);
+                targetlist4=opp.SyncedQuoteId;
+            }
+
+        }
+
+        if (targetList.size() > 0) {
+            List<Order> odrList = [select id, OpportunityId from Order where OpportunityId = :targetList and Status__c = 'Active'];
+            for (Order odr : odrList) {
+                Opportunity opp = newMap.get(odr.OpportunityId);
+
+                odr.Discount_D__c = opp.Quote_Discount__c;
+                odr.Olympus_Price_BeforeDiscount_D__c = opp.Quote_Subtotal__c;
+                odr.PaymentCondition_D__c = opp.Quote_PaymentTerms_Text__c;
+                Decimal warranty = opp.Quote_Warranty__c;
+                odr.SpecialWarranty_D__c = warranty == null ? '' : warranty.format();
+                odr.CustomerContractPriceD__c = opp.Quote_CustomPrice__c == null ? 0 : opp.Quote_CustomPrice__c;
+                odr.Shipment_Term_D__c = opp.Quote_ShipmentTerm__c;
+                odr.Shipment_Term2_D__c = opp.Quote_ShipmentTerm2__c;
+                Decimal totalPrice = opp.Quote_TotalPrice__c;
+                if(opp.ProductSegment__c != 'NDT' && opp.ProductSegment__c != 'ANI'){
+                    odr.OlympusContractPricesD__c = totalPrice.setScale(0, System.RoundingMode.HALF_UP);
+                }else{
+                    odr.OlympusContractPricesD__c = totalPrice;
+                    odr.WarrantyD__c = warranty == null ? '' : warranty.format();
+                }
+                //odr.OlympusContractPrices__c = odr.OlympusContractPricesD__c;
+                odr.Cost_D__c = opp.IE_local_cost__c;
+                if (changedMap.get(odr.OpportunityId)) {
+                    odr.Status__c = 'Inactive';
+                }
+            }
+
+            if (odrList.size() > 0) update odrList;
+        }
+        if (targetList2.size() > 0) {
+            //鐜嬮箯浼熻浠疯锤鏄撶鐞嗙被鍨嬪彉鏇达紝鍚堝悓鍚屾鍙樻洿  娣诲姞SQL鎼滅储瀛楁TradeMagCategory__c
+            List<Order> odrList = [select id, OpportunityId,TradeMagCategory__c from Order where OpportunityId = :targetList2];
+            for (Order odr : odrList) {
+                Opportunity opp = newMap.get(odr.OpportunityId);
+                //鐜嬮箯浼熻浠疯锤鏄撶鐞嗙被鍨嬪彉鏇达紝鍚堝悓鍚屾鍙樻洿  鏂板姞涓�琛�
+                odr.TradeMagCategory__c = opp.customerType__c;
+                // 璺ㄥ尯鍩熼攢鍞紝鍚堝悓鍏变韩寮傚父銆傚洜姝ゆ敞閲� 20210906 XHL  Start
+                // odr.OwnerId = opp.OwnerId;
+                // 璺ㄥ尯鍩熼攢鍞紝鍚堝悓鍏变韩寮傚父銆傚洜姝ゆ敞閲� 20210906 XHL  End
+            }
+
+            if (odrList.size() > 0) update odrList;
+        }
+        //娣诲姞鏃ユ湡:2019-1-3鏃�
+        //娣诲姞鍘熷洜:鍦ㄨ浠风殑鍚屾鎶ヤ环淇敼鏃�,灏嗗悓姝ユ姤浠风殑浠樻鏂瑰紡璧嬪�煎埌鍚堝悓涓�.
+        if(targetList3.size() > 0 ){
+            List<Order> odrList = [select id,OpportunityId from Order WHERE OpportunityId in :targetList3];
+            if(odrList.size() > 0){
+                for(Order odr : odrList){
+                    Opportunity opp = newMap.get(odr.OpportunityId);
+
+                    odr.PaymentTerms__c = opp.Quote_PaymentTerms__c;
+                }
+                update odrList;
+            }
+        }
+
+        if(quoID != null && quoId.length() > 0){
+            List<QuoteLineItem> qliList = [select id,DontSingleProduct__c from QuoteLineItem where QuoteId = :quoId];
+            String temp = '';
+            for(QuoteLineItem qli : qliList){
+                if(qli.DontSingleProduct__c != '1'){
+                    temp+=(' '+qli.DontSingleProduct__c);
+                }
+            }
+            Quote quo = new Quote();
+            quo.id = quoId;
+            quo.DontSingleProductCode__c = temp;
+
+            if(temp.length() >0) update quo;
+        }
+
+        if(targetList4 != null && targetlist4 != '' ){
+            List<QuoteLineItem> quoLIList = [select Id, QuoteId, Description, Quantity, PricebookEntryId, UnitPrice from QuoteLineItem where QuoteId = :targetlist4];
+            List<Order> ordList = [select Id from Order where QuoteId = :targetlist4 and Contract_Status__c = 'Active'];
+            if(ordList.size() > 0){
+                Order ord = ordList[0];
+                String orderId = ord.Id;
+                List<OrderItem> oiList = [select Id from OrderItem where OrderId = :orderId];
+                List<OrderItem> insList = new List<OrderItem>();
+                for (QuoteLineItem qli : quoLIList) {
+                    OrderItem oi = new OrderItem();
+                    oi.Description = qli.Description;
+                    oi.Quantity = qli.Quantity;
+                    oi.PricebookEntryId = qli.PricebookEntryId;
+                    oi.UnitPrice = qli.UnitPrice;
+                    oi.OrderId = orderId;
+                    oi.QuoteLineItemId = qli.Id;
+                    insList.add(oi);
+                }
+                system.debug('111');
+                if (oiList.size() > 0) delete oiList;
+                if (insList.size() > 0) insert insList;
+            }
+        }   
+    }
+
+
+    public static void check(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
+        
+        String id = newList[0].id;
+        List<OpportunityLineItem> oliList = [select id,Product2.If_Exempt_Product__c,Product2.If_Radiation_Product__c from OpportunityLineItem where opportunityId = :id];
+        Boolean hasA = false;
+        if(newList[0].ProductSegment__c == 'ANI' ||newList[0].ProductSegment__c == 'NDT'){
+            for(OpportunityLineItem oli : oliList){
+                if(oli.Product2.If_Exempt_Product__c == false && oli.Product2.If_Radiation_Product__c == true){
+                    hasA = true;
+                }
+            }
+            if(hasA == true){
+                String str =  LicenseCheckUtil.LicenseCheck1(newList[0].DealerId__c);
+            newList[0].check__c =str;
+          
+            }
+        } 
+        Integer i=0;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++;      
+        i++; 
+    }
+
+     public static String checkoly(){
+        return LicenseCheckUtil.LicenseCheckOly();
+     }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityTriggerHandler.cls-meta.xml b/scr/classes/OpportunityTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityTriggerTest.cls b/scr/classes/OpportunityTriggerTest.cls
new file mode 100644
index 0000000..12b89cf
--- /dev/null
+++ b/scr/classes/OpportunityTriggerTest.cls
@@ -0,0 +1,633 @@
+@isTest
+private class OpportunityTriggerTest {
+    
+    // 鍏抽棴璇环鎻掑叆鍜屾洿鏂�
+    static testMethod void myTest1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+           
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+
+        OpportunityWebService.UpdateStageName(opp.Id, 'Closed Cancel');
+        update opp;
+        
+        List<Opportunity> oppList = [Select Id, CloseDate, ProductSegmentCompetitor__c, Pricebook2Id from Opportunity where Id = :opp.Id];
+        
+        //System.assertEquals(Date.today().addDays(2), oppList[0].CloseDate);
+        //System.assertEquals('IE', oppList[0].ProductSegmentCompetitor__c);
+        //System.assertEquals(pricebook.Id, oppList[0].Pricebook2Id);
+        
+    }
+    
+    // 鏈叧闂浠锋彃鍏ュ拰鏇存柊
+    static testMethod void myTest2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+        
+        List<Opportunity> oppList = [Select Id, CloseDate, ProductSegmentCompetitor__c, Pricebook2Id from Opportunity where Id = :opp.Id];
+        
+        //System.assertEquals(Date.today().addDays(2), oppList[0].CloseDate);
+        //System.assertEquals('IE', oppList[0].ProductSegmentCompetitor__c);
+        //System.assertEquals(pricebook.Id, oppList[0].Pricebook2Id);
+        
+        opp.ExpectedOrderDate__c = Date.today().addDays(3);
+        opp.ProductSegment__c = 'BS';
+        update opp;
+        
+        List<Opportunity> oppList2 = [Select Id, CloseDate, ProductSegmentCompetitor__c, Pricebook2Id from Opportunity where Id = :opp.Id];
+        
+        //System.assertEquals(Date.today().addDays(3), oppList2[0].CloseDate);
+        //System.assertEquals('BS', oppList2[0].ProductSegmentCompetitor__c);
+        
+        // 鏃犻瀹氫笅鍗曟棩
+        Opportunity opp2 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp2;
+        
+        List<Opportunity> oppList3 = [Select Id, CloseDate, ProductSegmentCompetitor__c, Pricebook2Id from Opportunity where Id = :opp2.Id];
+        
+        //System.assertEquals(Date.today().addDays(-2).addMonths(6), oppList3[0].CloseDate);
+        //System.assertEquals('IE', oppList3[0].ProductSegmentCompetitor__c);
+        //System.assertEquals(pricebook.Id, oppList3[0].Pricebook2Id);
+        
+        opp2.NewInquiryDate__c = Date.today().addDays(-3);
+        opp2.ProductSegment__c = 'BS';
+        update opp2;
+        
+        List<Opportunity> oppList4 = [Select Id, CloseDate, ProductSegmentCompetitor__c, Pricebook2Id from Opportunity where Id = :opp2.Id];
+        
+        //System.assertEquals(Date.today().addDays(-3).addMonths(6), oppList4[0].CloseDate);
+        //System.assertEquals('BS', oppList4[0].ProductSegmentCompetitor__c);
+    }
+    //@isTest(SeeAllData=true)
+    static testMethod void myTest3() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectForeignCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'ForeignCompany'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        /*PriceBook2 pricebook1 = ControllerUtil.getStandardPricebook();
+        Id pricebookId = pricebook1.id;*/
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+        
+        /*Pricebook2 pricebook =  [select Id from PriceBook2 where ProductSegment__c = 'IE' and
+         TradeType__c = 'Taxation' and SalesChannel__c = 'direct' and MachineParts__c = 'Machine' and  isActive = true limit 1];
+*/
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.IsActive = true;
+        
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.IsActive = true;
+        
+        insert new Product2[] {product1,product2,product3};
+        
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+
+        );
+        
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+
+        
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        
+        Account specialDeliveryAddress1 = new Account(Name = '*',FacilityName__c='specialDeliveryAddress1',PostCode__c = '123456');
+        Account specialDeliveryAddress2 = new Account(Name = '*',FacilityName__c='specialDeliveryAddress2',PostCode__c = '123456');
+        Account specialDeliveryAddress3 = new Account(Name = '*',FacilityName__c='specialDeliveryAddress3',PostCode__c = '123456');
+        Account foreignTradeCompany1 = new Account(Name = '*',FacilityName__c='foreignTradeCompany1',PostCode__c = '123456',RecordTypeId = rectForeignCompany[0].Id);
+        Account foreignTradeCompany2 = new Account(Name = '*',FacilityName__c='foreignTradeCompany2',PostCode__c = '123456',RecordTypeId = rectForeignCompany[0].Id);
+        Account foreignTradeCompany3 = new Account(Name = '*',FacilityName__c='foreignTradeCompany3',PostCode__c = '123456',RecordTypeId = rectForeignCompany[0].Id);
+        insert new Account[] {specialDeliveryAddress1,specialDeliveryAddress2,specialDeliveryAddress3,foreignTradeCompany1,foreignTradeCompany2,foreignTradeCompany3};
+        
+        User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'User20210519@test.com';
+        user.Username = 'User20210519@test222.com';
+        user.CommunityNickname = 'test01';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+        
+        Date day1 = Date.today();
+        Date day2 = day1.addDays(-1);
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Prospect Created';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'direct';
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Taxation';
+        opp.Machine_Parts__c = 'Machine';
+        opp.SpecialDeliveryAddress__c = specialDeliveryAddress1.Id;
+        opp.ForeignTradeCompany__c = foreignTradeCompany1.Id;
+  
+        insert opp;
+        
+        OpportunityLineItem oli = new OpportunityLineItem();
+        oli.OpportunityId = opp.Id;
+        oli.Quantity = 2;
+        oli.UnitPrice = 111;
+        oli.Description = 'test';
+        oli.PricebookEntryId = entry1.Id;
+        
+        insert oli;
+        
+        opp.LeadSource = 'LeadSource';
+        opp.BudgetAmount__c = 222;
+        opp.CancelReasonText__c = 'CancelReasonText__c';
+        opp.CancelReason__c = 'CancelReason__c';
+        opp.CompetitorCompany__c = 'CompetitorCompany__c';
+        opp.Competitor_Product__c = 'Competitor_Product__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8__c';
+        opp.CompetitorProductCode__c = 'CompetitorProductCode__c';
+        opp.CompetitorProductCode2__c = 'CompetitorProductCode2__c';
+        opp.CompetitorProductCode3__c = 'CompetitorProductCode3__c';
+        opp.CompetitorProductCode4__c = 'CompetitorProductCode4__c';
+        opp.CompetitorProductCode5__c = 'CompetitorProductCode5__c';
+        opp.CompetitorProductCode6__c = 'CompetitorProductCode6__c';
+        opp.CompetitorProductCode7__c = 'CompetitorProductCode7__c';
+        opp.CompetitorProductCode8__c = 'CompetitorProductCode8__c';
+        opp.DealerSalesStaffName__c = 'DealerSalesStaffName__c';
+        opp.DealerService__c = 'DealerService__c';
+        opp.ExpectedDeliveryDate__c = day2;
+        opp.ExpectedOrderDate__c = day2;
+        opp.InquiryResult__c = 'InquiryResult__c';
+        opp.InquiryResultCancel__c = null;
+        opp.InquiryResultLost__c = null;
+        opp.InquiryResultOrder__c = null;
+        opp.LostAmount__c = 222;
+        opp.LostCompetitorProduct__c = 'LostCompetitorProduct__c';
+        opp.LostReasonText__c = 'LostReasonText__c';
+        opp.LostReason__c = 'LostReason__c';
+        opp.NewInquiryDate__c = day2;
+        opp.Phase1Date__c = day2;
+        opp.Phase2Date__c = day2;
+        opp.Phase3Date__c = day2;
+        opp.SalesChannel__c = 'direct';
+        opp.SubDealer__c = 'SubDealer__c';
+        opp.TradeType__c = 'Taxation';
+        opp.Machine_Parts__c = 'Machine';
+        opp.SpecialDeliveryAddress__c = specialDeliveryAddress2.Id;
+        opp.ForeignTradeCompany__c = foreignTradeCompany2.Id;
+        
+        
+        opp.OwnerId = user.Id;
+        
+        update opp;
+        
+        oli.Quantity = 3;
+        oli.UnitPrice = 222;
+        oli.Description = 'test1';
+        
+        update oli;
+        
+        opp.LeadSource_D__c = 'newOpp.LeadSource';
+        opp.Budget_Amount_D__c = 111;
+        opp.Cancel_Reason_Text_D__c = 'newOpp.CancelReasonText__c';
+        opp.Cancel_Reason_D__c = 'newOpp.CancelReason__c';
+        opp.Competitor_Company_D__c = 'newOpp.CompetitorCompany__c';
+        opp.Competitor_Product_D__c = 'newOpp.Competitor_Product__c';
+        opp.Competitor_Product2_D__c = 'newOpp.Competitor_Product2__c';
+        opp.Competitor_Product3_D__c = 'newOpp.Competitor_Product3__c';
+        opp.Competitor_Product4_D__c = 'newOpp.Competitor_Product4__c';
+        opp.Competitor_Product5_D__c = 'newOpp.Competitor_Product5__c';
+        opp.Competitor_Product6_D__c = 'newOpp.Competitor_Product6__c';
+        opp.Competitor_Product7_D__c = 'newOpp.Competitor_Product7__c';
+        opp.Competitor_Product8_D__c = 'newOpp.Competitor_Product8__c';
+        opp.Competitor_Product_Code_D__c = 'newOpp.CompetitorProductCode__c';
+        opp.Competitor_Product_Code2_D__c = 'newOpp.CompetitorProductCode2__c';
+        opp.Competitor_Product_Code3_D__c = 'newOpp.CompetitorProductCode3__c';
+        opp.Competitor_Product_Code4_D__c = 'newOpp.CompetitorProductCode4__c';
+        opp.Competitor_Product_Code5_D__c = 'newOpp.CompetitorProductCode5__c';
+        opp.Competitor_Product_Code6_D__c = 'newOpp.CompetitorProductCode6__c';
+        opp.Competitor_Product_Code7_D__c = 'newOpp.CompetitorProductCode7__c';
+        opp.Competitor_Product_Code8_D__c = 'newOpp.CompetitorProductCode8__c';
+        opp.Dealer_Sales_Staff_Name_D__c = 'newOpp.DealerSalesStaffName__c';
+        opp.Dealer_Service_D__c = 'newOpp.DealerService__c';
+        opp.Expected_Delivery_Date_D__c = day1;
+        opp.Expected_Order_Date_D__c = day1;
+        opp.Inquiry_Result_D__c = 'newOpp.InquiryResult__c';
+        opp.Inquiry_Result_Cancel_D__c = null;
+        opp.Inquiry_Result_Lost_D__c = null;
+        opp.Inquiry_Result_Order_D__c = null;
+        opp.Lost_Amount_D__c = 111;
+        opp.Lost_Competitor_Product_D__c = 'newOpp.LostCompetitorProduct__c';
+        opp.LostReasonText_D__c = 'newOpp.LostReasonText__c';
+        opp.LostReason_D__c = 'newOpp.Lostreason__c';
+        opp.New_Inquiry_Date_D__c = day1;
+        opp.Phase1Date_D__c = day1;
+        opp.Phase2Date_D__c = day1;
+        opp.Phase3Date_D__c = day1;
+        opp.Sales_Channel_D__c = 'direct';
+        opp.Sub_Dealer_D__c = 'newOpp.SubDealer__c';
+        opp.Trade_Type_D__c = 'Taxation';
+        opp.Machine_Parts_D__c = 'Machine';
+        opp.SpecialDeliveryAddress_D__c= specialDeliveryAddress3.Id;
+        opp.ForeignTradeCompany_D__c = foreignTradeCompany3.Id;
+        
+        opp.DealerSelectOwner__c = UserInfo.getUserId();
+        
+        update opp;
+        
+        oli.QuantityD__c = 2;
+        oli.UnitPriceD__c = 111;
+        oli.DescriptionD__c = 'test';
+        oli.DealerSelectProduct__c = product1.Id;
+        
+        update oli;
+        
+        opp.ApprovalStatus_D__c = 'Completed';
+        update opp;
+        opp.ApprovalStatus_D__c = 'Submit';
+        update opp;
+        opp.ApprovalStatus_D__c = 'Reject';
+        update opp;
+
+        opp.ApprovalStatus_D__c = 'Completed';
+        update opp;
+        opp.ApprovalStatus_D__c = 'Submit';
+        update opp;
+        opp.ApprovalStatus_D__c = 'Pass';
+        update opp;
+    }
+
+    static testMethod void myTest4() {
+
+        StaticParameter.OpportunityTriggerIsUpdate = true;
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+           
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+        
+        opp.Phase1Date_D__c = Date.today();
+        update opp;
+
+        opp.Phase2Date_D__c = Date.today();
+        update opp;
+
+        opp.StageName = 'Phase3';
+        update opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+        );
+        insert role;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            Status__c = 'Active',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            IE_SP8__c = true,
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+        opp.Name = 'test';
+        update opp;
+    }
+
+    static testMethod void myTest5() {
+        
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'User202105191300@test.com';
+        user.Username = 'User202105191300@test222.com';
+        user.CommunityNickname = 'test01';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+           
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+        Opportunity oppNew = new Opportunity();
+        oppNew.Name = 'test opp';
+        oppNew.AccountId = accIE.Id;
+        oppNew.RecordTypeId = rectOpp[0].Id;
+        oppNew.OwnerId = user.Id;
+        oppNew.StageName = 'Prospect Created';
+        oppNew.CancelReason__c = 'Inquiry repeat';
+        oppNew.Cancel_reason_D__c = 'Inquiry repeat';
+        oppNew.CurrencyIsoCode = 'CNY';
+        oppNew.ProductSegment__c = 'IE';
+        oppNew.CloseDate = Date.today();
+        oppNew.NewInquiryDate__c = Date.today().addDays(-2);
+        oppNew.ExpectedOrderDate__c = Date.today().addDays(2);
+        oppNew.TradeType__c = 'Taxation';
+        oppNew.SalesChannel__c = 'direct';
+        oppNew.Machine_Parts__c = 'Machine';
+        insert oppNew;
+        oppNew.Manager__c  = user.Id;
+        oppNew.Have_Computer__c = true;
+        oppNew.CanChangeOpp__c = true;
+        oppNew.Association_Opportunity__c = opp.Id;
+        update oppNew;
+        /*oppNew.Association_Opportunity__c = null;
+        update oppNew;*/
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityTriggerTest.cls-meta.xml b/scr/classes/OpportunityTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityUpdateSendEmailBatch.cls b/scr/classes/OpportunityUpdateSendEmailBatch.cls
new file mode 100644
index 0000000..a1c6031
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailBatch.cls
@@ -0,0 +1,178 @@
+global class OpportunityUpdateSendEmailBatch implements Database.Batchable<sObject>,Database.Stateful {
+    private List<String> idList = null;
+
+    global OpportunityUpdateSendEmailBatch() {
+       
+    }
+
+    global OpportunityUpdateSendEmailBatch(List<String> temp) {
+       idList = temp;
+    }
+
+    global Database.QueryLocator start(Database.BatchableContext bc) {
+        //姣忔棩鎵ц锛岃浠蜂粖鏃ユ湁鏇存柊銆佷笁涓湀鏈洿鏂般�佸叚涓湀鏈洿鏂颁笁绉嶆儏鍐靛彂閭欢鎻愰啋锛屼節涓湀鏈洿鏂拌浠峰彇娑堝苟鍙戦偖浠舵彁閱掋��
+        Date yesterDay = Date.today().addDays(-1);
+        if(idList != null && idList.size()!=0){
+            return Database.getQueryLocator([select Id,Name,IsSendEmail__c,IsUpdate__c,OppUpdateDate__c,ThreeMonths__c,SixMonths__c,NineMonths__c,Province__c,ProductSegment__c,OneYear__c,
+                OppUpdateAddress__c,Cancel_Fail_Approve__c,InquiryNumber__c,Cancel_reason_D__c,Cancel_Reason_Text_D__c,CancelReason__c,CancelReasonText__c 
+                from Opportunity where (((ProductSegment__c = 'NDT' or ProductSegment__c = 'ANI') and RecordTypeId = '012280000005hjO') or ProductSegment__c = 'RVI' or ProductSegment__c = 'IE' or ProductSegment__c = 'BS') and CreatedBy.IsActive = true 
+                and IsSendEmail__c=true and StageName != 'Closed Won' and StageName != 'Closed Lost' and StageName != 'Closed Cancel' and ((IsUpdate__c = true and OppUpdateDate__c > :yesterDay.addMonths(-3)) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-3) and OppUpdateDate__c > :yesterDay.addMonths(-6) and ThreeMonths__c = false) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-6) and OppUpdateDate__c > :yesterDay.addMonths(-9) and SixMonths__c = false) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-9) and OppUpdateDate__c > :yesterDay.addMonths(-12) and NineMonths__c = false) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-12) and OneYear__c = false)) and Id in :idList]);
+        }else{
+            return Database.getQueryLocator([select Id,Name,IsSendEmail__c,IsUpdate__c,OppUpdateDate__c,ThreeMonths__c,SixMonths__c,NineMonths__c,Province__c,ProductSegment__c,OneYear__c,
+                OppUpdateAddress__c,Cancel_Fail_Approve__c,InquiryNumber__c,Cancel_reason_D__c,Cancel_Reason_Text_D__c,CancelReason__c,CancelReasonText__c 
+                from Opportunity where (((ProductSegment__c = 'NDT' or ProductSegment__c = 'ANI') and RecordTypeId = '012280000005hjO') or ProductSegment__c = 'RVI' or ProductSegment__c = 'IE' or ProductSegment__c = 'BS') and CreatedBy.IsActive = true
+                and IsSendEmail__c=true and StageName != 'Closed Won' and StageName != 'Closed Lost' and StageName != 'Closed Cancel' and ((IsUpdate__c = true and OppUpdateDate__c > :yesterDay.addMonths(-3)) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-3) and OppUpdateDate__c > :yesterDay.addMonths(-6) and ThreeMonths__c = false) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-6) and OppUpdateDate__c > :yesterDay.addMonths(-9) and SixMonths__c = false) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-9) and OppUpdateDate__c > :yesterDay.addMonths(-12) and NineMonths__c = false) or 
+                (OppUpdateDate__c <= :yesterDay.addMonths(-12) and OneYear__c = false))]);
+        }
+    }
+
+    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
+        Date yesterDay = Date.today().addDays(-1);
+        List<Opportunity> oppList = new List<Opportunity>();
+        for(Sobject obj : scope){
+            Opportunity opp = (Opportunity)obj;
+            if(opp.IsUpdate__c == true && opp.OppUpdateDate__c == yesterDay){
+                if(opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI'){
+                    //鍒嗛噹涓嶅悓闇�瑕佸彂閫佸埌涓嶅悓鐨勪汉 NDT閮埥锛�00528000000YVMP ANI鏉庢枃鐝猴細00528000000YSSm
+                    String members = System.label.OppUpdateAddressMember;
+                    if (String.isNotBlank(members)) {
+                        if(opp.ProductSegment__c == 'NDT'){
+                            opp.OppUpdateAddress2__c = members.split('_')[0];
+                        }else if(opp.ProductSegment__c == 'ANI'){
+                            opp.OppUpdateAddress2__c = members.split('_')[1];
+                        }
+                    }
+                    String memberId = getMember(opp.ProductSegment__c,opp.Province__c);
+                    opp.OppUpdateAddress__c = memberId;
+                    if(memberId == '00528000000YVJk'){
+                       opp.OppUpdateAddress__c = '00528000006hJeB';
+                    }
+                    opp.IsUpdate__c = false;
+                    opp.IsUpdate_temp__c = true;
+                    oppList.add(opp);
+                    continue;
+                }
+                if(opp.ProductSegment__c == 'RVI'){
+                    opp.IsUpdate__c = false;
+                    opp.IsUpdate_temp__c = true;
+                    oppList.add(opp);
+                    continue;
+                }
+                
+            }
+            if(opp.OppUpdateDate__c <= yesterDay.addMonths(-3) && opp.OppUpdateDate__c > yesterDay.addMonths(-6) && opp.ThreeMonths__c == false){
+                opp.ThreeMonths_temp__c = true;
+                opp.ThreeMonths__c = true;
+                opp.AutoClosedDate__c = getAutoClosedDate(opp.ProductSegment__c,opp.OppUpdateDate__c);
+                oppList.add(opp);
+                continue;
+            }
+            if (opp.OppUpdateDate__c <= yesterDay.addMonths(-6) && opp.OppUpdateDate__c > yesterDay.addMonths(-9) && opp.SixMonths__c == false) {
+                opp.SixMonths_temp__c = true;
+                opp.SixMonths__c = true;
+                opp.AutoClosedDate__c = getAutoClosedDate(opp.ProductSegment__c,opp.OppUpdateDate__c);
+                oppList.add(opp);
+                continue;
+            }
+            if (opp.OppUpdateDate__c <= yesterDay.addMonths(-9) && opp.OppUpdateDate__c > yesterDay.addMonths(-12) && opp.NineMonths__c == false) {
+                opp.NineMonths_temp__c = true;
+                opp.NineMonths__c = true;
+                opp.AutoClosedDate__c = getAutoClosedDate(opp.ProductSegment__c,opp.OppUpdateDate__c);
+                if(opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI'){
+                    opp.IsSendEmail__c = false;
+                    opp.StageName = 'Closed Cancel';
+                    opp.Cancel_Fail_Approve__c = 'Pass';
+                    opp.Cancel_reason_D__c = 'Other';
+                    opp.Cancel_Reason_Text_D__c = '缂栧彿涓猴細'+opp.InquiryNumber__c+'鐨勮浠凤紝9涓湀鏈湁杩涘睍锛屽凡琚獵RM绯荤粺鑷姩鍙栨秷銆�';
+                    opp.CancelReason__c = 'Other';
+                    opp.CancelReasonText__c = '缂栧彿涓猴細'+opp.InquiryNumber__c+'鐨勮浠凤紝9涓湀鏈湁杩涘睍锛屽凡琚獵RM绯荤粺鑷姩鍙栨秷銆�';
+                    String memberId = getMember(opp.ProductSegment__c,opp.Province__c);
+                    opp.OppUpdateAddress__c = memberId;
+                    if(memberId == '00528000000YVJk'){
+                       opp.OppUpdateAddress__c = '00528000006hJeB';
+                    }
+                    
+                }
+                oppList.add(opp);
+                continue;
+            }
+            if(opp.OppUpdateDate__c <= yesterDay.addMonths(-12) && opp.OneYear__c == false){
+                if(opp.ProductSegment__c != 'NDT' && opp.ProductSegment__c != 'ANI'){
+                    opp.OneYear__c = true;
+                    opp.OneYear_temp__c = true;
+                    opp.IsSendEmail__c = false;
+                    opp.StageName = 'Closed Cancel';
+                    opp.Cancel_Fail_Approve__c = 'Pass';
+                    opp.Cancel_reason_D__c = 'Other';
+                    opp.Cancel_Reason_Text_D__c = '璇环缂栧彿'+opp.InquiryNumber__c+',璇环鍚嶇О'+opp.Name+'锛屽凡缁忔湁涓�骞存湭杩涜浠讳綍淇℃伅鏇存柊锛屽凡缁忕敱绯荤粺璋冩暣涓哄彇娑堢姸鎬侊紝涓嶈兘鍐嶈繘琛屼换浣曟搷浣滐紝璇蜂簡瑙o紝璋㈣阿';
+                    opp.CancelReasonText__c = '璇环缂栧彿'+opp.InquiryNumber__c+',璇环鍚嶇О'+opp.Name+'锛屽凡缁忔湁涓�骞存湭杩涜浠讳綍淇℃伅鏇存柊锛屽凡缁忕敱绯荤粺璋冩暣涓哄彇娑堢姸鎬侊紝涓嶈兘鍐嶈繘琛屼换浣曟搷浣滐紝璇蜂簡瑙o紝璋㈣阿';
+                    oppList.add(opp);
+                }
+            }
+        }
+
+        if(oppList.size() >0 ) update oppList;
+    }
+
+    global void finish(Database.BatchableContext BC) {
+
+    }
+
+    private Date getAutoClosedDate(String productSegment,Date oppUpdateDate){
+        if(productSegment == 'NDT' || productSegment == 'ANI'){
+            return oppUpdateDate.addMonths(9);
+        }else{
+            return oppUpdateDate.addMonths(12);
+        }
+    }
+
+    private String getMember(String type,String province){
+        if (String.isNotBlank(type) && String.isNotBlank(province)) {
+            if (type == 'NDT') {
+
+                String NDTGuanZhao = System.label.NDTGuanZhao;
+                String NDTLiuJianHua = System.label.NDTLiuJianHua;
+                String NDTPanWei = System.label.NDTPanWei;
+                String NDTYuDaZhi = System.label.NDTYuDaZhi;
+               
+                if(NDTGuanZhao.indexOf(province) != -1){
+                    return NDTGuanZhao.split('_')[1];
+                }
+                if(NDTLiuJianHua.indexOf(province) != -1){
+                    return NDTLiuJianHua.split('_')[1];
+                }
+                if(NDTPanWei.indexOf(province) != -1){
+                    return NDTPanWei.split('_')[1];
+                }
+                if(NDTYuDaZhi.indexOf(province) != -1){
+                    return NDTYuDaZhi.split('_')[1];
+                }
+            }else if (type == 'ANI') {
+                String ANIGuanZhao = System.label.ANIGuanZhao;
+                String ANILiuJianHua = System.label.ANILiuJianHua;
+                String ANIPanWei = System.label.ANIPanWei;
+                String ANIYuDaZhi = System.label.ANIYuDaZhi;
+                if(ANIGuanZhao.indexOf(province) != -1){
+                    return ANIGuanZhao.split('_')[1];
+                }
+                if(ANILiuJianHua.indexOf(province) != -1){
+                    return ANILiuJianHua.split('_')[1];
+                }
+                if(ANIPanWei.indexOf(province) != -1){
+                    return ANIPanWei.split('_')[1];
+                }
+                if(ANIYuDaZhi.indexOf(province) != -1){
+                    return ANIYuDaZhi.split('_')[1];
+                }
+            }
+        }
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityUpdateSendEmailBatch.cls-meta.xml b/scr/classes/OpportunityUpdateSendEmailBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityUpdateSendEmailBatchTest.cls b/scr/classes/OpportunityUpdateSendEmailBatchTest.cls
new file mode 100644
index 0000000..acb09b5
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailBatchTest.cls
@@ -0,0 +1,215 @@
+@isTest
+private class OpportunityUpdateSendEmailBatchTest {
+    static testMethod void testMethod1() {
+    	Date dateToday = Date.today();
+        List<RecordType> rectNDT = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+        Account accNDT = new Account(
+            Name = '*',
+            RecordTypeId = rectNDT[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer NDT',
+            FacilityName__c='abc',
+            Province__c = '鍐呰挋鍙�',
+            PostCode__c = '123456'
+        );
+        insert accNDT; 
+           
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp1 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accNDT.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            IsUpdate__c = true,
+            OppUpdateDate__c = dateToday.addDays(-1)
+        );
+        insert opp1;
+        Opportunity opp2 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accNDT.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            ThreeMonths__c = false,
+            OppUpdateDate__c = dateToday.addMonths(-4)
+        );
+        insert opp2;
+        Opportunity opp3 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accNDT.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            SixMonths__c = false,
+            OppUpdateDate__c = dateToday.addMonths(-7)
+        );
+        insert opp3;
+        Opportunity opp4 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accNDT.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            NineMonths__c = false,
+            OppUpdateDate__c = dateToday.addMonths(-10)
+        );
+        insert opp4;
+        List<String> oppList = new List<String>();
+        oppList.add(opp1.Id);
+        oppList.add(opp2.Id);
+        oppList.add(opp3.Id);
+        oppList.add(opp4.Id);
+        Database.executeBatch(new OpportunityUpdateSendEmailBatch(), 10);
+    }
+    static testMethod void testMethod2() {
+    	Date dateToday = Date.today();
+        List<RecordType> rectANI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        Account accANI = new Account(
+            Name = '*',
+            RecordTypeId = rectANI[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer ANI',
+            FacilityName__c='abc',
+            Province__c = '杈藉畞',
+            PostCode__c = '123456'
+        );
+        insert accANI; 
+           
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp1 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accANI.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'ANI',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            IsUpdate__c = true,
+            OppUpdateDate__c = dateToday.addMonths(-2)
+        );
+        insert opp1;
+        Opportunity opp2 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accANI.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'ANI',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            ThreeMonths__c = false,
+            OppUpdateDate__c = dateToday.addMonths(-4)
+        );
+        insert opp2;
+        Opportunity opp3 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accANI.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'ANI',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            SixMonths__c = false,
+            OppUpdateDate__c = dateToday.addMonths(-7)
+        );
+        insert opp3;
+        Opportunity opp4 = new Opportunity(
+            Name = 'test opp',
+            AccountId = accANI.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'ANIANI',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            IsSendEmail__c=true,
+            NineMonths__c = false,
+            OppUpdateDate__c = dateToday.addMonths(-10)
+        );
+        insert opp4;
+        List<String> oppList = new List<String>();
+        oppList.add(opp1.Id);
+        oppList.add(opp2.Id);
+        oppList.add(opp3.Id);
+        oppList.add(opp4.Id);
+        Database.executeBatch(new OpportunityUpdateSendEmailBatch(oppList), 10);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityUpdateSendEmailBatchTest.cls-meta.xml b/scr/classes/OpportunityUpdateSendEmailBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityUpdateSendEmailSTest.cls b/scr/classes/OpportunityUpdateSendEmailSTest.cls
new file mode 100644
index 0000000..0edbfdc
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailSTest.cls
@@ -0,0 +1,19 @@
+@isTest
+private class OpportunityUpdateSendEmailSTest {
+     static  testMethod void testExecute() {
+		 // This test runs a scheduled job at midnight Sept. 3rd. 2022
+        String CRON_EXP = '0 0 0 3 9 ? 2032';
+
+        System.Test.startTest();
+        // Schedule the test job
+        String jobId = system.schedule('OpportunityUpdateSendEmailSchedulable', CRON_EXP, new OpportunityUpdateSendEmailSchedulable());
+        // Get the information from the CronTrigger API object
+        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
+        // Verify the expressions are the same
+        System.assertEquals(CRON_EXP, ct.CronExpression);
+        // Verify the job has not run
+        System.assertEquals(0, ct.TimesTriggered);
+        // Verify the next time the job will run
+        System.assertEquals('2032-09-03 00:00:00', String.valueOf(ct.NextFireTime));
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityUpdateSendEmailSTest.cls-meta.xml b/scr/classes/OpportunityUpdateSendEmailSTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailSTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityUpdateSendEmailSchedulable.cls b/scr/classes/OpportunityUpdateSendEmailSchedulable.cls
new file mode 100644
index 0000000..a0eb093
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailSchedulable.cls
@@ -0,0 +1,5 @@
+global class OpportunityUpdateSendEmailSchedulable implements Schedulable {
+    global void execute(SchedulableContext sc) {
+        Id execBTId = Database.executeBatch(new OpportunityUpdateSendEmailBatch(), 10);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityUpdateSendEmailSchedulable.cls-meta.xml b/scr/classes/OpportunityUpdateSendEmailSchedulable.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OpportunityUpdateSendEmailSchedulable.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityVisitNotesController.cls b/scr/classes/OpportunityVisitNotesController.cls
new file mode 100644
index 0000000..821da10
--- /dev/null
+++ b/scr/classes/OpportunityVisitNotesController.cls
@@ -0,0 +1,116 @@
+public with sharing class OpportunityVisitNotesController {
+    String oldResponse;
+    // 璇环
+    public Opportunity ra { get; set; }
+    public Opportunity ra1 { get; set; }
+    public Opportunity cc { get; set; }
+    // 璇环ID
+    public Id raid { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    public String usertype { get; private set; }
+    
+
+    public OpportunityVisitNotesController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+    }
+
+    public OpportunityVisitNotesController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new Opportunity();
+        cc = new Opportunity();
+        usertype = UserInfo.getUserType();
+        List<Opportunity> raList = [select Id, Name, Visit_Notes__c from Opportunity where Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        ra1 = new Opportunity();
+        List<Opportunity> ra1List = [select Id, Name, Visit_Notes__c from Opportunity where Id = :raid];
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+        oldResponse = ra1.Visit_Notes__c;
+        ra1.Visit_Notes__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = ra1.Visit_Notes__c;
+        if (response == null || response.trim().length() == 0) {
+            ra1.Visit_Notes__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += ra1.Visit_Notes__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+   
+            ra1.Visit_Notes__c = temp;
+
+            update ra1;
+            ra1.Visit_Notes__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+            //messageNEW.Subject = '璁㈠崟' + ra.Name + '' + 'OCN鍐呴儴鐣欒█';
+            messageNEW.Subject = '璇环 ' + ra1.Name + '-鎷滆璁板綍';
+            messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');          
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityVisitNotesController.cls-meta.xml b/scr/classes/OpportunityVisitNotesController.cls-meta.xml
new file mode 100644
index 0000000..8b061c8
--- /dev/null
+++ b/scr/classes/OpportunityVisitNotesController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityVisitNotesControllerTest.cls b/scr/classes/OpportunityVisitNotesControllerTest.cls
new file mode 100644
index 0000000..4f0ecda
--- /dev/null
+++ b/scr/classes/OpportunityVisitNotesControllerTest.cls
@@ -0,0 +1,69 @@
+@isTest
+public with sharing class OpportunityVisitNotesControllerTest {
+
+    static testMethod void myTest1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            Visit_Notes__c = ''
+            
+        );
+        insert opp;
+
+       
+
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OpportunityVisitNotesPopUp?raid=' + opp.Id );
+        System.Test.setCurrentPage(page);
+
+        OpportunityVisitNotesController controller = new OpportunityVisitNotesController();
+
+        //鍙栧緱璇环鍗�
+        Opportunity opp1 = [select Id, Name, Visit_Notes__c from Opportunity where Id = :opp.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        System.assertEquals('', controller.ra1.Visit_Notes__c);
+
+        //鍙戦�佹寜閽�
+        controller.ra1.Visit_Notes__c = 'test1';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+
+        // StandardController
+        controller = new OpportunityVisitNotesController(new ApexPages.StandardController(opp));
+        controller.init();
+    }
+
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityVisitNotesControllerTest.cls-meta.xml b/scr/classes/OpportunityVisitNotesControllerTest.cls-meta.xml
new file mode 100644
index 0000000..8b061c8
--- /dev/null
+++ b/scr/classes/OpportunityVisitNotesControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityWebService.cls b/scr/classes/OpportunityWebService.cls
new file mode 100644
index 0000000..8b52fc2
--- /dev/null
+++ b/scr/classes/OpportunityWebService.cls
@@ -0,0 +1,703 @@
+global class OpportunityWebService {
+
+    WebService static String check(String oppId) {
+        String str = '1';
+        List<OpportunityLineItem> oliList = [select id, Product2.If_Exempt_Product__c, Product2.If_Radiation_Product__c, Opportunity.DealerId__c from OpportunityLineItem where opportunityId = :oppId];
+        Boolean hasA = false;
+        for (OpportunityLineItem oli : oliList) {
+            if (oli.Product2.If_Exempt_Product__c == false && oli.Product2.If_Radiation_Product__c == true) {
+                hasA = true;
+            }
+        }
+        if (hasA == true) {
+            str =  LicenseCheckUtil.LicenseCheck1(oliList[0].Opportunity.DealerId__c);
+        }
+        return str;
+    }
+
+    WebService static String checkOly() {
+        return LicenseCheckUtil.LicenseCheckOly();
+    }
+
+    WebService static String UpdateStageName(String opportunityId, String targetStageName) {
+        Opportunity opp = new Opportunity();
+        opp.Id = opportunityId;
+        opp.StageName = targetStageName;
+        try {
+            StaticParameter.StageProgressBarUpdate = true;
+            update opp;
+        } catch (Exception ex) {
+            return ex.getMessage();
+        }
+
+        return '1';
+    }
+
+    WebService static String UpdateShare(String opportunityId, String userId) {
+        try {
+            List<OpportunityShare> osList = [select Id, OpportunityId, UserOrGroupId, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId = :opportunityId and UserOrGroupId = :userId and RowCause = 'Team' and OpportunityAccessLevel = 'Read'];
+            for (OpportunityShare os : osList) {
+                os.OpportunityAccessLevel = 'Edit';
+            }
+            if (osList.size() > 0) {
+                update osList;
+            }
+        } catch (Exception ex) {
+            return ex.getMessage();
+        }
+
+        return '1';
+    }
+
+    WebService static String Upload2Sap(String opportunityId, String quoteNo, String quoteId) {
+        add();
+        Savepoint sp = Database.setSavepoint();
+        Opportunity oppor = [select id, AccountId, Dealer__r.DummyDealer__c, Dealer__r.ParentID, Account.MarketVerticals__c, Trade_Type_D__c from Opportunity where id = :opportunityId];
+        if (oppor.Account.MarketVerticals__c == 'Clinical' && oppor.Trade_Type_D__c == 'Taxation') {
+            if (oppor.Dealer__r.DummyDealer__c == true) {
+                String backStr = LicenseCheckUtil.LicenseCheck(oppor.AccountId);
+                if (backStr != '1') {
+                    return backStr + ',涓嶈兘涓婁紶鎶ヤ环';
+                }
+            } else {
+                String backStr = LicenseCheckUtil.LicenseCheck(oppor.Dealer__r.ParentID);
+                if (backStr != '1') {
+                    return backStr + ',涓嶈兘涓婁紶鎶ヤ环';
+                }
+            }
+        }
+        try {
+            Opportunity opp = new Opportunity();
+            opp.Id = opportunityId;
+            opp.the_Upload_of_quotation_number__c = quoteNo;
+            update opp;
+
+            Quote quo = new Quote();
+            quo.Id = quoteId;
+            quo.Is_upload__c = true;
+            update quo;
+
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            return ex.getMessage();
+        }
+
+        return '1';
+    }
+
+
+    WebService static void batch(String oppId){
+
+        System.debug('$$$$$$$$$$'+oppId);
+        List<String> idList = new List<String>();
+        idList.add(oppId);
+        Database.executeBatch(new OpportunityUpdateSendEmailBatch(idList), 10);
+    }
+
+    WebService static String checkUpperLimitOfSales(String oppId, String dealerId) {
+        String result = '';
+        String olympusAccountId = System.label.Olympus_Id;
+        Map<String, Integer> getModelQuantityMap = RadiationUtil.GetOpportunityLineMap(oppId);
+        String errorStr = RadiationUtil.GetCertificationDetail(dealerId, getModelQuantityMap);
+        if (errorStr != '') {
+            return '-1';
+        }
+        String accountDealerErrorMessage = RadiationUtil.updateCertificationDetails(dealerId, null, getModelQuantityMap, false);
+        //String olympusDealerErrorMessage = RadiationUtil.updateCertificationDetails(olympusAccountId, null, getModelQuantityMap, false);
+        result = accountDealerErrorMessage ;
+        //String flage = LicenseCheckUtil.LicenseCheckOly();
+        Boolean temp = result.startsWith('浣犱笉鑳�');
+        if (temp) {
+            return '-1';
+        } else {
+            return result;
+        }
+    }
+
+
+    WebService static String checkUpperLimitOfSalesOly(String oppId, String dealerId) {
+        String result = '';
+        String olympusAccountId = System.label.Olympus_Id;
+        Map<String, Integer> getModelQuantityMap = RadiationUtil.GetOpportunityLineMap(oppId);
+        /*String errorStr = RadiationUtil.GetCertificationDetail(oppId,getModelQuantityMap);
+        if(errorStr != ''){
+           return '-1';
+        }
+        String accountDealerErrorMessage = RadiationUtil.updateCertificationDetails(dealerId, null, getModelQuantityMap, false);*/
+        String olympusDealerErrorMessage = RadiationUtil.updateCertificationDetails(olympusAccountId, null, getModelQuantityMap, false);
+        result = olympusDealerErrorMessage == '' ? '' : '浠櫙閫氬彲閿�鍞暟閲忎笉瓒�' ;
+        //String flage = LicenseCheckUtil.LicenseCheckOly();
+        Boolean temp = result.startsWith('浣犱笉鑳�');
+        if (temp) {
+            return '-1';
+        } else {
+            return result;
+        }
+    }
+
+    WebService static String checkOrderStatus(String oppId, String stageName, String creuser, String owner) {
+        String temp = '1';
+        Order ord = new Order();
+        List<Order> ordList = new List<Order>();
+        ordList = [select id, SAP_Order__c, ProductSegment__c, Is_TAX__c, SAP_Contract__c, ApproveStatus__c, CreatedById from Order where OpportunityId = : oppId and Status__c = 'Active'];
+         String userId = UserInfo.getUserId().substring(0, 15);
+         String roleId = UserInfo.getUserRoleId().substring(0, 15);
+        if (ordList.size() > 0) {
+            ord = ordList[0];
+           
+            if ( (ord.ApproveStatus__c == 'CancelPass' ||  ord.ApproveStatus__c == 'OrderDraft' || ord.ApproveStatus__c  == 'Draft' || ord.ApproveStatus__c == 'Reject') &&  (creuser == userId || owner == userId)) {
+                StaticParameter.StageProgressBarUpdate = true;
+
+                
+
+                if (userId == '005280000037mrQ' || userId == '00528000002OAvH' || userId == '00528000000YSdB' ||
+                        roleId == '00E0K000001ywwz' || roleId == '00E0K000001jGiM' || roleId == '00E0K000001jGib' ||
+                        roleId == '00E0K000001ywgS' || roleId == '00E28000000knAm' || roleId == '00E28000000knAr' ||
+                        roleId == '00E28000000aKzn' || roleId == '00E0K000001jGhn' || roleId == '00E0K000001jGhs' ||
+                        roleId == '00E0K000001ywgN' || roleId == '00E0K000001PWuh' || roleId == '00E0K000001PWum' ||
+                        roleId == '00E0K000001PWur' || roleId == '00E280000015xus' || roleId == '00E280000015xux' ||
+                        roleId == '00E28000000aKzs' || roleId == '00E0K000001jGiC' || roleId == '00E0K000001jGiR' ||
+                        roleId == '00E0K000001ywgX' || roleId == '00E28000000knAc' || roleId == '00E28000000knAh' ||
+                        roleId == '00E28000000aKzx' || roleId == '00E28000000knAw' || roleId == '00E28000000knB1' ||
+                        roleId == '00E28000000aL02' || roleId == '00E28000000kjpX') {
+
+                    Opportunity opp = new Opportunity();
+                    opp.Id = oppId;
+                    opp.Cancel_Fail_Approve__c = 'Pass';
+                    opp.StageName = stageName;
+
+                    try {
+                        StaticParameter.StageProgressBarUpdate = true;
+                        update opp;
+                    } catch (Exception ex) {
+                        return ex.getMessage();
+                    }
+                } else {
+                    temp = '0';
+                }
+            } else {
+                temp = '0';
+            }
+        } else {
+            if  ((userId == '005280000037mrQ' || userId == '00528000002OAvH' || userId == '00528000000YSdB' ||
+                    roleId == '00E0K000001ywwz' || roleId == '00E0K000001jGiM' || roleId == '00E0K000001jGib' ||
+                    roleId == '00E0K000001ywgS' || roleId == '00E28000000knAm' || roleId == '00E28000000knAr' ||
+                    roleId == '00E28000000aKzn' || roleId == '00E0K000001jGhn' || roleId == '00E0K000001jGhs' ||
+                    roleId == '00E0K000001ywgN' || roleId == '00E0K000001PWuh' || roleId == '00E0K000001PWum' ||
+                    roleId == '00E0K000001PWur' || roleId == '00E280000015xus' || roleId == '00E280000015xux' ||
+                    roleId == '00E28000000aKzs' || roleId == '00E0K000001jGiC' || roleId == '00E0K000001jGiR' ||
+                    roleId == '00E0K000001ywgX' || roleId == '00E28000000knAc' || roleId == '00E28000000knAh' ||
+                    roleId == '00E28000000aKzx' || roleId == '00E28000000knAw' || roleId == '00E28000000knB1' ||
+                    roleId == '00E28000000aL02' || roleId == '00E28000000kjpX') &&  (creuser == userId || owner == userId)) {
+
+                Opportunity opp = new Opportunity();
+                opp.Id = oppId;
+                opp.Cancel_Fail_Approve__c = 'Pass';
+                opp.StageName = stageName;
+
+                try {
+                    StaticParameter.StageProgressBarUpdate = true;
+                    update opp;
+                } catch (Exception ex) {
+                    return ex.getMessage();
+                }
+            } else {
+                temp = '0';
+            }
+        }
+        return temp;
+
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    private static void add() {
+        Integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityWebService.cls-meta.xml b/scr/classes/OpportunityWebService.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OpportunityWebServiceTest.cls b/scr/classes/OpportunityWebServiceTest.cls
new file mode 100644
index 0000000..cca142b
--- /dev/null
+++ b/scr/classes/OpportunityWebServiceTest.cls
@@ -0,0 +1,99 @@
+@isTest
+private class OpportunityWebServiceTest {
+
+    static testMethod void myUnitTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        insert acc1;
+        
+        Opportunity opp1 = new Opportunity(
+            name = 'test opp1',
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            AccountId = acc1.Id,
+            StageName = 'Prospect Created',
+            SalesChannel__c = 'direct',
+            CloseDate = Date.valueof('1900-01-01')
+        );
+        insert opp1;
+        
+        String rs = '';
+        rs = OpportunityWebService.UpdateStageName(opp1.Id, 'Phase1');
+        System.assertEquals('1', rs);
+        
+        List<Opportunity> oppList = [select Id, StageName from Opportunity where Id = :opp1.Id];
+        System.assertEquals('Phase1', oppList[0].StageName);
+    }
+    
+    static testMethod void myUnitTest2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            PostCode__c='000000'
+        );
+        insert acc1;
+        
+        Opportunity opp1 = new Opportunity(
+            name = 'test opp1',
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            AccountId = acc1.Id,
+            StageName = 'Prospect Created',
+            SalesChannel__c = 'direct',
+            CloseDate = Date.valueof('1900-01-01')
+        );
+        insert opp1;
+        
+        User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'test@test.com';
+        user.Username = 'test111@test222.com';
+        user.CommunityNickname = 'test';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+        
+        OpportunityTeamMember otm = new OpportunityTeamMember(
+            opportunityId = opp1.Id,
+            userId = user.Id,
+            teamMemberRole = 'Sales Manager'
+        );
+        insert otm;
+        
+        String rs = '';
+        rs = OpportunityWebService.UpdateShare(opp1.Id, user.Id);
+        System.assertEquals('1', rs);
+        
+        List<OpportunityTeamMember> otmList = [select Id, OpportunityAccessLevel from OpportunityTeamMember where Id = :otm.Id];
+        System.assertEquals('Edit', otmList[0].OpportunityAccessLevel);
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp1.Id
+        );
+        insert quo;
+
+        rs = '';
+        rs = OpportunityWebService.Upload2Sap(opp1.Id, quo.Name, quo.Id);
+        System.assertEquals('1', rs);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OpportunityWebServiceTest.cls-meta.xml b/scr/classes/OpportunityWebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OpportunityWebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderDivisionController.cls b/scr/classes/OrderDivisionController.cls
new file mode 100644
index 0000000..407b3ba
--- /dev/null
+++ b/scr/classes/OrderDivisionController.cls
@@ -0,0 +1,1193 @@
+public without sharing class OrderDivisionController {
+    public static Boolean OrderDivision = false;
+    // 閾炬帴鍦板潃
+    public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+    // 鍚堝悓ID銆佺敾闈㈤」鐩�
+    public Id odrId {get;set;}
+    public Order odr {get;set;}
+    public List<LineInfo> lineinfo {get;set;}
+
+    public boolean is_IE {get;set;}
+    public Decimal sh_o {get;set;}
+    public Decimal sh_d {get;set;}
+
+    private Decimal total;
+    private Decimal total_o;
+    private Decimal total_d;
+
+    public Boolean specialDealer { get; set; }
+    //public String testlog {get;set;}
+
+    public OrderDivisionController() {
+        // 鍩虹Url
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        // 杩斿洖鍦板潃url
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+        // 鍚堝悓ID
+        if (odrId == null) {
+            odrId = System.currentPageReference().getParameters().get('odrId');
+        }
+        // 鐢婚潰椤圭洰鍒濆鍖�
+        lineinfo = new List<LineInfo>();
+    }
+
+    public OrderDivisionController(ApexPages.StandardController controller) {
+        this();
+    }
+
+    public void init() {
+        // 鍚堝悓ID妫�鏌�
+        if (odrId == null) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鍚堝悓涓嶅瓨鍦ㄣ��'));
+            return;
+        }
+        // 鍙栧緱鍚堝悓淇℃伅
+        Schema.DescribeSobjectResult d_odr = Order.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_odr_map = d_odr.fields.getMap();
+        String soql_odr = 'select ';
+        String fields_odr = '';
+        for (String field : d_odr_map.keySet()) {
+            if (fields_odr.length() > 0) {
+                fields_odr += ', ';
+            }
+            fields_odr += field;
+        }
+        fields_odr += ', Opportunity.IE_ShippingHandling__c';
+        soql_odr += fields_odr;
+        soql_odr += ' from Order where Id = \'' + odrId + '\'';
+        //List<Order> odrList = [select Id, OpportunityId, QuoteId from Order where Id = :odrId];
+        List<Order> odrList = Database.query(soql_odr);
+        if (odrList.size() == 0) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鍚堝悓涓嶅瓨鍦ㄣ��'));
+            return;
+        }
+        odr = odrList[0];
+
+        specialDealer = IfspecialDealer(odr.DealerId__c);
+        is_IE = false;
+        sh_o = 0;
+        sh_d = 0;
+        total = 0;
+        if (odr.ProductSegment__c == 'IE' || odr.ProductSegment__c == 'RVI'|| odr.ProductSegment__c == 'NDT'|| odr.ProductSegment__c == 'ANI') {
+            is_IE =true;
+            sh_o = odr.Opportunity.IE_ShippingHandling__c == null ? 0 : odr.Opportunity.IE_ShippingHandling__c;
+            total = odr.TotalAmount;
+            System.debug(total+'@@@@@@@@@@@'+sh_o);
+        }
+
+        // 鍙栧緱鍚堝悓浜у搧
+        List<OrderItem> oiList = new List<OrderItem>();
+        List<DecideQuoteProductSet__c> dqList = new List<DecideQuoteProductSet__c>();
+        if(odr.ProductSegment__c != 'BS'){
+            oiList = [select Id, QuoteLineItemId, Description, Quantity, PricebookEntry.Product2.Name,PricebookEntry.Product2.ProductCode,PricebookEntry.Product2.Product_ECCode__c,UnitPrice from OrderItem where OrderId = :odrId order by Id];
+        }else{
+            oiList = [select Id, QuoteLineItemId, Description, Quantity, PricebookEntry.Product2.Name,PricebookEntry.Product2.ProductCode,PricebookEntry.Product2.Product_ECCode__c,UnitPrice from OrderItem where OrderId = :odrId and ODISingleProduct__c = true order by Id];
+            dqList = [select Id,Name,OwnerId, DecideProductSet__c,DecideProductSetCount__c,DecideProductSetDiscount__c,DecideProductSetName__c,DecideProductSetUnivalence__c,DecideProductSetCode__c from DecideQuoteProductSet__c where DecideOrder__c = :odrId order by Id];
+        }
+        System.debug(dqList);
+        if (oiList.size() == 0 && odr.ProductSegment__c != 'BS') {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鍚堝悓浜у搧涓嶅瓨鍦ㄣ��'));
+            return;
+        }else if(odr.ProductSegment__c == 'BS' && oiList.size() == 0 && dqList.size() == 0 ){
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鍚堝悓浜у搧涓嶅瓨鍦ㄣ��'));
+            return; 
+        }
+        // 鐢婚潰椤圭洰鍋氭垚
+        Integer lineno = 0;
+        if(odr.ProductSegment__c != 'BS'){
+            for (OrderItem oi : oiList) {
+                lineno += 1;
+                LineInfo li = new LineInfo(lineno, oi);
+                lineinfo.add(li);
+            }
+        }else{
+            if(dqList.size() > 0){
+                for (DecideQuoteProductSet__c dqp : dqList){
+                    lineno += 1;
+                    LineInfo li = new LineInfo(lineno,dqp);
+                    LineInfo.add(li);
+                }
+            }
+
+            if(oiList.size() > 0){
+                for (OrderItem oi : oiList) {
+                    lineno += 1;
+                    LineInfo li = new LineInfo(lineno, oi);
+                    lineinfo.add(li);
+                } 
+            }
+        }
+    }
+
+    public PageReference saveBtn() {
+        tes();
+        // 鏄惁鍒嗗壊
+        boolean divideFlg = false;
+        total_o = 0;
+        total_d = 0;
+        List<String> setIDList = new List<String>();
+        if (sh_o < sh_d) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鎷嗗垎杩愪繚璐逛笉姝g‘銆�'));
+            return null;
+        }
+        for (LineInfo li : lineinfo) {
+            if (li.divideCnt != null && li.divideCnt > 0) {
+                if (li.divideCnt > li.oi.Quantity) {
+                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鎷嗗垎浜у搧鏁伴噺涓嶆纭紝琛岋細' + li.lineNo + '锛屾暟閲忥細' + li.divideCnt));
+                    return null;
+                }
+                divideFlg = true;
+            }
+
+            if(li.isSet){
+                setIDList.add(li.dqps.DecideProductSet__c);
+            }
+            if(!li.isSet){
+                Decimal dcnt = li.divideCnt != null && li.divideCnt > 0 ? li.divideCnt : 0;
+                total_o += (li.oi.Quantity - dcnt) * li.oi.UnitPrice;
+                total_d += dcnt * li.oi.UnitPrice;
+            }
+        }
+
+        if (divideFlg == false) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '娌℃湁鎷嗗垎鍚堝悓銆�'));
+            return null;
+        }
+
+        // 鍙栧緱鍘熻浠枫�佽浠蜂骇鍝併�佽浠疯仈绯讳汉
+        Opportunity opp = null;
+        List<OpportunityLineItem> oliList = null;
+        List<OpportunityContactRole> ocrList = null;
+        Schema.DescribeSobjectResult d_opp = Opportunity.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_opp_map = d_opp.fields.getMap();
+        String soql_opp = 'select ';
+        String fields_opp = '';
+        for (String field : d_opp_map.keySet()) {
+            if (fields_opp.length() > 0) {
+                fields_opp += ', ';
+            }
+            fields_opp += field;
+        }
+        soql_opp += fields_opp;
+        soql_opp += ' from Opportunity where Id = \'' + odr.OpportunityId + '\'';
+        //List<Opportunity> oppList = [select Id, SyncedQuoteId from Opportunity where Id = :odr.OpportunityId];
+        List<Opportunity> oppList = Database.query(soql_opp);
+        if (oppList.size() > 0) {
+            opp = oppList[0];
+            oliList = [select Id, PricebookEntryId, Product_Search__c, Product_Search__r.Id, Product_Search__r.Product__c from OpportunityLineItem where OpportunityId = :odr.OpportunityId];
+            ocrList = [select Id, OpportunityId, ContactId, Role, IsPrimary from OpportunityContactRole where OpportunityId = :odr.OpportunityId];
+        }
+        Map<String, Product_Search__c> psMap = new Map<String, Product_Search__c>();
+        if (oliList.size() > 0) {
+            for (OpportunityLineItem oli : oliList) {
+                psMap.put(oli.PricebookEntryId, oli.Product_Search__r);
+            }
+        }
+        // 鍙栧緱鍘熸姤浠枫�佹姤浠蜂骇鍝�
+        Quote quo = null;
+        List<QuoteLineItem> qliList = null;
+        Map<String, QuoteLineItem> qliMap = new Map<String, QuoteLineItem>();
+        Schema.DescribeSobjectResult d_quo = Quote.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_quo_map = d_quo.fields.getMap();
+        String soql_quo = 'select ';
+        String fields_quo = '';
+        for (String field : d_quo_map.keySet()) {
+            if (fields_quo.length() > 0) {
+                fields_quo += ', ';
+            }
+            fields_quo += field;
+        }
+        soql_quo += fields_quo;
+        soql_quo += ' from Quote where Id = \'' + (odr.QuoteId == null ? '' : odr.QuoteId) + '\'';
+        //List<Quote> quoList = [select Id from Quote where Id = :odr.QuoteId];
+        List<Quote> quoList = Database.query(soql_quo);
+        if (quoList.size() > 0) {
+            quo = quoList[0];
+            qliList = [select Id, Set__c, Description, Quantity, Discount, ListPrice, PricebookEntryId, QuoteId, UnitPrice, Custom_Price__c,SetName__c from QuoteLineItem where QuoteId = :odr.QuoteId];
+            for (QuoteLineItem qli : qliList) {
+                qliMap.put(qli.Id, qli);
+            }
+        }
+
+         //鑾峰彇浜у搧閰嶅
+        List<productSetItem__c> pSetItemList = new List<productSetItem__c>();
+        Map<String,List<productSetItem__c>> productSetMap = new Map<String,List<productSetItem__c>>();
+        Map<String,List<QuoteLineItem>> set_qliMap = new Map<String,List<QuoteLineItem>>();
+        if(setIDList.size() > 0){
+            pSetItemList = [select id,Count__c,product__c,productSet__r.Name from productSetItem__c where productSet__c in : setIDList order by productSet__c];
+            
+            for(productSetItem__c psi : pSetItemList){
+                if(productSetMap.size() != 0 && productSetMap.containsKey(psi.productSet__c)){
+                     productSetMap.get(psi.productSet__r.Name).add(psi);
+                }else{
+                    productSetMap.put(psi.productSet__r.Name, new List<productSetItem__c>());
+                    productSetMap.get(psi.productSet__r.Name).add(psi);
+                }
+            }
+
+            List<QuoteLineItem> tempList = qliMap.values();
+            System.debug(tempList);
+            for(QuoteLineItem qli : tempList){
+                System.debug(qli.SetName__c);
+                if(set_qliMap.size() !=0 && set_qliMap.containsKey(qli.SetName__c)){
+                    set_qliMap.get(qli.SetName__c).add(qli);
+                }else{
+                    set_qliMap.put(qli.SetName__c, new List<QuoteLineItem>());
+                    set_qliMap.get(qli.SetName__c).add(qli);
+                }
+            } 
+            
+        }
+        System.debug(set_qliMap);
+        // 鍒嗗壊淇濆瓨寮�濮�
+        Savepoint sp = Database.setSavepoint();
+        Map<Integer,String> old = new Map<Integer,String>();
+        Map<Integer,String> newd = new Map<Integer,String>();
+
+        Map<String,Decimal> qOld = new Map<String,Decimal>();
+        Map<String,Decimal> qnew = new Map<String,Decimal>();
+
+        // 璺宠繃璇环鐘舵�佸啓鍏ラ檺鍒�
+        StaticParameter.StageProgressBarUpdate = true;
+        OrderDivisionController.OrderDivision = true;
+        try {
+            // 澶嶅埗璇环
+            Opportunity ins_opp = opp.clone();
+            opp.Is_Decided__c = false;
+            if (is_IE) {
+                Decimal tmp = opp.IE_Custom_Price__c == null ? 0 : opp.IE_Custom_Price__c * total_o / total;
+                opp.IE_Custom_Price__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
+                tmp = opp.IE_local_cost__c == null ? 0 : opp.IE_local_cost__c * total_o / total;
+                opp.IE_local_cost__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
+                opp.IE_ShippingHandling__c = sh_o - sh_d;
+                System.debug(tmp+'@@@@@'+sh_d);
+            }
+            update opp;
+            System.debug('=====update opp');
+            ins_opp.Id = null;
+            ins_opp.SyncedQuoteId = null;
+            ins_opp.Is_Decided__c = false;
+            ins_opp.org_opportunity__c = opp.Id;
+            if (is_IE) {
+                Decimal tmp = ins_opp.IE_Custom_Price__c == null ? 0 : ins_opp.IE_Custom_Price__c * total_d / total;
+                ins_opp.IE_Custom_Price__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
+                tmp = ins_opp.IE_local_cost__c == null ? 0 : ins_opp.IE_local_cost__c * total_d / total;
+                ins_opp.IE_local_cost__c = tmp.setScale(2, System.RoundingMode.HALF_UP);
+                ins_opp.IE_ShippingHandling__c = sh_d;
+            }
+            insert ins_opp;
+            System.debug('=====ins_opp');
+            // 澶嶅埗璇环鑱旂郴浜�
+            List<OpportunityContactRole> ins_ocrList = new List<OpportunityContactRole>();
+            for (OpportunityContactRole ocr : ocrList) {
+                OpportunityContactRole ins_ocr = ocr.clone();
+                ins_ocr.Id = null;
+                ins_ocr.OpportunityId = ins_opp.Id;
+                ins_ocrList.add(ins_ocr);
+            }
+            if (ins_ocrList.size() > 0) insert ins_ocrList;
+            System.debug('=====ins_ocrList');
+            // 澶嶅埗鎶ヤ环
+            Quote ins_quo = null;
+            if (quo != null) {
+                ins_quo = quo.clone();
+                ins_quo.Id = null;
+                ins_quo.OpportunityId = ins_opp.Id;
+                ins_quo.Is_Decided__c = false;
+                for (Integer i = 1; i < = 30; i++) {
+                    Decimal qty = (Decimal) ins_quo.get('SetQty' + i + '__c');
+                    if (qty > 1) {
+                        ins_quo.put('SetQty' + i + '__c', 1);
+                    }
+                }
+            }
+            if (ins_quo != null) insert ins_quo;
+System.debug('=====ins_quo');
+            // 濡傛灉澶嶅埗鎶ヤ环锛屽垎鍓叉姤浠蜂骇鍝�
+            List<QuoteLineItem> upd_qliList = new List<QuoteLineItem>();
+            List<QuoteLineItem> del_qliList = new List<QuoteLineItem>();
+            List<QuoteLineItem> ins_qliList = new List<QuoteLineItem>();
+
+
+            Integer setNum = 1;
+            Integer allNum = 1;
+            if (ins_quo != null) {
+                Decimal oldSum = 0;
+                Decimal newSum = 0;
+                for (LineInfo li : lineinfo) {
+                    if(li.isSet == false){
+                        // 鍏ㄩ儴鍒嗗壊
+                        if (li.divideCnt == li.oi.Quantity) {
+                            // 鍒犻櫎鍘熸姤浠蜂骇鍝�
+                            QuoteLineItem del_qli = new QuoteLineItem(Id = li.oi.QuoteLineItemId);
+                            del_qliList.add(del_qli);
+                            // 鍏ㄩ儴鍒嗗壊鍒版柊鎶ヤ环
+                            QuoteLineItem ins_qli = qliMap.get(li.oi.QuoteLineItemId).clone();
+                            ins_qli.Id = null;
+                            ins_qli.QuoteId = ins_quo.Id;
+
+                            ins_qliList.add(ins_qli);
+                            newSum += ins_qli.Quantity * ins_qli.UnitPrice;
+                        // 閮ㄥ垎鍒嗗壊
+                        } else if (li.divideCnt > 0 && li.divideCnt <= li.oi.Quantity) {
+                            // 鏇存柊鍘熸姤浠蜂骇鍝佹暟閲�
+                            QuoteLineItem upd_qli = qliMap.get(li.oi.QuoteLineItemId);
+                            upd_qli.Quantity = upd_qli.Quantity - li.divideCnt;
+                            upd_qli.Custom_Price__c = upd_qli.Custom_Price__c == null ? 0 : upd_qli.Custom_Price__c * upd_qli.Quantity / (upd_qli.Quantity + li.divideCnt);
+                            upd_qliList.add(upd_qli);
+                            oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
+                            // 閮ㄥ垎鍒嗗壊鍒版柊鎶ヤ环
+                            QuoteLineItem ins_qli = qliMap.get(li.oi.QuoteLineItemId).clone();
+                            ins_qli.Id = null;
+                            ins_qli.QuoteId = ins_quo.Id;
+                            ins_qli.Custom_Price__c = ins_qli.Custom_Price__c * li.divideCnt / ins_qli.Quantity;
+                            ins_qli.Quantity = li.divideCnt;
+                            ins_qliList.add(ins_qli);
+                            newSum += ins_qli.Quantity * ins_qli.UnitPrice;
+                        // 鏈垎鍓�
+                        } else{
+                            // 涓嶅仛澶勭悊
+                            QuoteLineItem upd_qli = qliMap.get(li.oi.QuoteLineItemId);
+                            oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
+                        }
+                    }else{
+                        // 鍏ㄩ儴鍒嗗壊
+                        if (li.divideCnt == li.dqps.DecideProductSetCount__c){
+                            List<QuoteLineItem> tempList = set_qliMap.get(li.productName);
+                            System.debug(li.productName+'-----'+tempList);
+                            for(QuoteLineItem tempqli : tempList){
+                                QuoteLineItem del_qli = new QuoteLineItem(Id = tempqli.Id);
+                                del_qliList.add(del_qli);
+
+                                QuoteLineItem ins_qli = qliMap.get(tempqli.Id).clone();
+                                ins_qli.Id = null;
+                                ins_qli.SetName__c = li.productName;
+                                ins_qli.Set__c = 'set'+ (setNum>9?''+setNum:'0'+setNum);
+                                ins_qli.QuoteId = ins_quo.Id;
+                                ins_qli.SingleProduct__c = false;
+                                ins_qliList.add(ins_qli);
+                                newSum += ins_qli.Quantity * ins_qli.UnitPrice;
+                            }
+                            newd.put(setNum,li.productName);
+                            qnew.put(li.productName,li.divideCnt);
+                            setNum++;
+                        } else if (li.divideCnt > 0 && li.divideCnt <= li.dqps.DecideProductSetCount__c) {
+                            List<QuoteLineItem> tempList = set_qliMap.get(li.productName);
+                             System.debug(li.productName);
+                            for(QuoteLineItem tempqli : tempList){
+                                 // 鏇存柊鍘熸姤浠蜂骇鍝佹暟閲�
+                                QuoteLineItem upd_qli = qliMap.get(tempqli.Id);
+                                upd_qli.Quantity = upd_qli.Quantity - li.divideCnt;
+                                upd_qli.Custom_Price__c = upd_qli.Custom_Price__c == null ? 0 : upd_qli.Custom_Price__c * upd_qli.Quantity / (upd_qli.Quantity + li.divideCnt);
+                                upd_qli.Set__c = 'set'+ (allNum>9?''+allNum:'0'+allNum);
+                                upd_qliList.add(upd_qli);
+                                oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
+                                // 閮ㄥ垎鍒嗗壊鍒版柊鎶ヤ环
+                                QuoteLineItem ins_qli = qliMap.get(tempqli.Id).clone();
+                                ins_qli.Id = null;
+                                ins_qli.SingleProduct__c = false;
+                                ins_qli.SetName__c = li.productName;
+
+                                ins_qli.Set__c = 'set'+ (setNum>9?''+setNum:'0'+setNum);
+                                ins_qli.QuoteId = ins_quo.Id;
+                                ins_qli.Custom_Price__c = ins_qli.Custom_Price__c * li.divideCnt / ins_qli.Quantity;
+                                ins_qli.Quantity = li.divideCnt;
+                                ins_qliList.add(ins_qli);
+                                newSum += ins_qli.Quantity * ins_qli.UnitPrice; 
+                            }
+                            newd.put(setNum,li.productName);
+                            qnew.put(li.productName,li.divideCnt);
+                            old.put(allNum,li.productName);
+                            qOld.put(li.productName,li.dqps.DecideProductSetCount__c-li.divideCnt);
+                            setNum++;
+                            allNum++;
+                        } else{
+                            List<QuoteLineItem> tempList = set_qliMap.get(li.productName);
+                            System.debug(li.productName);
+                            for(QuoteLineItem tempqli : tempList){
+                                QuoteLineItem upd_qli = qliMap.get(tempqli.Id);
+                                upd_qli.Set__c = 'set'+ (allNum>9?''+allNum:'0'+allNum);
+                                oldSum += upd_qli.Quantity * upd_qli.UnitPrice;
+                            }
+
+                            old.put(allNum,li.productName);
+                            qOld.put(li.productName,li.dqps.DecideProductSetCount__c);
+                            allNum++;
+                        }
+                    }
+                    System.debug(upd_qliList);
+                    System.debug(del_qliList);
+                    System.debug(ins_qliList);
+                }
+
+                Decimal oldCustomPrice = quo.Custom_Price_Total_Text__c == null ? 0 : quo.Custom_Price_Total_Text__c * oldSum / quo.Subtotal;
+                Decimal newCustomPrice = quo.Custom_Price_Total_Text__c == null ? 0 : quo.Custom_Price_Total_Text__c * newSum / quo.Subtotal;
+
+                if (upd_qliList.size() > 0) update upd_qliList;
+                if (del_qliList.size() > 0) delete del_qliList;
+                if (ins_qliList.size() > 0) insert ins_qliList;
+System.debug('=====ins_qliList');
+
+                for (Integer i = 1; i < = 30; i++) {
+
+                    if(old.containsKey(i)){
+                        String temp = old.get(i);
+                        quo.put('SetName' + i + '__c', temp);
+                        quo.put('SetQty' + i + '__c', qOld.get(temp));
+                    }else{
+                        quo.put('SetName' + i + '__c', '');
+                        quo.put('SetQty' + i + '__c', null);
+                    }
+
+                    if(newd.containsKey(i)){
+                        String temp = newd.get(i);
+                        ins_quo.put('SetName' + i + '__c', temp);
+                        ins_quo.put('SetQty' + i + '__c', qnew.get(temp));
+                    }else{
+                        ins_quo.put('SetName' + i + '__c', '');
+                        ins_quo.put('SetQty' + i + '__c', null);
+                    }
+
+                }
+                quo.Custom_Price_Total_Text__c = oldCustomPrice;
+                quo.Is_Decided__c = false;
+                update quo;
+
+                ins_quo.Custom_Price_Total_Text__c = newCustomPrice;
+                update ins_quo;
+System.debug('=====update quo');
+
+                ins_opp.SyncedQuoteId = ins_quo.Id;
+                update ins_opp;
+System.debug('=====update ins_opp');
+            } else {
+                List<OpportunityLineItem> ins_oliList1 = new List<OpportunityLineItem>();
+                List<OpportunityLineItem> ins_oliList2 = new List<OpportunityLineItem>();
+                for (LineInfo li : lineinfo) {
+                    if (li.divideCnt == li.oi.Quantity) {
+                        OpportunityLineItem ins_oli2 = new OpportunityLineItem();
+                        ins_oli2.Description = li.oi.Description;
+                        ins_oli2.DescriptionD__c = li.oi.Description;
+                        ins_oli2.Quantity = li.divideCnt;
+                        ins_oli2.QuantityD__c = li.divideCnt;
+                        ins_oli2.PricebookEntryId = li.oi.PricebookEntryId;
+                        ins_oli2.UnitPrice = li.oi.UnitPrice;
+                        ins_oli2.UnitPriceD__c = li.oi.UnitPrice;
+                        ins_oli2.OpportunityId = ins_opp.Id;
+                        ins_oli2.IsNew__c = false;
+                        ins_oli2.Discount = ins_opp.Quote_Discount__c;
+                        ins_oli2.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
+                        ins_oli2.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
+                        ins_oliList2.add(ins_oli2);
+                    } else if (li.divideCnt > 0 && li.divideCnt <= li.oi.Quantity) {
+                        OpportunityLineItem ins_oli1 = new OpportunityLineItem();
+                        ins_oli1.Description = li.oi.Description;
+                        ins_oli1.DescriptionD__c = li.oi.Description;
+                        ins_oli1.Quantity = li.oi.Quantity - li.divideCnt;
+                        ins_oli1.QuantityD__c = li.oi.Quantity - li.divideCnt;
+                        ins_oli1.PricebookEntryId = li.oi.PricebookEntryId;
+                        ins_oli1.UnitPrice = li.oi.UnitPrice;
+                        ins_oli1.UnitPriceD__c = li.oi.UnitPrice;
+                        ins_oli1.OpportunityId = opp.Id;
+                        ins_oli1.IsNew__c = false;
+                        ins_oli1.Discount = opp.Quote_Discount__c;
+                        ins_oli1.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
+                        ins_oli1.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
+                        ins_oliList1.add(ins_oli1);
+
+                        OpportunityLineItem ins_oli2 = new OpportunityLineItem();
+                        ins_oli2.Description = li.oi.Description;
+                        ins_oli2.DescriptionD__c = li.oi.Description;
+                        ins_oli2.Quantity = li.divideCnt;
+                        ins_oli2.QuantityD__c = li.divideCnt;
+                        ins_oli2.PricebookEntryId = li.oi.PricebookEntryId;
+                        ins_oli2.UnitPrice = li.oi.UnitPrice;
+                        ins_oli2.UnitPriceD__c = li.oi.UnitPrice;
+                        ins_oli2.OpportunityId = ins_opp.Id;
+                        ins_oli2.IsNew__c = false;
+                        ins_oli2.Discount = ins_opp.Quote_Discount__c;
+                        ins_oli2.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
+                        ins_oli2.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
+                        ins_oliList2.add(ins_oli2);
+                    } else {
+                        OpportunityLineItem ins_oli1 = new OpportunityLineItem();
+                        ins_oli1.Description = li.oi.Description;
+                        ins_oli1.DescriptionD__c = li.oi.Description;
+                        ins_oli1.Quantity = li.oi.Quantity;
+                        ins_oli1.QuantityD__c = li.oi.Quantity;
+                        ins_oli1.PricebookEntryId = li.oi.PricebookEntryId;
+                        ins_oli1.UnitPrice = li.oi.UnitPrice;
+                        ins_oli1.UnitPriceD__c = li.oi.UnitPrice;
+                        ins_oli1.OpportunityId = opp.Id;
+                        ins_oli1.IsNew__c = false;
+                        ins_oli1.Discount = opp.Quote_Discount__c;
+                        ins_oli1.Product_Search__c = psMap.get(li.oi.PricebookEntryId).Id;
+                        ins_oli1.DealerSelectProduct__c = psMap.get(li.oi.PricebookEntryId).Product__c;
+                        ins_oliList1.add(ins_oli1);
+                    }
+                }
+
+                if (oliList.size() > 0) delete oliList;
+                if (ins_oliList1.size() > 0) insert ins_oliList1;
+                if (ins_oliList2.size() > 0) insert ins_oliList2;
+System.debug('=====ins_oliList1');
+            }
+
+            // 鍚屾浠g悊鍟嗙殑鏁伴噺瀛楁
+            List<OpportunityLineItem> upd_oli = new List<OpportunityLineItem>();
+            List<OpportunityLineItem> oliList2 = [select Id, Quantity, QuantityD__c from OpportunityLineItem where OpportunityId = :opp.Id];
+            for (OpportunityLineItem oli : oliList2) {
+                if (oli.Quantity != oli.QuantityD__c) {
+                    oli.QuantityD__c = oli.Quantity;
+                    upd_oli.add(oli);
+                }
+            }
+            if (upd_oli.size() > 0) update upd_oli;
+System.debug('=====update upd_oli');
+            // 澶嶅埗鍚堝悓
+            Opportunity ins_opp_view = [select Id,Quote_Discount__c,Quote_Subtotal__c,Quote_TotalPrice__c,Quote_CustomPrice__c,
+                                               SyncedQuoteId,SyncedQuote.Discount,SyncedQuote.Subtotal,SyncedQuote.TotalPrice,SyncedQuote.Custom_Price_Total__c,
+                                               SyncedQuote.Custom_Price_Total_Text__c,IE_local_cost__c
+                                          from Opportunity where Id = :ins_opp.Id];
+            Order ins_odr = odr.clone();
+            ins_odr.Id = null;
+            ins_odr.OpportunityId = ins_opp.Id;
+            if (ins_quo != null) {
+                ins_odr.QuoteId = ins_quo.Id;
+            }
+            ins_odr.org_order__c = odr.Id;
+            ins_odr.Name = null;
+            ins_odr.ContractCode__c = null;
+            ins_odr.Split_Approved__c = false;
+            //ins_odr.product_approval__c = false;
+            ins_odr.Is_Already_Splited__c = true;
+            Decimal quoteDiscount = ins_opp_view.Quote_Discount__c;
+            ins_odr.Discount__c = quoteDiscount.setScale(4, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_Discount__c;
+            ins_odr.Discount_D__c = quoteDiscount.setScale(4, System.RoundingMode.HALF_UP);
+            Decimal quoteSubtotal = ins_opp_view.Quote_Subtotal__c;
+            ins_odr.Olympus_Price_BeforeDiscount__c = quoteSubtotal.setScale(2, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_Subtotal__c;
+            ins_odr.Olympus_Price_BeforeDiscount_D__c = quoteSubtotal.setScale(2, System.RoundingMode.HALF_UP);
+            Decimal quoteTotalPrice = ins_opp_view.Quote_TotalPrice__c;
+            if(odr.ProductSegment__c != 'NDT' && odr.ProductSegment__c != 'ANI'){
+                ins_odr.OlympusContractPrices__c = quoteTotalPrice.setScale(0, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_TotalPrice__c;
+                ins_odr.OlympusContractPricesD__c = quoteTotalPrice.setScale(0, System.RoundingMode.HALF_UP);
+            }else{
+                ins_odr.OlympusContractPrices__c = quoteTotalPrice;//ins_opp_view.Quote_TotalPrice__c;
+                ins_odr.OlympusContractPricesD__c = quoteTotalPrice;
+            }
+            Decimal quoteCustomPrice = ins_opp_view.Quote_CustomPrice__c;
+            ins_odr.CustomerContractPrice__c = quoteCustomPrice.setScale(2, System.RoundingMode.HALF_UP);//ins_opp_view.Quote_CustomPrice__c;
+            ins_odr.CustomerContractPriceD__c = quoteCustomPrice.setScale(2, System.RoundingMode.HALF_UP);
+            if (is_IE) {
+                Decimal oppCost = ins_opp_view.IE_local_cost__c == null ? 0 : ins_opp_view.IE_local_cost__c;
+                ins_odr.Cost__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
+                ins_odr.Cost_D__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
+            }
+            if (ins_odr.ApproveStatus__c == 'Submit') {
+                ins_odr.ApproveStatus__c = 'Draft';
+            } else if (ins_odr.ApproveStatus__c == 'OrderSubmit') {
+                ins_odr.ApproveStatus__c = 'OrderDraft';
+            } else {
+                // 淇濇寔鐘舵��
+                
+            }
+            ins_odr.IsUpload__c = false;
+            insert ins_odr;
+System.debug('=====ins_odr');
+
+            List<OrderItem> upd_oiList = new List<OrderItem>();
+            List<OrderItem> del_oiList = new List<OrderItem>();
+            //List<OrderItem> ins_oiList = new List<OrderItem>();
+            if(odr.ProductSegment__c == 'BS'){
+                List<QuoteLineItem> tempList = [select Id, QuoteId, Description, Quantity, PricebookEntryId, UnitPrice from QuoteLineItem where QuoteId = :quo.Id];
+                for( QuoteLineItem qli : tempList){
+                    OrderItem oi = new OrderItem();
+                    oi.Description = qli.Description;
+                    oi.Quantity = qli.Quantity;
+                    oi.PricebookEntryId = qli.PricebookEntryId;
+                    oi.UnitPrice = qli.UnitPrice;
+                    oi.OrderId = odr.Id;
+                    oi.QuoteLineItemId = qli.Id;
+                    upd_oiList.add(oi);
+                }
+                del_oiList = [select Id from OrderItem where OrderId = :odr.Id];
+
+                
+            }else{
+                for (LineInfo li : lineinfo) {
+                    if (li.divideCnt == li.oi.Quantity) {
+                        //
+                        OrderItem del_oi = new OrderItem(Id = li.oi.Id);
+                        del_oiList.add(del_oi);
+                        //
+                        /*OrderItem ins_oi = li.oi.clone();
+                        ins_oi.Id = null;
+                        ins_oi.OrderId = ins_odr.Id;
+                        ins_oiList.add(ins_oi);*/
+                    } else if (li.divideCnt > 0 && li.divideCnt <= li.oi.Quantity) {
+                        //
+                        OrderItem upd_oi = li.oi;
+                        upd_oi.Quantity = upd_oi.Quantity - li.divideCnt;
+                        upd_oiList.add(upd_oi);
+                        //
+                        /*OrderItem ins_oi = li.oi.clone();
+                        ins_oi.Id = null;
+                        ins_oi.OrderId = ins_odr.Id;
+                        ins_oi.Quantity = li.divideCnt;
+                        ins_oiList.add(ins_oi);*/
+                    } else {
+                        // 涓嶅仛澶勭悊
+                    }
+                }
+            }
+            
+          
+                List<DecideQuoteProductSet__c> del_dqpList = new List<DecideQuoteProductSet__c>();
+                List<DecideQuoteProductSet__c> ins_dqpList = new List<DecideQuoteProductSet__c>();
+                List<DecideQuoteProductSet__c> upd_dqpList = new  List<DecideQuoteProductSet__c>();
+                for (LineInfo li : lineinfo) {
+                    if(li.isSet == true){
+                        // 鍏ㄩ儴鍒嗗壊
+                        if (li.divideCnt == li.dqps.DecideProductSetCount__c) {
+                            // 鍒犻櫎鍘熸姤浠蜂骇鍝�
+                            DecideQuoteProductSet__c del_dqp = new DecideQuoteProductSet__c(Id = li.dqps.Id);
+                            del_dqpList.add(del_dqp);
+                            // 鍏ㄩ儴鍒嗗壊鍒版柊鎶ヤ环
+                            DecideQuoteProductSet__c ins_dqp = li.dqps.clone();
+                            ins_dqp.Id = null;
+                            ins_dqp.DecideQuote__c = ins_quo.Id;
+                            ins_dqp.DecideOrder__c = ins_odr.Id;
+                            ins_dqp.DecideOpportunity__c = ins_opp.Id;
+
+                            ins_dqpList.add(ins_dqp);
+                        // 閮ㄥ垎鍒嗗壊
+                        } else if (li.divideCnt > 0 && li.divideCnt <= li.dqps.DecideProductSetCount__c) {
+                            // 鏇存柊鍘熸姤浠蜂骇鍝佹暟閲�
+                            DecideQuoteProductSet__c upd_dqp = li.dqps;
+                            upd_dqp.DecideProductSetCount__c = upd_dqp.DecideProductSetCount__c - li.divideCnt;
+                            upd_dqp.DecideProductSetTotalprice__c = upd_dqp.DecideProductSetUnivalence__c * upd_dqp.DecideProductSetCount__c;
+                            upd_dqpList.add(upd_dqp);
+            
+                            // 閮ㄥ垎鍒嗗壊鍒版柊鎶ヤ环
+                           DecideQuoteProductSet__c ins_dqp = li.dqps.clone();
+                            ins_dqp.Id = null;
+                            ins_dqp.DecideQuote__c = ins_quo.Id;
+                            ins_dqp.DecideOrder__c = ins_odr.Id;
+                            ins_dqp.DecideOpportunity__c = ins_opp.Id;
+                            ins_dqp.DecideProductSetCount__c = li.divideCnt;
+                            ins_dqp.DecideProductSetTotalprice__c = ins_dqp.DecideProductSetUnivalence__c * ins_dqp.DecideProductSetCount__c;
+
+                            ins_dqpList.add(ins_dqp);
+                        // 鏈垎鍓�
+                        } else{
+                            // 涓嶅仛澶勭悊
+                           
+                        } 
+                    }
+                }
+                System.debug(ins_dqpList);
+                System.debug(upd_dqpList);
+                System.debug(del_dqpList);
+                if(ins_dqpList.size() > 0 ) insert ins_dqpList;
+                if(upd_dqpList.size() > 0 ) update upd_dqpList;
+                if(del_dqpList.size() > 0 ) delete del_dqpList;
+           
+
+            
+
+
+/*            if (upd_oiList.size() > 0) update upd_oiList;
+            if (del_oiList.size() > 0) delete del_oiList;
+            //if (ins_oiList.size() > 0) insert ins_oiList;
+System.debug('=====ins_oiList');*/
+
+            Opportunity opp_view = [select Id,Quote_Discount__c,Quote_Subtotal__c,Quote_TotalPrice__c,Quote_CustomPrice__c,IE_local_cost__c from Opportunity where Id = :opp.Id];
+            odr.Split_Approved__c = false;
+            //odr.product_approval__c = false;
+            odr.Is_Already_Splited__c = true;
+            Decimal quoteDiscount1 = opp_view.Quote_Discount__c;
+            odr.Discount__c = quoteDiscount1.setScale(4, System.RoundingMode.HALF_UP);//opp_view.Quote_Discount__c;
+            odr.Discount_D__c = quoteDiscount1.setScale(4, System.RoundingMode.HALF_UP);
+            Decimal quoteSubtotal1 = opp_view.Quote_Subtotal__c;
+            odr.Olympus_Price_BeforeDiscount__c = quoteSubtotal1.setScale(2, System.RoundingMode.HALF_UP);//opp_view.Quote_Subtotal__c;
+            odr.Olympus_Price_BeforeDiscount_D__c = quoteSubtotal1.setScale(2, System.RoundingMode.HALF_UP);
+            Decimal quoteTotalPrice1 = opp_view.Quote_TotalPrice__c;
+            if(odr.ProductSegment__c != 'NDT' && odr.ProductSegment__c != 'ANI'){
+                odr.OlympusContractPrices__c = quoteTotalPrice1.setScale(0, System.RoundingMode.HALF_UP);//opp_view.Quote_TotalPrice__c;
+                odr.OlympusContractPricesD__c = quoteTotalPrice1.setScale(0, System.RoundingMode.HALF_UP);
+            }else{
+                odr.OlympusContractPrices__c = quoteTotalPrice1;//opp_view.Quote_TotalPrice__c;
+                odr.OlympusContractPricesD__c = quoteTotalPrice1;
+            }
+            Decimal quoteCustomPrice1 = opp_view.Quote_CustomPrice__c;
+            odr.CustomerContractPrice__c = quoteCustomPrice1.setScale(2, System.RoundingMode.HALF_UP);//opp_view.Quote_CustomPrice__c;
+            odr.CustomerContractPriceD__c = quoteCustomPrice1.setScale(2, System.RoundingMode.HALF_UP);
+            if (is_IE) {
+                Decimal oppCost = opp_view.IE_local_cost__c == null ? 0 : opp_view.IE_local_cost__c;
+                odr.Cost__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
+                odr.Cost_D__c = oppCost.setScale(2, System.RoundingMode.HALF_UP);
+            }
+            if (odr.ApproveStatus__c == 'Submit') {
+                odr.ApproveStatus__c = 'Draft';
+               
+           
+            } else if (odr.ApproveStatus__c == 'OrderSubmit') {
+                odr.ApproveStatus__c = 'OrderDraft';
+               
+          
+            } else {
+                // 淇濇寔鐘舵��
+
+            }
+            update odr;
+System.debug('=====update odr');
+
+            if (upd_oiList.size() > 0 && odr.ProductSegment__c == 'BS'){
+                System.debug('upd_oilist' + upd_oiList);
+                insert upd_oiList;
+            }else if(upd_oiList.size() > 0) {
+                update upd_oiList;
+            }
+            if (del_oiList.size() > 0) delete del_oiList;
+            //if (ins_oiList.size() > 0) insert ins_oiList;
+System.debug('=====ins_oiList');
+            //OrderWebService.updItems(odr.OpportunityId, odr.Id);
+           //鐜嬮箯浼� 寮�濮� 鍚堝悓鍒嗗壊鍚屾鍒嗗壊璐告槗绠$悊瀹㈡埛鐢宠琛�
+            if(ins_odr!=null && ins_odr.Id!=null){
+                Schema.DescribeSobjectResult tradeFields = TradeCustomerManager__c.sObjectType.getDescribe();
+                Map<String, Schema.SObjectField> tradeFields_map = tradeFields.fields.getMap();
+                String tradeList_sql = 'select ';
+                String fields_trade = '';
+                for (String field : tradeFields_map.keySet()) {
+                    if (fields_trade.length() > 0) {
+                        fields_trade += ', ';
+                    }
+                    fields_trade += field;
+                }
+                tradeList_sql += fields_trade;
+                tradeList_sql += ' from TradeCustomerManager__c where order__c = \'' + odr.Id + '\'';
+                List<TradeCustomerManager__c> tradeList = Database.query(tradeList_sql);
+                if(tradeList!=null && tradeList.size()!=0){
+                    TradeCustomerManager__c newTrade = tradeList[0].clone();
+                    newTrade.Id = null;
+                    newTrade.OrderIdSave__c = ins_odr.Id;
+                    newTrade.order__c = ins_odr.Id;
+                    insert newTrade;
+                }
+            }
+            //鐜嬮箯浼� 缁撴潫
+
+            String url = baseUrl;
+            url += '\\' + ins_odr.Id;
+            return new Pagereference(url);
+            //Database.rollback(sp);
+            //return null;
+        } catch (Exception ex) {
+            Database.rollback(sp);
+System.debug('=====Exception:' + ex.getMessage() + ' | Line:' + ex.getLineNumber());
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
+            return null;
+        }
+        return null;
+    }
+
+
+    public static Boolean IfspecialDealer(String oppDealerId) {
+        if (String.isBlank(oppDealerId)) {
+            return false;
+        }
+        return StaticParameter.specialDealerMap.containsKey(oppDealerId.substring(0, 15)) && UserInfo.getUserType() == 'PowerPartner';
+    }
+
+    public PageReference BackBtn() {
+        String url = baseUrl;
+        if (rtUrl != null && rtUrl.length() > 0) {
+            url += rtUrl.replace('/production', '');
+        } else {
+            url += '\\' + odrId;
+        }
+        return new Pagereference(url);
+    }
+
+    public class LineInfo {
+        public Integer lineNo { get; set; }
+        public String productName { get; set; }
+        public String ProductCode { get; set; }
+        public String ECCode { get; set; }
+        public OrderItem oi { get; set; }
+        public Integer divideCnt { get; set; }
+        //浜у搧閰嶅
+        public DecideQuoteProductSet__c dqps {get; set; }
+        public Boolean isSet {get; set;}
+
+        public LineInfo(Integer in_i, OrderItem in_oi) {
+            lineNo = in_i;
+            productName = in_oi.PricebookEntry.Product2.Name;
+            ProductCode = in_oi.PricebookEntry.Product2.ProductCode;
+            ECCode = in_oi.PricebookEntry.Product2.Product_ECCode__c;
+            oi = in_oi;
+            divideCnt = 0;
+            isSet = false;
+        }
+
+        public LineInfo(Integer in_i,DecideQuoteProductSet__c in_dqps){
+            lineNo = in_i;
+            productName = in_dqps.DecideProductSetName__c;
+            ProductCode = in_dqps.DecideProductSetCode__c;
+            ECCode = '';
+            dqps = in_dqps;
+            divideCnt = 0;
+            isSet = true;
+        }
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    private void tes(){
+        Integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderDivisionController.cls-meta.xml b/scr/classes/OrderDivisionController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderDivisionController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderDivisionControllerTest.cls b/scr/classes/OrderDivisionControllerTest.cls
new file mode 100644
index 0000000..35ef85d
--- /dev/null
+++ b/scr/classes/OrderDivisionControllerTest.cls
@@ -0,0 +1,434 @@
+@isTest
+private class OrderDivisionControllerTest {
+
+	@isTest static void test_init() {
+		Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+
+            isActive = true
+        );
+        insert pricebook;
+
+       Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            CurrencyIsoCode = 'CNY',
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectBS[0].Id
+        );
+        insert user;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert contact;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = contact.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10
+        );
+        insert oli1;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli1 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10,
+            Custom_Price__c = 15,
+            Set__c = 'set01'
+        );
+        insert qli1;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            QuoteId = quo.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        
+        PageReference page = new PageReference('/apex/OrderDivision?odrId=' + order.Id + '&retURL=' + opp.Id);
+        System.Test.setCurrentPage(page);
+        OrderDivisionController controller = new OrderDivisionController();
+
+        controller.init();
+
+        //System.assertEquals(1, controller.lineinfo.size());
+        //System.assertEquals(10, controller.lineinfo[0].oi.Quantity);
+        //System.assertEquals(20, controller.lineinfo[1].oi.Quantity);
+
+        controller.lineinfo[0].divideCnt = 10;
+        //controller.lineinfo[1].divideCnt = 11;
+        
+        System.Test.StartTest();
+        controller.saveBtn();
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        List<OrderItem> oiList1 = [select id, Quantity from OrderItem where OrderId = :order.Id];
+        //System.assertEquals(0, oiList1.size());
+        //System.assertEquals(9, oiList1[0].Quantity);
+
+        List<OrderItem> oiList2 = [select id, Quantity from OrderItem where OrderId <> :order.Id];
+       // System.assertEquals(1, oiList2.size());
+        //System.assertEquals(10, oiList2[0].Quantity);
+        //System.assertEquals(11, oiList2[1].Quantity);
+
+        controller.backBtn();
+        System.Test.StopTest();
+    }
+
+/*    @isTest static void test_init_2() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20
+        );
+        insert oli2;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli2 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20,
+            Custom_Price__c = 25,
+            Set__c = 'set01'
+        );
+        insert qli2;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            QuoteId = quo.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id
+        );
+        insert order;
+
+        PageReference page = new PageReference('/apex/OrderDivision?odrId=' + order.Id + '&retURL=' + opp.Id);
+        System.Test.setCurrentPage(page);
+        OrderDivisionController controller = new OrderDivisionController();
+
+        controller.init();
+
+        System.assertEquals(1, controller.lineinfo.size());
+        //System.assertEquals(10, controller.lineinfo[0].oi.Quantity);
+        System.assertEquals(20, controller.lineinfo[0].oi.Quantity);
+
+        //controller.lineinfo[0].divideCnt = 10;
+        controller.lineinfo[0].divideCnt = 11;
+
+        controller.saveBtn();
+
+        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
+
+        List<OrderItem> oiList1 = [select id, Quantity from OrderItem where OrderId = :order.Id];
+        System.assertEquals(1, oiList1.size());
+        System.assertEquals(9, oiList1[0].Quantity);
+
+        List<OrderItem> oiList2 = [select id, Quantity from OrderItem where OrderId <> :order.Id];
+        System.assertEquals(1, oiList2.size());
+        //System.assertEquals(10, oiList2[0].Quantity);
+        System.assertEquals(11, oiList2[0].Quantity);
+    }*/
+
+    @isTest static void test_init2() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert contact;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id,
+            IE_Custom_Price__c = 2000,
+            IE_local_cost__c = 200,
+            IE_ShippingHandling__c = 100
+        );
+        insert opp;
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = contact.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10
+        );
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20
+        );
+        OpportunityLineItem oli3 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 30,
+            UnitPrice = 30
+        );
+        insert new OpportunityLineItem[] {oli1, oli2, oli3};
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        
+        PageReference page = new PageReference('/apex/OrderDivision?odrId=' + order.Id + '&retURL=' + opp.Id);
+        System.Test.setCurrentPage(page);
+        OrderDivisionController controller = new OrderDivisionController();
+
+        controller.init();
+
+        System.assertEquals(3, controller.lineinfo.size());
+        System.assertEquals(10, controller.lineinfo[0].oi.Quantity);
+        System.assertEquals(20, controller.lineinfo[1].oi.Quantity);
+        System.assertEquals(30, controller.lineinfo[2].oi.Quantity);
+
+        controller.lineinfo[0].divideCnt = 10;
+        controller.lineinfo[1].divideCnt = 11;
+System.Test.StartTest();
+        controller.saveBtn();
+System.Test.StopTest();
+        List<OrderItem> oiList1 = [select id, Quantity from OrderItem where OrderId = :order.Id];
+        System.assertEquals(2, oiList1.size());
+        System.assertEquals(9, oiList1[0].Quantity);
+        System.assertEquals(30, oiList1[1].Quantity);
+
+        List<OrderItem> oiList2 = [select id, Quantity from OrderItem where OrderId <> :order.Id];
+        System.assertEquals(2, oiList2.size());
+        System.assertEquals(10, oiList2[0].Quantity);
+        System.assertEquals(11, oiList2[1].Quantity);
+        
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/OrderDivisionControllerTest.cls-meta.xml b/scr/classes/OrderDivisionControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderDivisionControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderInternalMessageController.cls b/scr/classes/OrderInternalMessageController.cls
new file mode 100644
index 0000000..efd18db
--- /dev/null
+++ b/scr/classes/OrderInternalMessageController.cls
@@ -0,0 +1,422 @@
+public with sharing class OrderInternalMessageController {
+   
+    String oldResponse;
+    // 璇环
+    public Order ra { get; set; }
+    public Order ra1 { get; set; }
+    public Order cc { get; set; }
+    // 璇环ID
+    public Id raid { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    public String usertype { get; private set; }
+    
+
+    public OrderInternalMessageController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+    }
+
+    public OrderInternalMessageController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new Order();
+        cc = new Order();
+        usertype = UserInfo.getUserType();
+        List<Order> raList = [select Id, Name, InternalMessage__c from Order where Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        ra1 = new Order();
+        List<Order> ra1List = [select Id, Name, InternalMessage__c from Order where Id = :raid];
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+        oldResponse = ra1.InternalMessage__c;
+        ra1.InternalMessage__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = ra1.InternalMessage__c;
+        if (response == null || response.trim().length() == 0) {
+            ra1.InternalMessage__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += ra1.InternalMessage__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+   
+            ra1.InternalMessage__c = temp;
+
+            update ra1;
+            ra1.InternalMessage__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+            //messageNEW.Subject = '璁㈠崟' + ra.Name + '' + 'OCN鍐呴儴鐣欒█';
+            messageNEW.Subject = '鍚堝悓 ' + ra1.Name + '-鍐呴儴鐣欒█';
+            messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');          
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+
+
+
+
+    public static void te(){
+        Integer i = 1;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/OrderInternalMessageController.cls-meta.xml b/scr/classes/OrderInternalMessageController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrderInternalMessageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderItemTriggerHandler.cls b/scr/classes/OrderItemTriggerHandler.cls
new file mode 100644
index 0000000..eccf948
--- /dev/null
+++ b/scr/classes/OrderItemTriggerHandler.cls
@@ -0,0 +1,700 @@
+public without sharing class OrderItemTriggerHandler {
+
+    public static void setProductConfig(List<OrderItem> newList, Map<Id, OrderItem> newMap, List<OrderItem> oldList, Map<Id, OrderItem> oldMap) {
+        List<OrderItem> targetList = null;
+        if (Trigger.isDelete) {
+            targetList = oldList;
+        } else {
+            targetList = newList;
+        }
+        // 澶勭悊瀵硅薄鐨勫悎鍚孖D
+        List<String> ordIdList = new List<String>();
+        Map<String, String> ordMap = new Map<String, String>();
+        for (OrderItem target : targetList) {
+            if (ordMap.containsKey(target.OrderId) == false) {
+                ordIdList.add(target.OrderId);
+                ordMap.put(target.OrderId, target.OrderId);
+            }
+        }
+        // 鍙栧緱澶勭悊瀵硅薄鐨勫悎鍚屼骇鍝�
+        List<OrderItem> oiList = [select Id, PricebookEntry.Product2.ProductCode, Quantity, OrderId from OrderItem where OrderId = :ordIdList order by OrderId, PricebookEntry.Product2.ProductCode, Quantity];
+        Map<String, List<OrderItem>> oiMap = new Map<String, List<OrderItem>>();
+        List<OrderItem> nList = new List<OrderItem>();
+        String tmp = '';
+        for (OrderItem oi : oiList) {
+            if (tmp == '' || oi.OrderId != tmp) {
+                tmp = oi.OrderId;
+                nList = new List<OrderItem>();
+                oiMap.put(oi.OrderId, nList);
+                nList.add(oi);
+            } else {
+                nList.add(oi);
+            }
+        }
+        // 鏇存柊澶勭悊瀵硅薄鐨勫悎鍚�
+        List<Order> ordList = [select Id, RecordTypeId, ProductConfig__c, ProductConfig_D__c from Order where Id = :ordIdList];
+        List<Order> updList = new List<Order>();
+        for (Order target : ordList) {
+            List<OrderItem> ois = oiMap.get(target.Id);
+            if (ois == null || ois.size() == 0) {
+                continue;
+            }
+            String oiStr = '';
+            for (OrderItem oi : ois) {
+                if (oiStr == '') {
+                    oiStr += oi.PricebookEntry.Product2.ProductCode + '*' + oi.Quantity + '\n';
+                } else {
+                    oiStr += oi.PricebookEntry.Product2.ProductCode + '*' + oi.Quantity + '\n';
+                }
+            }
+
+            boolean individualCase = target.RecordTypeId == System.Label.RT_Contract_IndividualCase_ANI ||
+                                     target.RecordTypeId == System.Label.RT_Contract_IndividualCase_BS  ||
+                                     target.RecordTypeId == System.Label.RT_Contract_IndividualCase_IE  ||
+                                     target.RecordTypeId == System.Label.RT_Contract_IndividualCase_NDT ||
+                                     target.RecordTypeId == System.Label.RT_Contract_IndividualCase_RVI;
+
+            Order upd = new Order(Id = target.Id);
+            if (UserInfo.getUserType() == 'PowerPartner' || target.RecordTypeId == System.Label.RT_ServiceContract 
+                || target.RecordTypeId == System.Label.RT_ServiceContractIE || target.RecordTypeId == System.Label.RT_ServiceContractRVI || individualCase) {
+                upd.ProductConfig_D__c = oiStr;
+            } else {
+                upd.ProductConfig__c = oiStr;
+                upd.ProductConfig_D__c = oiStr;
+            }
+            updList.add(upd);
+        }
+
+        if (updList.size() > 0) update updList;
+    }
+
+    public static void insSingleProduct(List<OrderItem> newList, Map<Id, OrderItem> newMap, List<OrderItem> oldList, Map<Id, OrderItem> oldMap) {
+        List<Id> idList = new List<Id>();
+        idList.addAll(newMap.keySet());
+        List<order_Single_product__c> ospList = new List<order_Single_product__c>();
+        if(idList.size() >0 ){
+            for(Id id: idList){
+                if(newMap.get(id).ODISingleProduct__c == true){
+                    order_Single_product__c osp = new order_Single_product__c();
+                    osp.OrderProduct__c = id;
+                    osp.Order__c = newMap.get(id).OrderId;
+                    osp.CurrencyIsoCode = newMap.get(id).CurrencyCode__c;
+                    ospList.add(osp);
+                }
+            }
+            System.debug(ospList);
+            insert ospList;
+        }
+    }
+
+    public static void delSingleProduct(List<OrderItem> newList, Map<Id, OrderItem> newMap, List<OrderItem> oldList, Map<Id, OrderItem> oldMap) {
+        List<Id> idList = new List<Id>();
+        for(OrderItem ord : oldList){
+            if(ord.ODISingleProduct__c == true){
+                idList.add(ord.Id);
+            }
+        }
+        if(idList.size() >0 ){
+            List<order_Single_product__c> ospList = [select id from order_Single_product__c where OrderProduct__c in :idList];
+            System.debug('ospList***'+ospList);
+            delete ospList;
+        }
+
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    public static void tess(){
+        Integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderItemTriggerHandler.cls-meta.xml b/scr/classes/OrderItemTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderItemTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderMessageController.cls b/scr/classes/OrderMessageController.cls
new file mode 100644
index 0000000..b1746a4
--- /dev/null
+++ b/scr/classes/OrderMessageController.cls
@@ -0,0 +1,117 @@
+public without sharing class OrderMessageController {
+    String oldResponse;
+    // 璁㈠崟
+    public Order ra { get; set; }
+    public Order ra1 { get; set; }
+    public Order cc { get; set; }
+    // 璁㈠崟ID
+    public Id raid { get; private set; }
+
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }
+    
+
+    public OrderMessageController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+    }
+
+    public OrderMessageController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new Order();
+        cc = new Order();
+        List<Order> raList = [select Id, Name, OCN_Internal_Notes__c from Order where Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+    }
+    
+     // 鐢婚潰鍒濆鍖�-POP UP
+    public void init1() {
+        hasError = false;
+        ra1 = new Order();
+        List<Order> ra1List = [select Id, Name, OCN_Internal_Notes__c from Order where Id = :raid];
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+        oldResponse = ra1.OCN_Internal_Notes__c;
+        ra1.OCN_Internal_Notes__c = '';
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String response = ra1.OCN_Internal_Notes__c;
+        if (response == null || response.trim().length() == 0) {
+            ra1.OCN_Internal_Notes__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        // 鍘熺暀瑷�-oldResponse
+        // oldResponse = ra.OCN_Internal_Notes__c;
+        
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += ra1.OCN_Internal_Notes__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        try {
+            // 鏇存柊鐣欒█
+    //        Order updra = new Order();
+    //        updra.Id = ra.Id;
+            ra1.OCN_Internal_Notes__c = temp;
+
+            update ra1;
+            ra1.OCN_Internal_Notes__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+            //messageNEW.Subject = '璁㈠崟' + ra.Name + '' + 'OCN鍐呴儴鐣欒█';
+            messageNEW.Subject = '璁㈠崟 ' + ra1.Name + '-OCSM鍐呴儴鐣欒█';
+            messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');          
+            
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderMessageController.cls-meta.xml b/scr/classes/OrderMessageController.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/OrderMessageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderMessageControllerTest.cls b/scr/classes/OrderMessageControllerTest.cls
new file mode 100644
index 0000000..c1d988f
--- /dev/null
+++ b/scr/classes/OrderMessageControllerTest.cls
@@ -0,0 +1,198 @@
+@isTest
+public with sharing class OrderMessageControllerTest {
+
+    static testMethod void myTest1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today()
+        );
+        insert odr;
+        
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OrderMessagePopUp?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        
+        OrderMessageController controller = new OrderMessageController();
+        
+
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name, OCN_Internal_Notes__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1.OCN_Internal_Notes__c = 'test1';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+
+    static testMethod void myTest2() {
+         List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+         Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            OCN_Internal_Notes__c = 'test1',
+            EffectiveDate = Date.today()
+        );
+        insert odr;
+        
+        //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OrderMessagePopUp?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        OrderMessageController controller = new OrderMessageController();
+        
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name, OCN_Internal_Notes__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        //System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1.OCN_Internal_Notes__c = '';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+     static testMethod void myTest3() {
+         List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+         Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today()
+        );
+        insert odr;
+        
+        //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OrderMessagePopUp?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        OrderMessageController controller = new OrderMessageController();
+        
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name, OCN_Internal_Notes__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init();
+        //System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1 = odr1;
+        controller.ra1.OCN_Internal_Notes__c = '';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderMessageControllerTest.cls-meta.xml b/scr/classes/OrderMessageControllerTest.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/OrderMessageControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderPdf2Controller.cls b/scr/classes/OrderPdf2Controller.cls
new file mode 100644
index 0000000..c090912
--- /dev/null
+++ b/scr/classes/OrderPdf2Controller.cls
@@ -0,0 +1,1355 @@
+public without sharing class OrderPdf2Controller {
+    public HeaderInfo header { get; set; }
+    public List<List<DetailInfo>> pageDetails { get; set; }
+    public String productSegment { get; set; }
+
+    public List<DetailInfo> inputDetails { get; set; }
+
+    public Order order { get; set; }
+    // 涔版柟
+    public Account buyer { get; set; }
+    // 鏀惰揣鏂�
+    public Account delivery { get; set; }
+    public Contact delivery_contact { get; set; }
+    // 鏈�缁堢敤鎴�
+    public Account user { get; set; }
+    public Contact contact { get; set; }
+
+    public String id;
+    public String baseUrl { get; set; }
+    public String strToday { get; set; }
+    public boolean is_parts_direct { get; set; }
+    public boolean is_ie_direct { get; set; }
+
+    public Integer pageCnt { get; set; }
+    public boolean fistPageBreak { get; set; }
+    public boolean lastPageBreak { get; set; }
+
+    private Integer firstCnt = 10;
+    private Integer firstMaxCnt = 24;
+    private Integer eachCnt = 48;
+    private Integer lastMaxCnt = 35;
+
+    private Integer iRfirstCnt = 6;
+    private Integer iRfirstMaxCnt = 23;
+    private Integer iReachCnt = 48;
+    private Integer iRlastMaxCnt = 30;
+
+    private Integer nAfirstCnt = 6;
+    private Integer nAfirstMaxCnt = 23;
+    private Integer nAeachCnt = 48;
+    private Integer nAlastMaxCnt = 30;
+
+    public String seller_name1 { get; set; }
+    public String seller_address1 { get; set; }
+    public String seller_city1 { get; set; }
+    public String seller_province1 { get; set; }
+    public String seller_phone1 { get; set; }
+
+    public String seller_name2 { get; set; }
+    public String seller_address2 { get; set; }
+    public String seller_city2 { get; set; }
+    public String seller_province2 { get; set; }
+    public String seller_phone2 { get; set; }
+
+    public boolean is_hidden_user { get; set; }
+    public boolean is_dealer_user { get; set; }
+
+    public Decimal dis {get;set;}
+
+    public String ndt_name{get;set;}
+    public String ndt_email{get;set;}
+    public String ndt_number{get;set;}
+    public String ndt_fax{get;set;}
+
+    public Boolean notSpecialDealer { get; set; }
+
+    public OrderPdf2Controller() {
+        id = ApexPages.currentPage().getParameters().get('id');
+
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+
+        Date today = Date.today();
+        strToday = today.format();
+    }
+
+    public PageReference init() {
+        notSpecialDealer = true;
+        if (id == null || id.length() == 0) {
+            return null;
+        }
+
+        is_hidden_user = false;
+        // String profileid = UserInfo.getProfileId().subString(0,15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {
+            is_hidden_user = true;
+        }
+        is_dealer_user = false;
+        if (UserInfo.getUserType() == 'PowerPartner') {
+            is_dealer_user = true;
+        }
+
+        order = new Order();
+        List<Order> orderList = [select Id, AccountId, OpportunityId, Opportunity.Dealer__c, Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c,Opportunity.InquiryNumber__c,
+                                        PDF_S_Name__c, PDF_S_Address__c, PDF_S_City__c, PDF_S_Province__c, PDF_S_Phone__c,Opportunity.CreatedBy.ContactId,CreatedBy.ContactId,
+                                        Name, Opportunity.ExpectedDeliveryDate__c, PDF_Sap_No__c, OrderNumber, Opportunity.SubDealer__c,
+                                        PDF_Property__c, Opportunity.Name, PDF_No__c, Description, PDF_Order_No__c,CrossCooperativeProject__c,Dealer_A__c,
+                                        Olympus_Price_BeforeDiscount_D__c, Discount_D__c, OlympusContractPricesD__c, CustomerContractPriceD__c,
+                                        Opportunity.ProductSegment__c, Opportunity.SalesChannel__c, Opportunity.Machine_Parts__c,
+                                        SpecialDeliveryAccount__c, SpecialDeliveryAccount_D__c, SpecialDeliveryContact2__c, SpecialDeliveryContact2_D__c
+                                   from Order where Id = :id];
+        if (orderList.size() == 0) {
+            return null;
+        }
+        order = orderList[0];
+        dis = order.Discount_D__c;
+        productSegment = order.Opportunity.ProductSegment__c;
+        is_parts_direct = false;
+        is_ie_direct = false;
+        if (order.Opportunity.ProductSegment__c == 'IE' && order.Opportunity.SalesChannel__c == 'direct') {
+            is_ie_direct = true;
+        }
+        system.debug(is_ie_direct);
+        if (order.Opportunity.SalesChannel__c == 'direct' && order.Opportunity.Machine_Parts__c == 'Parts') {
+            is_parts_direct = true;
+        }
+        /*Contact dealerContact = new Contact();
+        if(order.Opportunity.ProductSegment__c == 'NDT' || order.Opportunity.ProductSegment__c == 'ANI'){
+            String id = UserInfo.getUserId();
+            User user = [select id,ContactID from User where id =: id];
+            String conid = user.ContactId;
+            dealerContact = [select id, Name,Phone,MobilePhone,Fax,Email from Contact where id =:conid];
+        }*/
+        buyer = new Account();
+        if (order.Opportunity.Dealer__c != null) {
+             if (order.CrossCooperativeProject__c) {
+                buyer = [select Id, Name, Address1__c,Business_license__c, City__c, Province__c, Phone from Account where Id = :order.Dealer_A__c];
+            }else{
+                buyer = [select Id, Name, Address1__c,Business_license__c, City__c, Province__c, Phone from Account where Id = :order.Opportunity.Dealer__c];
+            }
+            //buyer = [select Id, Name, Address1__c,Business_license__c, City__c, Province__c, Phone from Account where Id = :order.Opportunity.Dealer__c];
+        }
+        notSpecialDealer = !StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c));
+        system.debug('order.Opportunity.Dealer__c' + order.Opportunity.Dealer__c);
+        String ndtID = order.CreatedBy.ContactId;
+        if(ndtID != null){
+            Contact ndtcon =  [select Id, Department, Name, Phone, MobilePhone,Fax,Email from Contact where Id = :ndtID];
+            ndt_name = ndtcon.Name;
+            ndt_email = ndtcon.Email;
+            ndt_number = ndtcon.Phone;
+            ndt_fax = ndtcon.Fax;
+        }
+
+        delivery = new Account();
+        if (order.SpecialDeliveryAccount_D__c != null) {
+            delivery = [select Id, Name, Address1__c, City__c, Province__c, Sub_Use__c from Account where Id = :order.SpecialDeliveryAccount_D__c];
+        }
+
+        delivery_contact = new Contact();
+        if (order.SpecialDeliveryContact2_D__c != null) {
+            delivery_contact = [select Id, Department, Name, Phone, MobilePhone,Address1__c from Contact where Id = :order.SpecialDeliveryContact2_D__c];
+        }
+
+        user = new Account();
+        if (order.AccountId != null) {
+            user = [select Id, Name, ManagementCode_F__c, Address1__c,Business_license__c, City__c, Province__c, Sub_Use__c, Phone from Account where Id = :order.AccountId];
+        }
+
+        List<OpportunityContactRole> ocrList = [select Id, OpportunityId, IsPrimary, ContactId
+                                                  from OpportunityContactRole
+                                                 where OpportunityId = :order.OpportunityId
+                                                 order by IsPrimary desc];
+        String contactid = null;
+        if (ocrList.size() > 0) {
+            contactid = ocrList[0].ContactId;
+        }
+        contact = new Contact();
+        if (contactid != null && contactid.length() > 0) {
+            contact = [select Id, Department, Name, Phone, MobilePhone,Fax,Email from Contact where Id = :contactid];
+        }
+
+        List<OrderItem> oiList = [select Id, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Product_ECCode__c,PriceBookEntry.Product2.Name,PriceBookEntry.Product2.registrationCode__c,
+                                         Quantity, UnitPrice, Factory__c, PriceBookEntry.Hidden_flag__c,PriceBookEntry.Product2.Product_CCode__c
+                                    from OrderItem
+                                   where OrderId = :id
+                                   order by QuoteLineItemId,Id];
+
+        if (is_parts_direct == true || is_ie_direct == true) {
+            header = new HeaderInfo(order, user, delivery, delivery_contact, user, contact);
+        } else {
+            header = new HeaderInfo(order, buyer, delivery, delivery_contact, user, contact);
+        }
+        
+        fistPageBreak = false;
+        lastPageBreak = false;
+        pageCnt = 0;
+        pageDetails = new List<List<DetailInfo>>();
+        Integer  count = 0;
+       
+        for (OrderItem oi : oiList) {
+            count += getRow(oi);
+        }
+
+        if(productSegment == 'IE' || productSegment == 'RVI'){
+            if (count <= iRfirstCnt) {
+                pageCnt = 1;
+            } else if (count > iRfirstCnt && count <= iRfirstMaxCnt) {
+                fistPageBreak = true;
+                pageCnt = 2;
+            } else {
+                pageCnt = 1 + (count - iRfirstMaxCnt) / iReachCnt;
+                Integer mod = Math.mod(count - iRfirstMaxCnt, iReachCnt);
+                if (mod > 0 && mod <= iRlastMaxCnt) {
+                    pageCnt += 1;
+                } else if (mod > iRlastMaxCnt) {
+                    lastPageBreak = true;
+                    pageCnt += 2;
+                }
+            }
+        }else if (productSegment == 'NDT' || productSegment == 'ANI') {
+            if (count <= nAfirstCnt) {
+                pageCnt = 1;
+            } else if (count > nAfirstCnt && count <= nAfirstMaxCnt) {
+                fistPageBreak = true;
+                pageCnt = 2;
+            } else {
+                pageCnt = 1 + (count - nAfirstMaxCnt) / nAeachCnt;
+                Integer mod = Math.mod(count - nAfirstMaxCnt, nAeachCnt);
+                if (mod > 0 && mod <= nAlastMaxCnt) {
+                    pageCnt += 1;
+                } else if (mod > nAlastMaxCnt) {
+                    lastPageBreak = true;
+                    pageCnt += 2;
+                }
+            }
+        }else {
+            if (count <= firstCnt) {
+                pageCnt = 1;
+            } else if (count > firstCnt && count <= firstMaxCnt) {
+                fistPageBreak = true;
+                pageCnt = 2;
+            } else {
+                pageCnt = 1 + (count - firstMaxCnt) / eachCnt;
+                Integer mod = Math.mod(count - firstMaxCnt, eachCnt);
+                if (mod > 0 && mod <= lastMaxCnt) {
+                    pageCnt += 1;
+                } else if (mod > lastMaxCnt) {
+                    lastPageBreak = true;
+                    pageCnt += 2;
+                }
+            }
+        }
+
+        
+
+        Integer nowPage = 1;
+        Integer nowLine = 0;
+        Integer line = 0;
+        List<DetailInfo> details = new List<DetailInfo>();
+        for (OrderItem oi : oiList) {
+            if (productSegment == 'IE' || productSegment == 'RVI') {
+                line += 1;
+                nowLine += getRow(oi);
+                if (count <= iRfirstMaxCnt) {
+                    DetailInfo di = new DetailInfo(line, oi,dis);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                } else if (nowPage == 1) {
+                    if (nowLine <= iRfirstMaxCnt) {
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    } else {
+                        nowPage += 1;
+                        nowLine = 0;
+                        pageDetails.add(details);
+                        details = new List<DetailInfo>();
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    }
+                } else {
+                    if (nowLine <= iReachCnt) {
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    } else {
+                        nowPage += 1;
+                        nowLine = 0;
+                        pageDetails.add(details);
+                        details = new List<DetailInfo>();
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    }
+                }
+            }else if (productSegment == 'NDT' || productSegment == 'ANI') {
+                line += 1;
+                nowLine += getRow(oi);
+                if (count <= nAfirstMaxCnt) {
+                    DetailInfo di = new DetailInfo(line, oi,dis);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                } else if (nowPage == 1) {
+                    if (nowLine <= nAfirstMaxCnt) {
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    } else {
+                        nowPage += 1;
+                        nowLine = 0;
+                        pageDetails.add(details);
+                        details = new List<DetailInfo>();
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    }
+                } else {
+                    if (nowLine <= nAeachCnt) {
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    } else {
+                        nowPage += 1;
+                        nowLine = 0;
+                        pageDetails.add(details);
+                        details = new List<DetailInfo>();
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    }
+                }
+            }else {
+                line += 1;
+                nowLine += getRow(oi);
+                if (count <= firstMaxCnt) {
+                    DetailInfo di = new DetailInfo(line, oi,dis);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                } else if (nowPage == 1) {
+                    if (nowLine <= firstMaxCnt) {
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    } else {
+                        nowPage += 1;
+                        nowLine = 0;
+                        pageDetails.add(details);
+                        details = new List<DetailInfo>();
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    }
+                } else {
+                    if (nowLine <= eachCnt) {
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    } else {
+                        nowPage += 1;
+                        nowLine = 0;
+                        pageDetails.add(details);
+                        details = new List<DetailInfo>();
+                        DetailInfo di = new DetailInfo(line, oi,dis);
+                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                            di.price = 0;
+                            di.totalprice = 0;
+                        }
+                        details.add(di);
+                    }
+                }
+            }
+
+            
+
+
+        }
+
+        /*if (oiList.size() <= firstCnt) {
+            pageCnt = 1;
+        } else if (oiList.size() > firstCnt && oiList.size() <= firstMaxCnt) {
+            fistPageBreak = true;
+            pageCnt = 2;
+        } else {
+            pageCnt = 1 + (oiList.size() - firstMaxCnt) / eachCnt;
+            Integer mod = Math.mod(oiList.size() - firstMaxCnt, eachCnt);
+            if (mod > 0 && mod <= lastMaxCnt) {
+                pageCnt += 1;
+            } else if (mod > lastMaxCnt) {
+                lastPageBreak = true;
+                pageCnt += 2;
+            }
+        }*/
+       /* Integer nowPage = 1;
+        Integer nowLine = 0;
+        Integer line = 0;
+        List<DetailInfo> details = new List<DetailInfo>();
+        for (OrderItem oi : oiList) {
+            line += 1;
+            nowLine += 1;
+            if (oiList.size() <= firstMaxCnt) {
+                DetailInfo di = new DetailInfo(line, oi);
+                if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                    di.price = 0;
+                    di.totalprice = 0;
+                }
+                details.add(di);
+            } else if (nowPage == 1) {
+                if (nowLine <= firstMaxCnt) {
+                    DetailInfo di = new DetailInfo(line, oi);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                } else {
+                    nowPage += 1;
+                    nowLine = 0;
+                    pageDetails.add(details);
+                    details = new List<DetailInfo>();
+                    DetailInfo di = new DetailInfo(line, oi);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                }
+            } else {
+                if (nowLine <= eachCnt) {
+                    DetailInfo di = new DetailInfo(line, oi);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                } else {
+                    nowPage += 1;
+                    nowLine = 0;
+                    pageDetails.add(details);
+                    details = new List<DetailInfo>();
+                    DetailInfo di = new DetailInfo(line, oi);
+                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                        di.price = 0;
+                        di.totalprice = 0;
+                    }
+                    details.add(di);
+                }
+            }
+        }*/
+
+        if (fistPageBreak == true) {
+            for (Integer i = nowLine + 1; i <= firstMaxCnt; i++) {
+                line += 1;
+                DetailInfo di = new DetailInfo(line);
+                details.add(di);
+            }
+        } else if (lastPageBreak == true) {
+            for (Integer i = nowLine + 1; i <= eachCnt; i++) {
+                line += 1;
+                DetailInfo di = new DetailInfo(line);
+                details.add(di);
+            }
+        }
+
+        pageDetails.add(details);
+
+        Decimal sum = 0;
+        for(List<DetailInfo> difList : pageDetails){
+            for (DetailInfo  dif: difList ) {
+                if(dif.price_d != null){
+                    sum+=dif.price_d;
+                }
+            }
+        }
+        if(sum != 0){
+            for(List<DetailInfo> difList : pageDetails){
+                for (DetailInfo  dif: difList ) {
+                    system.debug(header.order_totalprice+'-----'+sum);
+                    dif.price_d = dif.price_d + (header.order_totalprice - sum);
+                    break;
+                }
+                break;
+            }
+        }
+
+        return null;
+    }
+
+    private Integer getRow(OrderItem oi){
+        Integer row = 1;
+        if(oi.PriceBookEntry.Product2.Product_ECCode__c != null){
+            if (productSegment == 'ANI' || productSegment == 'NDT'){
+                row = oi.PriceBookEntry.Product2.Product_ECCode__c.length()/27 +1 > row ? oi.PriceBookEntry.Product2.Product_ECCode__c.length() == 24 ?1:oi.PriceBookEntry.Product2.Product_ECCode__c.length()/24  +1: row;
+            } else if (productSegment == 'IE' || productSegment == 'RVI'){
+                row = oi.PriceBookEntry.Product2.Product_ECCode__c.length()/17 +1 > row ? oi.PriceBookEntry.Product2.Product_ECCode__c.length() == 17 ?1:oi.PriceBookEntry.Product2.Product_ECCode__c.length()/17  +1: row;
+            } else{
+                row = oi.PriceBookEntry.Product2.Product_ECCode__c.length()/11 +1 > row ? oi.PriceBookEntry.Product2.Product_ECCode__c.length() == 11 ?1:oi.PriceBookEntry.Product2.Product_ECCode__c.length()/11  +1: row;
+            }
+        }
+        if(oi.PriceBookEntry.Product2.Product_CCode__c != null){
+            row = oi.PriceBookEntry.Product2.Product_CCode__c.length()/12 +1> row ? oi.PriceBookEntry.Product2.Product_CCode__c.length() == 12?1:oi.PriceBookEntry.Product2.Product_CCode__c.length()/12 +1: row;
+        }
+        if(oi.PriceBookEntry.Product2.Name != null){
+            if (productSegment == 'BS') {
+                row = oi.PriceBookEntry.Product2.Name.length()/9 +1> row ? oi.PriceBookEntry.Product2.Name.length() == 9 ? 1 : oi.PriceBookEntry.Product2.Name.length()/9 +1: row;
+            }else if (productSegment == 'NDT' || productSegment == 'ANI') {
+                row = oi.PriceBookEntry.Product2.Name.length()/12 +1> row ? oi.PriceBookEntry.Product2.Name.length() == 12 ? 1 : oi.PriceBookEntry.Product2.Name.length()/12 +1: row;
+            }
+        }
+        if(productSegment == 'BS' && oi.PriceBookEntry.Product2.registrationCode__c != null){
+            row = oi.PriceBookEntry.Product2.registrationCode__c.length()/17 +1>row? oi.PriceBookEntry.Product2.registrationCode__c.length() == 15 ? 1 : oi.PriceBookEntry.Product2.registrationCode__c.length()/17 +1 : row;
+            system.debug('======'+row+'++++++++++'+oi.PriceBookEntry.Product2.registrationCode__c.length() +'-------'+oi.PriceBookEntry.Product2.registrationCode__c);
+        }
+        system.debug(oi.PriceBookEntry.Product2.Name+'***********'+row+'***'+oi.PriceBookEntry.Product2.Name.length()+'***'+ (oi.PriceBookEntry.Product2.Name.length()/9 +1));
+        
+        return row;
+    }
+
+    public PageReference init2() {
+        notSpecialDealer = true;
+        is_hidden_user = false;
+        // String profileid = UserInfo.getProfileId().subString(0,15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        
+        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {
+            is_hidden_user = true;
+        }
+        is_dealer_user = false;
+        if (UserInfo.getUserType() == 'PowerPartner') {
+            is_dealer_user = true;  
+        }
+
+        seller_name1 = '濂ユ灄宸存柉(涓浗)鏈夐檺鍏徃';
+        seller_address1 = '鍖椾含甯傛湞闃冲尯鏂版簮鍗楄矾1-3鍙峰钩瀹夊浗闄呴噾铻嶄腑蹇傾搴�8妤�';
+        seller_city1 = '鍖椾含';
+        seller_province1 = '鍖椾含';
+        seller_phone1 = '010-58199000';
+
+        seller_name2 = '濂ユ灄宸存柉锛堝寳浜級閿�鍞湇鍔℃湁闄愬叕鍙镐笂娴峰垎鍏徃';
+        seller_address2 = '涓婃捣甯傚緪姹囧尯娣捣涓矾1010鍙�1001-1006銆�1101銆�1102銆�1104-1106銆�1601瀹�';
+        seller_city2 = '涓婃捣';
+        seller_province2 = '涓婃捣';
+        seller_phone2 = '021-51582084';
+
+        header = new HeaderInfo();
+        inputDetails = new List<DetailInfo>();
+        order = new Order();
+
+        List<Order> orderList = [select Id, AccountId, OpportunityId, Opportunity.Dealer__c, Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c,
+                                        PDF_S_Name__c, PDF_S_Address__c, PDF_S_City__c, PDF_S_Province__c, PDF_S_Phone__c,
+                                        Name, Opportunity.ExpectedDeliveryDate__c, PDF_Sap_No__c, OrderNumber, Opportunity.SubDealer__c,
+                                        PDF_Property__c, Opportunity.Name, PDF_No__c, Description, PDF_Order_No__c,
+                                        Olympus_Price_BeforeDiscount_D__c, Discount_D__c, OlympusContractPricesD__c, CustomerContractPriceD__c,
+                                        Opportunity.ProductSegment__c
+                                   from Order where Id = :id];
+        if (orderList.size() == 0) {
+            return null;
+        }
+
+        order = orderList[0];
+        dis = order.Discount_D__c;
+        header.seller_name = order.PDF_S_Name__c;
+        header.seller_address = order.PDF_S_Address__c;
+        header.seller_city = order.PDF_S_City__c;
+        header.seller_province = order.PDF_S_Province__c;
+        header.seller_phone = order.PDF_S_Phone__c;
+        header.order_sap_no = order.PDF_Sap_No__c;
+        //header.user_property_IE = order.PDF_Property__c;
+        header.order_no = order.PDF_No__c;
+        header.pdf_order_no = order.PDF_Order_No__c;
+        //dealerid = order.Opportunity.Dealer__c.subString(0,15)
+        notSpecialDealer = !StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c));
+        system.debug('order.Opportunity.Dealer__c' + StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c)));
+        system.debug(!StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c)));
+        productSegment = order.Opportunity.ProductSegment__c;
+
+        //2019-5-20
+        if(productSegment == 'IE' && (order.PDF_Property__c == '' || order.PDF_Property__c == null)){
+            List<Account> accList = [select id,UserType__c from Account where id = :order.AccountId];
+            if(accList.size() > 0 ){
+                order.PDF_Property__c = accList[0].UserType__c;
+            }
+        }
+
+        List<OrderItem> oiList = [select Id, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Product_ECCode__c,PriceBookEntry.Product2.Name,PriceBookEntry.Product2.Factory__c,Discount__c,
+                                         Quantity, UnitPrice, Factory__c, PriceBookEntry.Hidden_flag__c,PriceBookEntry.Product2.Product_CCode__c,PriceBookEntry.Product2.registrationCode__c
+                                    from OrderItem
+                                   where OrderId = :id
+                                   order by QuoteLineItemId, Id];
+        Integer line = 0;
+        for (OrderItem oi : oiList) {
+            line += 1;
+            DetailInfo di = new DetailInfo(line, oi,dis);
+            if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
+                di.price = 0;
+                di.totalprice = 0;
+            }
+            di.factory = oi.PriceBookEntry.Product2.Factory__c;
+            inputDetails.add(di);
+        }
+
+        //notSpecialDealer = !StaticParameter.specialDealerMap.containsKey(order.Opportunity.Dealer__c);
+        return null;
+    }
+
+    public PageReference printBtn() {
+        PageReference ref = null;
+        if (saveFunction() == true) {
+            if(productSegment == 'NDT' || productSegment == 'ANI'){
+                ref = new Pagereference(baseUrl + '/apex/OrderPdf3?id=' + order.id);
+                ref.setRedirect(true);
+            }else{
+                ref = new Pagereference(baseUrl + '/apex/OrderPdf2?id=' + order.id);
+                ref.setRedirect(true);
+            }
+        }
+        return ref;
+    }
+
+    public PageReference saveBtn() {
+        PageReference ref = null;
+        if (saveFunction() == true) {
+            ref = new Pagereference(baseUrl + '/apex/OrderContract2?id=' + order.id);
+            ref.setRedirect(true);
+        }
+        return ref;
+    }
+
+    public boolean saveFunction() {
+        boolean rt = false;
+
+        Order upd_order = new Order();
+        upd_order.Id = order.Id;
+        upd_order.Name = order.Name;
+        upd_order.PDF_S_Name__c = header.seller_name;
+        upd_order.PDF_S_Address__c = header.seller_address;
+        upd_order.PDF_S_City__c = header.seller_city;
+        upd_order.PDF_S_Province__c = header.seller_province;
+        upd_order.PDF_S_Phone__c = header.seller_phone;
+        upd_order.PDF_Sap_No__c = header.order_sap_no;
+        //upd_order.PDF_Property__c = header.user_property_IE;
+        upd_order.PDF_Property__c = order.PDF_Property__c;
+        upd_order.PDF_No__c = header.order_no;
+        upd_order.PDF_Order_No__c = header.pdf_order_no;
+
+        List<OrderItem> upd_oiList = new List<OrderItem>();
+        for (DetailInfo inputDetail : inputDetails) {
+            OrderItem oi = new OrderItem();
+            oi.Id = inputDetail.orderItem.Id;
+            oi.Factory__c = inputDetail.factory;
+            upd_oiList.add(oi);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            update upd_order;
+            update upd_oiList;
+           
+            rt = true;
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
+            Database.rollback(sp);
+            return false;
+        }
+
+        return rt;
+    }
+
+    public class HeaderInfo {
+        // 涔版柟淇℃伅
+        public String buyer_name { get; set; }
+        public String buyer_address { get; set; }
+        public String buyer_city { get; set; }
+        public String buyer_province { get; set; }
+        public String buyer_phone { get; set; }
+        public String buyer_code {get; set;}
+        // 鍗栨柟淇℃伅
+        public String seller_name { get; set; }
+        public String seller_address { get; set; }
+        public String seller_city { get; set; }
+        public String seller_province { get; set; }
+        public String seller_phone { get; set; }
+        public String seller_code {get; set;}
+        // 璁㈠崟淇℃伅1
+        public String order_number { get; set; }
+        public String order_require_date { get; set; }
+        public String order_sap_no { get; set; }
+        public String order_crm_no { get; set; }
+        public String order_subdealer { get; set; }
+        // 鏀惰揣淇℃伅
+        public String delivery_name { get; set; }
+        public String delivery_department { get; set; }
+        public String delivery_address { get; set; }
+        public String delivery_city { get; set; }
+        public String delivery_province { get; set; }
+        public String delivery_user { get; set; }
+        public String delivery_phone { get; set; }
+        public String delivery_tel { get; set; }
+        // 鏈�缁堢敤鎴蜂俊鎭�
+        public String user_name { get; set; }
+        public String user_no { get; set; }
+        public String user_department { get; set; }
+        public String user_address { get; set; }
+        public String user_city { get; set; }
+        public String user_province { get; set; }
+        public String user_name2 { get; set; }
+        public String user_phone { get; set; }
+        public String user_fax {get; set;}
+        public String user_email {get;set;}
+        public String user_tel { get; set; }
+        public String user_property_IE { get; set; }
+        public String user_product_IE { get; set; }
+        public String user_market_RVI { get; set; }
+        // 璁㈠崟淇℃伅2
+        public Decimal order_subtotal { get; set; }
+        public Decimal order_discount_rate { get; set; }
+        public Decimal order_discount_value { get; set; }
+        public Decimal order_totalprice { get; set; }
+        public Decimal order_dealer_profit { get; set; }
+        public Decimal order_dealer_price { get; set; }
+        public boolean order_print_dealer { get; set; }
+        // 璁㈠崟淇℃伅3
+        public String order_inquiry_no { get; set; }
+        public String order_no { get; set; }
+        public String order_comment { get; set; }
+        public String pdf_order_no { get; set; }
+
+        public HeaderInfo() {
+
+        }
+
+        public HeaderInfo(Order order, Account buyer, Account delivery, Contact delivery_contact, Account user, Contact contact) {
+            buyer_name = buyer.Name;
+            buyer_address = buyer.Address1__c;
+            buyer_city = buyer.City__c;
+            buyer_province = buyer.Province__c;
+            buyer_phone = buyer.Phone;
+            buyer_code = buyer.Business_license__c;
+
+            seller_name = order.PDF_S_Name__c;
+            seller_address = order.PDF_S_Address__c;
+            seller_city = order.PDF_S_City__c;
+            seller_province = order.PDF_S_Province__c;
+            seller_phone = order.PDF_S_Phone__c;
+
+            order_number = order.Name;
+            Date dt = order.Opportunity.ExpectedDeliveryDate__c;
+            order_require_date = dt == null ? '' : dt.format();
+            order_sap_no =  order.PDF_Sap_No__c;
+            order_crm_no = order.OrderNumber;
+            order_subdealer = order.Opportunity.SubDealer__c;
+
+            delivery_name = delivery.Name;
+            delivery_department = delivery_contact.Department;
+            delivery_address = delivery_contact.Address1__c;
+            delivery_city = delivery.City__c;
+            delivery_province = delivery.Province__c;
+            delivery_user = delivery_contact.Name;
+            delivery_phone = delivery_contact.Phone;
+            delivery_tel = delivery_contact.MobilePhone;
+
+            user_name = user.Name;
+            user_no = user.ManagementCode_F__c;
+            user_department = contact.Department;
+            user_address = user.Address1__c;
+            user_city = user.City__c;
+            user_province = user.Province__c;
+            user_name2 = contact.Name;
+            user_phone = contact.Phone;
+            user_fax = contact.Fax;
+            user_email = Contact.Email;
+            user_tel = contact.MobilePhone;
+            user_property_IE = order.PDF_Property__c;
+            user_product_IE = user.Sub_Use__c == 'Automotive' ? '姹借溅' : user.Sub_Use__c;
+            user_market_RVI = user.Sub_Use__c;
+
+            order_subtotal = order.Olympus_Price_BeforeDiscount_D__c;
+            order_discount_rate = order.Discount_D__c;
+            order_totalprice = order.OlympusContractPricesD__c;
+            order_discount_value = (order_subtotal == null ? 0 : order_subtotal) - (order_totalprice == null ? 0 : order_totalprice);
+            order_dealer_price = order.CustomerContractPriceD__c;
+            order_dealer_profit = (order_dealer_price == null ? 0 : order_dealer_price) - (order_totalprice == null ? 0 : order_totalprice);
+            order_print_dealer = true;
+            if (order_dealer_price == null || order_dealer_price == 0) {
+                order_print_dealer = false;
+            }
+
+            order_inquiry_no = order.Opportunity.Name;
+            if(order.Opportunity.ProductSegment__c == 'NDT' || order.Opportunity.ProductSegment__c == 'ANI'){
+                order_inquiry_no = order.Opportunity.InquiryNumber__c;
+            }
+            order_no = order.PDF_No__c;
+            order_comment = order.Description;
+            pdf_order_no = order.PDF_Order_No__c;
+        }
+    }
+
+    public class DetailInfo {
+        public OrderItem orderItem { get; set; }
+        public Integer lineno { get; set; }
+        public String otcode { get; set; }
+        public String eccode { get; set; }
+        public Integer quantity { get; set; }
+        public Decimal price { get; set; }
+        public Decimal totalprice { get; set; }
+        public String factory { get; set; }
+        public String ccode { get; set; }
+        public String name {get; set;}
+        public String registrationCode {get; set;}
+        public Decimal price_d {get;set;}
+        public String discount {get;set;}
+
+        public DetailInfo(Integer line) {
+            orderItem = new OrderItem();
+            lineno = line;
+            otcode = null;
+            eccode = null;
+            quantity = null;
+            price = null;
+            totalprice = null;
+            factory = null;
+            ccode = null;
+            name = null;
+            registrationCode = null;
+            discount = null;
+        }
+
+        public DetailInfo(Integer line, OrderItem oi,Decimal dis) {
+            discount = dis + '%';
+            orderItem = oi;
+            lineno = line;
+            otcode = oi.PriceBookEntry.Product2.ProductCode;
+            otcode = otcode.startsWith('00000000000') ? otcode.substring(11) : otcode;
+            eccode = oi.PriceBookEntry.Product2.Product_ECCode__c;
+            //eccode = eccode.startsWith('00000000000') ? eccode.substring(11) : eccode;
+            Decimal qty = oi.Quantity;
+            quantity = qty.intValue();
+            price = oi.UnitPrice;
+            price = price.setScale(2, System.RoundingMode.HALF_UP);
+            totalprice = qty * price;
+            totalprice = totalprice.setScale(2, System.RoundingMode.HALF_UP);
+            factory = oi.Factory__c;
+            ccode = oi.PriceBookEntry.Product2.Product_CCode__c;
+            name = oi.PriceBookEntry.Product2.Name;
+            if (oi.PriceBookEntry.Product2.registrationCode__c !=null && oi.PriceBookEntry.Product2.registrationCode__c != '') {
+                registrationCode = oi.PriceBookEntry.Product2.registrationCode__c + 'LS鍐呰锤';
+            }else{
+                registrationCode = oi.PriceBookEntry.Product2.registrationCode__c;
+            }
+            
+            system.debug('registrationCode='+registrationCode);
+            if(dis != null ){
+                price_d =totalprice * (1-(dis/100));
+                price_d = price_d.setScale(2, System.RoundingMode.HALF_UP);
+            }
+        }
+    }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    public static void asd() {
+        Integer i = 1;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderPdf2Controller.cls-meta.xml b/scr/classes/OrderPdf2Controller.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderPdf2Controller.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderPdf2ControllerTest.cls b/scr/classes/OrderPdf2ControllerTest.cls
new file mode 100644
index 0000000..1cca8b0
--- /dev/null
+++ b/scr/classes/OrderPdf2ControllerTest.cls
@@ -0,0 +1,845 @@
+@isTest
+private class OrderPdf2ControllerTest {
+
+	@isTest static void test_init1() {
+        OrderPdf2Controller.asd();
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+
+		Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'IE'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            Role = 'End user',
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+           //ProductListApproveStatus__c = 'Reject'
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderPdf2?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdf2Controller controller = new OrderPdf2Controller();
+
+        controller.init();
+/*
+        oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 10; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        controller.init();
+
+        oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 48; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        controller.init();*/
+	}
+
+    @isTest static void test_init2() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'IE'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductCode = 'product2';
+        product2.Product_ECCode__c = 'product165456456465';
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product16545645641265';
+        insert product3;
+
+        Product2 product4 = new Product2();
+        product4.Name = 'product4';
+        product4.ProductCode = 'product4';
+        product4.Product_ECCode__c = 'product165456asd5641265';
+        insert product4;
+
+        Product2 product5 = new Product2();
+        product5.Name = 'product5';
+        product5.ProductCode = 'product5';
+        product5.Product_ECCode__c = 'product16512456asd5641265';
+        insert product5;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            AccountId = user.Id,
+            CurrencyIsoCode = 'CNY',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderContract2?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdf2Controller controller = new OrderPdf2Controller();
+
+        controller.init2();
+
+        controller.inputDetails[0].factory = 'factory0';
+
+        controller.saveBtn();
+
+        List<OrderItem> oiList1 = [select id, Factory__c from OrderItem where OrderId = :order.Id];
+        System.assertEquals('factory0', oiList1[0].Factory__c);
+
+        controller.printBtn();
+    }
+
+    @isTest static void test_init3() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectBS[0].Id
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            Role = 'End user',
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+           //ProductListApproveStatus__c = 'Reject'
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderPdf2?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdf2Controller controller = new OrderPdf2Controller();
+
+        controller.init();
+    }
+
+    @isTest static void test_init4() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectBS[0].Id
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            AccountId = user.Id,
+            CurrencyIsoCode = 'CNY',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderContract2?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdf2Controller controller = new OrderPdf2Controller();
+
+        controller.init2();
+
+        controller.inputDetails[0].factory = 'factory0';
+
+        controller.saveBtn();
+
+        List<OrderItem> oiList1 = [select id, Factory__c from OrderItem where OrderId = :order.Id];
+        System.assertEquals('factory0', oiList1[0].Factory__c);
+
+        controller.printBtn();
+    }
+
+    @isTest static void test_init5() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectNDT = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'NDT'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectNDT[0].Id
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'NDT',
+            ProductSegment__c = 'NDT',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            Role = 'End user',
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+           //ProductListApproveStatus__c = 'Reject'
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderPdf2?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdf2Controller controller = new OrderPdf2Controller();
+
+        controller.init();
+    }
+
+    @isTest static void test_init6() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectNDT = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'NDT'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectNDT[0].Id
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'NDT',
+            ProductSegment__c = 'NDT',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order order = new Order(
+            Name = 'order',
+            AccountId = user.Id,
+            CurrencyIsoCode = 'CNY',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderContract2?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdf2Controller controller = new OrderPdf2Controller();
+
+        controller.init2();
+
+        controller.inputDetails[0].factory = 'factory0';
+
+        controller.saveBtn();
+
+        List<OrderItem> oiList1 = [select id, Factory__c from OrderItem where OrderId = :order.Id];
+        System.assertEquals('factory0', oiList1[0].Factory__c);
+
+        controller.printBtn();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderPdf2ControllerTest.cls-meta.xml b/scr/classes/OrderPdf2ControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderPdf2ControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderPdfController.cls b/scr/classes/OrderPdfController.cls
new file mode 100644
index 0000000..1609f66
--- /dev/null
+++ b/scr/classes/OrderPdfController.cls
@@ -0,0 +1,896 @@
+public without sharing class OrderPdfController {
+
+    public Order od { get; set; }
+    public Order odpdf { get; set; }
+    public Contract contra { get; set; }
+
+    public Integer pageCnt {get; private set;}
+    public Decimal TotalMoney {get; private set;}
+    public Decimal TotalMoney2 {get; private set;}
+    public Decimal TrAndPre {get; set;}
+    public List<SetInfo> printRecords {get; private set;}
+    public List<Order_Print_SetInfo__c> ndtdelList {get; set;}
+
+    public List<Order_Print_SetInfo__c> printSetInfo { get; set; }
+
+    public Opportunity Opp {get; private set;}
+    public Boolean saveBtnDisabled { get; private set; }
+    public String Id;
+
+    public String baseUrl { get; set; }
+
+    public Account specialDeliveryAddress { get; private set; }
+    public Contact specialDeliveryContact { get; private set; }
+
+    public String PDF_N_NotifyParty1 { get; private set; }
+    public String PDF_NOTIFY_PARTY1 { get; private set; }
+    public String PDF_N_Address1 { get; private set; }
+    public String PDF_N_Add1 { get; private set; }
+    public String PDF_N_TEL1 { get; private set; }
+    public String PDF_N_FAX1 { get; private set; }
+    public String PDF_N_CONTACT1 { get; private set; }
+    public String PDF_N_CONTACTPERSON1 { get; private set; }
+
+    public String PDF_N_NotifyParty2 { get; private set; }
+    public String PDF_NOTIFY_PARTY2 { get; private set; }
+    public String PDF_N_Address2 { get; private set; }
+    public String PDF_N_Add2 { get; private set; }
+    public String PDF_N_TEL2 { get; private set; }
+    public String PDF_N_FAX2 { get; private set; }
+    public String PDF_N_CONTACT2 { get; private set; }
+    public String PDF_N_CONTACTPERSON2 { get; private set; }
+
+    public String PDF_Forwarder1 { get; private set; }
+    public String PDF_F_Add1 { get; private set; }
+    public String PDF_F_TEL1 { get; private set; }
+    public String PDF_F_FAX1 { get; private set; }
+    public String PDF_F_ContactPerson1 { get; private set; }
+
+    public String PDF_Forwarder2 { get; private set; }
+    public String PDF_F_Add2 { get; private set; }
+    public String PDF_F_TEL2 { get; private set; }
+    public String PDF_F_FAX2 { get; private set; }
+    public String PDF_F_ContactPerson2 { get; private set; }
+
+    public List<NDT_Produce__c> ndtList {get; set;}
+    public Decimal dis {get; set;}
+    public List<DetailInfo> detaList {get; set;}
+
+    public Boolean isNull {get; set;}
+    public Boolean isVer {get; set;}
+    public Boolean isPtf {get; set;}
+
+    public List<OrderItem> oiList {get; set;}
+
+    // The extension constructor initializes the private member
+    // variable mysObject by using the getRecord method from the standard
+    // controller.
+    public OrderPdfController() {
+        Id = ApexPages.currentPage().getParameters().get('id');
+
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+    }
+    public PageReference init() {
+        od = new Order();
+        List<Order> oList = new List<Order>();
+
+        printSetInfo = new List<Order_Print_SetInfo__c>();
+        //ndtdelList = new List<Order_Print_SetInfo__c>();
+        saveBtnDisabled = false;
+        String saveflg = ApexPages.currentPage().getParameters().get('save');
+        if (saveflg == '1') {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '淇濆瓨鎴愬姛銆�'));
+        }
+        isNull = false;
+        if (Id != null) {
+            oList = [select id, Discount_D__c, ServiceFee_D__c, ShippingHandling_Tax__c, /*B_Address__c, B_contactperson__c, */ApproveStatus__c, ProductSegment__c, Name, AccountId, OrderNumber, OpportunityId, PaymentCondition__c, PaymentCondition_D__c, DeliveryDate__c, EndUser__r.Name, PDF_SignatureDate__c, PDF_SignaturePlace__c, PDF_B_Add__c,
+                     PDF_B_contactperson__c, PDF_SELLER__c, PDF_THE_SELLER__c, PDF_S_Adds__c, PDF_S_Address__c, PDF_S_TEL__c, PDF_S_FAX__c, PDF_B_Department__c,
+                     PDF_S_Bank_Name__c, PDF_S_Bank_Address__c, PDF_S_Branch__c, PDF_QA__c, PDF_QA2__c, PDF_S_Account_No__c, PDF_S_Swift_Code__c, PDF_S_Account_Name__c, PDF_C_Add__c, CustomerContractPrice__c, CustomerContractPriceD__c,
+                     PDF_C_contactperson__c, PDF_NotifyFlag__c, PDF_N_NotifyParty__c, PDF_NOTIFY_PARTY__c, PDF_N_Address__c, PDF_N_Add__c, PDF_B_Attri__c,
+                     PDF_N_TEL__c, PDF_N_FAX__c, PDF_N_CONTACT__c, PDF_N_CONTACTPERSON__c, PDF_Sp_Shipment_Term__c, PDF_Sp_DestinationPort__c, PDF_Sp_DestinationPort_E__c, PDF_G_SpecNo__c,
+                     PDF_Sp_ShippingTerms__c, PDF_Sp_Freight__c, PDF_Sp_insurance__c, PDF_Sp_SHIPPINGMARK__c, PDF_Bi_AllBill__c, PDF_I_Report__c, PDF_G_TrAndPre__c,
+                     PDF_Bi_manufacturers__c, PDF_Bi_manufacturersEn__c, PDF_Bi_q1__c, PDF_Bi_airway__c, PDF_Bi_copyairway__c, PDF_Bi_invoice__c, PDF_Bi_Insurance__c, PDF_ForwarFlag__c,
+                     PDF_Bi_Packing__c, PDF_Bi_Quality__c, PDF_Bi_Origin__c, PDF_Bi_Non_Wooden__c, PDF_Co_Contract__c, PDF_Co_Contract_E__c, PDF_Co_BContra__c, PDF_Co_BContra_E__c, PDF_SignaturePlaces__c,
+                     PDF_Co_SContra__c, PDF_Co_SContra_E__c, PDF_C_Consignee__c, PDF_C_THECONSIGNE__c, PDF_C_Address__c, PDF_C_TEL__c, PDF_C_FAX__c, PDF_C_CONTACT__c,
+                     PDF_BusyerCompany__c, PDF_By_Add__c, PDF_By_Tel__c, PDF_Forwarder__c, PDF_F_Add__c, PDF_F_TEL__c, PDF_F_FAX__c, PDF_F_ContactPerson__c,
+                     Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c, DeliveryTimeText__c, DeliveryTimeTextEn__c,
+                     SpecialDeliveryAccount__c, SpecialDeliveryAccount_D__c, SpecialDeliveryContact2__c, SpecialDeliveryContact2_D__c, PDF_Order_No__c, Total_price_E__c, ContractPriceTotal__c,
+                     PDF_Shipment_Term2_Text__c, PDF_PaymentTerms__c, PDF_PaymentTerms_E__c, PDF_Sign_Name__c, PDF_Sign_Title__c, org_order__c, Is_Already_Splited__c, PDF_Is_True__c 
+                     from Order where id = :Id];
+            ndtList = [select id, U8_Code__c, Quantity__c, Part_Number__c, Name_of_Goods__c from NDT_Produce__c where NDTOrder__c = :Id order by Id];
+            printSetInfo = [select id, Order__c, No__c, Goods__c, Unit__c, Qty__c , UnitPrice__c, Total_Amount__c, U8__c, discount__c, discountprice__c, PriceNDT__c, Total_AmountNDT__c, Remark__c, NameOfGood__c from Order_Print_SetInfo__c where Order__c = :Id order by No__c];
+            system.debug('printSetInfo.size = ' + printSetInfo.size());
+            //ndtdelList = printSetInfo;
+
+            List<OpportunityLineItem> oliList = [select Id, TotalPrice, Subtotal, Quantity, Product2Id, Product2.ProductCode, Product2.Name,
+                                                 Product2.Description, Description, OpportunityId, Product2.Product_ECCode__c
+                                                 from OpportunityLineItem
+                                                 where OpportunityId = :oList[0].OpportunityId
+                                                         order by Id];
+            //isNull = printSetInfo.size() == 0 ? true : false;
+            //鍏堝仛鍚堝悓鐨勬墦鍗皃df娌℃湁淇濆瓨鎴栬�呮墦鍗板氨鎷嗗垎,鍐嶈�屾槸宸茬粡鎵撳嵃鎴栦繚瀛樹簡,鍐嶆媶鍒嗙殑鎯呭喌銆�
+            isPtf = oList[0].PDF_Is_True__c == true ? true : false;
+            isVer = (oList[0].ApproveStatus__c == 'OrderPass' && oList[0].Is_Already_Splited__c == true) ? true : false;
+            //**isNull鍜屼笂闈袱涓爣蹇楁湁鑱旂郴锛岃浠ュ悗淇敼isNull鐨勬椂鍊欙紝鎶奿sPtf鍜宨sVer涔熷甫涓婏紝isNull鐢ㄥ埌鐨勫湴鏂硅涔熺粰杩欎咯绠椾笂銆�
+            isNull = (oList[0].ApproveStatus__c == 'OrderDraft' || oList[0].ApproveStatus__c == 'OrderReject' ) ? true : false;
+            system.debug('@@@@@@@@'+oList[0].ApproveStatus__c);
+            system.debug(oList[0].ProductSegment__c);
+            if (oList[0].ProductSegment__c != 'NDT' && oList[0].ProductSegment__c != 'ANI') {
+                if (printSetInfo.size() < 15) {
+                    for (Integer i = printSetInfo.size(); i < 15; i++) {
+                        printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
+                    }
+                }
+            } else {
+                if (isNull || (isVer == true && isPtf == false)) {
+                    //delete printSetInfo;
+                    printSetInfo.clear();
+                    if (printSetInfo.size() < 15 && oliList.size() < 15) {
+                        for (Integer i = printSetInfo.size(); i < 15; i++) {
+                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
+                        }
+                    } else {
+                        for (Integer i = printSetInfo.size(); i < oliList.size(); i++) {
+                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
+                        }
+                    }
+                } else {
+                    if (printSetInfo.size() < 15 && oliList.size() < 15) {
+                        for (Integer i = printSetInfo.size(); i < 15; i++) {
+                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
+                        }
+                    } else {
+                        for (Integer i = printSetInfo.size(); i < oliList.size(); i++) {
+                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
+                        }
+                    }
+                }
+            }
+
+
+
+            if (ndtList.size() < oliList.size()) {
+                for (Integer i = ndtList.size(); i < oliList.size(); i++) {
+                    ndtList.add(new NDT_Produce__c(NDTOrder__c = Id));
+                }
+            }
+
+            if (oList.size() > 0) {
+                od = oList[0];
+                dis = od.Discount_D__c;
+                Opp = [select id, Name, Amount, ProductSegment__c, TradeType__c, SyncedQuoteId, Quote_TotalPrice__c from Opportunity where id = :od.OpportunityId];
+               /* if (od.PDF_B_Add__c == null || od.PDF_B_Add__c == '') {
+                    od.PDF_B_Add__c = od.B_Address__c;
+                }
+                if (od.PDF_B_contactperson__c  == null || od.PDF_B_contactperson__c == '') {
+                    od.PDF_B_contactperson__c = od.B_contactperson__c;
+                }*/
+                if (od.PDF_SELLER__c == null || od.PDF_SELLER__c == '') {
+
+                    od.PDF_Bi_q1__c = '2';
+                    od.PDF_Bi_airway__c = '1';
+                    od.PDF_Bi_copyairway__c = '1';
+                    od.PDF_Bi_invoice__c = '2';
+                    od.PDF_Bi_Insurance__c = '1';
+                    od.PDF_Bi_Packing__c = '2';
+                    od.PDF_Bi_Quality__c = '2';
+                    od.PDF_Bi_Origin__c = '2';
+                    od.PDF_Bi_Non_Wooden__c = '1';
+
+                    od.PDF_Co_Contract__c = '2';
+                    od.PDF_Co_BContra__c = '1';
+                    od.PDF_Co_SContra__c = '1';
+
+                    od.PDF_Co_Contract_E__c = 'two';
+                    od.PDF_Co_BContra_E__c = 'one';
+                    od.PDF_Co_SContra_E__c = 'one';
+                }
+                if ((Opp.ProductSegment__c == 'IE'  || Opp.ProductSegment__c == 'RVI' || Opp.ProductSegment__c == 'BS') && Opp.TradeType__c == 'Tax Exemption') {
+                    od.PDF_SELLER__c = '濂ユ灄宸存柉棣欐腐涓浗鏈夐檺鍏徃';
+                    od.PDF_THE_SELLER__c = 'Olympus Hong Kong and China Limited';
+                    od.PDF_S_Adds__c = '棣欐腐鏂扮晫钁垫秾钁垫槍璺�51铏熶節榫嶈部鏄撲腑蹇�1搴�26妯�';
+                    od.PDF_S_Address__c = 'L26, Tower 1, Kowloon Commerce Centre, 51 Kwai Cheong Road, Kwai Chung, New Territories, Hong Kong.';
+                    od.PDF_S_TEL__c = '锛�852锛�2170 5678';
+                    od.PDF_S_FAX__c = '锛�852锛�2170 5679';
+                    od.PDF_S_Bank_Name__c = 'MUFG Bank锛孡td';
+                    od.PDF_S_Branch__c = 'Kowloon Branch';
+                    od.PDF_S_Bank_Address__c = '15/F, Peninsula Office Tower 18 Middle Road, Kowloon, Hong Kong';
+                    od.PDF_S_Account_No__c = '047-821-85800023837锛圲SD Saving Account锛�';
+                    od.PDF_S_Swift_Code__c = 'BOTKHKHH';
+                    od.PDF_S_Account_Name__c = 'Evident Corporation';
+                } else if (( Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') && Opp.TradeType__c == 'Tax Exemption') {
+                    od.PDF_SELLER__c = '濂ユ灄宸存柉棣欐腐涓浗鏈夐檺鍏徃';
+                    od.PDF_THE_SELLER__c = 'Olympus Hong Kong and China Limited';
+                    od.PDF_S_Adds__c = '棣欐腐鏂扮晫钁垫秾钁垫槍璺�51铏熶節榫嶈部鏄撲腑蹇�1搴�26妯�';
+                    od.PDF_S_Address__c = 'L26, Tower 1, Kowloon Commerce Centre, 51 Kwai Cheong Road, Kwai Chung, New Territories, Hong Kong';
+                    od.PDF_S_TEL__c = '锛�852锛�2170 5678';
+                    od.PDF_S_FAX__c = '锛�852锛�2170 5679';
+                    od.PDF_S_Bank_Name__c = 'The Bank Of Tokyo-Mitsubishi UFJ锛孡td.';
+                    od.PDF_S_Branch__c = 'Kowloon Branch ';
+                    od.PDF_S_Bank_Address__c = '15/F., Peninsula Office Tower, 18 Middle Road, Kowloon';
+                    od.PDF_S_Account_No__c = '047-821-85800023837锛圲SD Saving Account锛�';
+                    od.PDF_S_Swift_Code__c = 'BOTKHKHH';
+                    od.PDF_S_Account_Name__c = 'Olympus Hong Kong and China Limited';
+                    od.DeliveryTimeTextEn__c = 'Please refer to order confirmation';
+                    od.DeliveryTimeText__c = '璇峰弬鑰冭鍗曠‘璁�';
+                    od.PDF_Bi_AllBill__c = '涓嶉殢璐�';
+                    od.PDF_G_TrAndPre__c = String.valueOf(od.ShippingHandling_Tax__c);
+                }
+
+                //Decimal TotalMoney = 0;
+                TotalMoney = 0;
+                TotalMoney2 = 0;
+                if (Opp.Amount != null) {
+                    TotalMoney = od.ContractPriceTotal__c; //Opp.Quote_TotalPrice__c;
+                    if ((Opp.ProductSegment__c == 'BS' || Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI' ) && Opp.TradeType__c == 'Tax Exemption') {
+                        TotalMoney = TotalMoney.setScale(2, System.RoundingMode.HALF_UP);
+                    } else {
+                        TotalMoney = TotalMoney.setScale(0, System.RoundingMode.HALF_UP);
+                    }
+                }
+                if (od.CustomerContractPriceD__c != null) {
+                    TotalMoney2 = od.CustomerContractPriceD__c;
+                    TotalMoney2 = TotalMoney2.setScale(2, System.RoundingMode.HALF_UP);
+                }
+            } else {
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鍚堝悓涓嶅瓨鍦�'));
+                saveBtnDisabled = true;
+                return null;
+            }
+
+            specialDeliveryAddress = new Account();
+            if (od.SpecialDeliveryAccount_D__c != null) {
+                specialDeliveryAddress = [select Id, Name, EnglishName__c, Address1__c, Phone, Fax from Account where Id = :od.SpecialDeliveryAccount_D__c];
+            }
+            specialDeliveryContact = new Contact();
+            if (od.SpecialDeliveryContact2_D__c != null) {
+                specialDeliveryContact = [select Id, Name, Email from Contact where Id = :od.SpecialDeliveryContact2_D__c];
+            }
+        }
+
+        Account acc = [select id, Name, EnglishName__c, Address1__c, Fax, Phone from Account where id = :od.AccountId];
+
+        PDF_N_NotifyParty1 = acc.Name;
+        PDF_NOTIFY_PARTY1 = acc.EnglishName__c;
+        PDF_N_Address1 = acc.Address1__c;
+        PDF_N_Add1 = od.PDF_B_Add__c;
+        PDF_N_TEL1 = acc.Phone;
+        PDF_N_FAX1 = acc.Fax;
+        PDF_N_CONTACT1 = od.EndUser__r.Name;
+        PDF_N_CONTACTPERSON1 = od.PDF_B_contactperson__c;
+
+        PDF_N_NotifyParty2 = specialDeliveryAddress.Name;
+        PDF_NOTIFY_PARTY2 = od.PDF_C_THECONSIGNE__c;
+        PDF_N_Address2 = specialDeliveryAddress.Address1__c;
+        PDF_N_Add2 = od.PDF_C_Add__c;
+        PDF_N_TEL2 = specialDeliveryAddress.Phone;
+        PDF_N_FAX2 = specialDeliveryAddress.Fax;
+        PDF_N_CONTACT2 = specialDeliveryContact.Name;
+        PDF_N_CONTACTPERSON2 = od.PDF_C_contactperson__c;
+
+        PDF_Forwarder1 = acc.EnglishName__c;
+        PDF_F_Add1 = od.PDF_B_Add__c;
+        PDF_F_TEL1 = acc.Phone;
+        PDF_F_FAX1 = acc.Fax;
+        PDF_F_ContactPerson1 = od.EndUser__r.Name;
+
+        PDF_Forwarder2 = od.PDF_C_THECONSIGNE__c;
+        PDF_F_Add2 = od.PDF_C_Add__c;
+        PDF_F_TEL2 = specialDeliveryAddress.Phone;
+        PDF_F_FAX2 = specialDeliveryAddress.Fax;
+        PDF_F_ContactPerson2 = od.PDF_C_contactperson__c;
+        Decimal sum = 0;
+        oiList = [select Id, PDF_Remark__c, Unit__c, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Product_ECCode__c, PriceBookEntry.Product2.Name, PriceBookEntry.Product2.registrationCode__c,
+                      Quantity, UnitPrice, Factory__c, PriceBookEntry.Hidden_flag__c, PriceBookEntry.Product2.Product_CCode__c
+                      from OrderItem
+                      where OrderId = :od.id
+                                      order by QuoteLineItemId, Id];
+        if ((Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') && (isNull == true || (isVer == true && isPtf == false))) {
+            Integer i = 0;
+            /*oiList = [select Id, PDF_Remark__c, Unit__c, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Product_ECCode__c, PriceBookEntry.Product2.Name, PriceBookEntry.Product2.registrationCode__c,
+                      Quantity, UnitPrice, Factory__c, PriceBookEntry.Hidden_flag__c, PriceBookEntry.Product2.Product_CCode__c
+                      from OrderItem
+                      where OrderId = :od.id
+                                      order by QuoteLineItemId, Id];*/
+            for (Order_Print_SetInfo__c prc : printSetInfo) {
+                if (i >= oiList.size()) {
+                    prc.U8__c = null;
+                    prc.Goods__c = null;
+
+                    prc.Qty__c = null;
+                    prc.Unit__c = '';
+                    prc.Remark__c = '';
+                    prc.UnitPrice__c = null;
+                    prc.UnitPrice__c = null;
+                    prc.discount__c = null;
+                    if (dis != null) {
+                        prc.discountprice__c = null;
+                        //prc.discountprice__c = prc.discountprice__c * setScale(2, System.RoundingMode.HALF_UP);
+                    } else {
+                        prc.discountprice__c = null;
+                    }
+                    prc.Total_AmountNDT__c = null;
+                    //Decimal.valueOf(String str)
+                    //sum += prc.Total_AmountNDT__c;
+                } else {
+                    prc.Id = null;
+                    prc.U8__c = oiList[i].PriceBookEntry.Product2.ProductCode;
+                    prc.Goods__c = oiList[i].PriceBookEntry.Product2.Product_ECCode__c;
+
+                    prc.Qty__c = oiList[i].Quantity.intValue();
+                    prc.Unit__c = oiList[i].Unit__c;
+                    prc.Remark__c = oiList[i].PDF_Remark__c;
+                    prc.UnitPrice__c = oiList[i].UnitPrice;
+                    prc.UnitPrice__c = prc.UnitPrice__c.setScale(2, System.RoundingMode.HALF_UP);
+                    prc.discount__c = (dis == null ? 0 : dis ) + '';
+                    if (dis != null) {
+                        prc.discountprice__c = (prc.UnitPrice__c * (1 - (dis / 100))).setScale(2, System.RoundingMode.HALF_UP) + '';
+                        //prc.discountprice__c = prc.discountprice__c * setScale(2, System.RoundingMode.HALF_UP);
+                    } else {
+                        prc.discountprice__c = prc.UnitPrice__c + '';
+                    }
+                    prc.Total_AmountNDT__c = Decimal.valueOf(prc.discountprice__c) * prc.Qty__c;
+                    //Decimal.valueOf(String str)
+                    sum += prc.Total_AmountNDT__c;
+                    if (isVer == true) {
+                        od.PDF_Is_True__c = true;
+                    }
+                }
+                i++;
+            }
+            if (sum != 0) {
+                printSetInfo[0].Total_AmountNDT__c = printSetInfo[0].Total_AmountNDT__c + (TotalMoney - sum - (od.ServiceFee__c == null ? 0 : od.ServiceFee__c) - (od.ShippingHandling_Tax__c == null ? 0 : od.ShippingHandling_Tax__c));
+            }
+        }
+
+        return null;
+    }
+
+    public PageReference printBtn() {
+        PageReference ref = null;
+        if (saveFunction() == true) {
+            ref = new Pagereference(baseUrl + '/apex/OrderPDF?id=' + od.id);
+            ref.setRedirect(true);
+        }
+        return ref;
+    }
+
+    public PageReference saveBtn() {
+        PageReference ref = null;
+        if (saveFunction() == true) {
+            ref = new Pagereference(baseUrl + '/apex/OrderContract?id=' + od.id + '&save=1');
+            ref.setRedirect(true);
+        }
+        return ref;
+    }
+
+    public boolean saveFunction() {
+        /*        Account acc = [select id, Name, EnglishName__c, Address1__c, Fax, Phone from Account where id = :od.AccountId];
+
+                if(od.PDF_NotifyFlag__c == '鏈�缁堢敤鎴�'){
+                    od.PDF_N_NotifyParty__c = acc.Name;
+                    od.PDF_NOTIFY_PARTY__c = acc.EnglishName__c;
+                    od.PDF_N_Address__c = acc.Address1__c;
+                    od.PDF_N_Add__c = od.PDF_B_Add__c;
+                    od.PDF_N_TEL__c = acc.Phone;
+                    od.PDF_N_FAX__c = acc.Fax;
+                    od.PDF_N_CONTACT__c = od.EndUser__r.Name;
+                    od.PDF_N_CONTACTPERSON__c = od.PDF_B_contactperson__c;
+                }else if(od.PDF_NotifyFlag__c == '鏀惰揣浜�'){
+                    od.PDF_N_NotifyParty__c = specialDeliveryAddress.Name;
+                    od.PDF_NOTIFY_PARTY__c = od.PDF_C_THECONSIGNE__c;
+                    od.PDF_N_Address__c = specialDeliveryAddress.Address1__c;
+                    od.PDF_N_Add__c = od.PDF_C_Add__c;
+                    od.PDF_N_TEL__c = specialDeliveryAddress.Phone;
+                    od.PDF_N_FAX__c = specialDeliveryAddress.Fax;
+                    od.PDF_N_CONTACT__c = specialDeliveryContact.Name;
+                    od.PDF_N_CONTACTPERSON__c = od.PDF_C_contactperson__c;
+                }else if(od.PDF_NotifyFlag__c == '鏂板缓濉啓'){
+
+                }
+
+                if(od.PDF_ForwarFlag__c == '鏈�缁堢敤鎴�'){
+                    od.PDF_Forwarder__c = acc.EnglishName__c;
+                    od.PDF_F_Add__c = od.PDF_B_Add__c;
+                    od.PDF_F_TEL__c = acc.Address1__c;
+                    od.PDF_F_FAX__c = acc.Phone;
+                    od.PDF_F_ContactPerson__c = od.EndUser__r.Name;
+                }else if(od.PDF_ForwarFlag__c == '鏀惰揣浜�'){
+                    od.PDF_Forwarder__c = od.PDF_C_THECONSIGNE__c;
+                    od.PDF_F_Add__c = od.PDF_C_Add__c;
+                    od.PDF_F_TEL__c = specialDeliveryAddress.Phone;
+                    od.PDF_F_FAX__c = specialDeliveryAddress.Fax;
+                    od.PDF_F_ContactPerson__c = od.PDF_C_contactperson__c;
+                }else if(od.PDF_ForwarFlag__c == '鏂板缓濉啓'){
+
+                }*/
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            List<Order_Print_SetInfo__c> updList = new List<Order_Print_SetInfo__c>();
+            List<Order_Print_SetInfo__c> delList = new List<Order_Print_SetInfo__c>();
+
+            List<NDT_Produce__c> nupdList = new List<NDT_Produce__c>();
+            List<NDT_Produce__c> ndelList = new List<NDT_Produce__c>();
+
+            List<OrderItem> oiupdList = new List<OrderItem>();
+
+            Integer lineNo = 0;
+            for (Order_Print_SetInfo__c ops : printSetInfo) {
+                if (ops.Goods__c != null && ops.Goods__c != '') {
+                    lineNo += 1;
+                    ops.No__c = lineNo;
+                    updList.add(ops);
+                    if (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') {
+                        if (ops.Unit__c == null || ops.Unit__c == '') {
+                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇疯緭鍏ュ叏閮ㄨ揣鐗╃殑鍗曚綅銆�'));
+                            return false;
+                        }
+                    }
+                }
+                if (ops.Id != null && (ops.Goods__c == null || ops.Goods__c == '')) {
+                    delList.add(ops);
+                }
+            }
+
+            for (NDT_Produce__c npr : ndtList) {
+                if (npr.U8_Code__c != null && npr.U8_Code__c != '') {
+                    nupdList.add(npr);
+                }
+                if (npr.Id != null && (npr.U8_Code__c == null || npr.U8_Code__c == '')) {
+                    ndelList.add(npr);
+                }
+            }
+            if (nupdList.size() == 0 && (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI')) {
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇疯緭鍏ラ檮浠跺唴瀹�'));
+                return false;
+            } else {
+                upsert nupdList;
+            }
+
+            if (ndelList.size() > 0 && (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI')) {
+                delete ndelList;
+            }
+
+            if ((isNull || (isVer == true && isPtf == false)) && (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI')) {
+                ndtdelList = [select id from Order_Print_SetInfo__c where Order__c = :Id order by No__c];
+                system.debug('ndtdelList:'+ndtdelList);
+                delete ndtdelList;
+            }
+
+            if (updList.size() == 0) {
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '璇疯緭鍏ヨ揣鐗╁悕绉板強瑙勬牸銆�'));
+                return false;
+            } else {
+                system.debug('updList:'+updList);
+                if (od != null && od.id != null) {
+                    update od;
+                }
+                upsert updList;
+            }
+            if (delList.size() > 0) {
+                system.debug('delList'+delList);
+                delete delList;
+            }
+
+           
+
+           
+
+            if (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') {
+                for (OrderItem oi : oiList ) {
+                    for ( Order_Print_SetInfo__c ops : printSetInfo ) {
+                        if (oi.PriceBookEntry.Product2.ProductCode == ops.U8__c) {
+                            OrderItem ordi = new orderItem();
+                            ordi.Id = oi.Id;
+                            ordi.Unit__c = ops.Unit__c;
+                            ordi.PDF_Remark__c = ops.Remark__c;
+                            oiupdList.add(ordi);
+                            break;
+                        }
+                    }
+                }
+                if (oiupdList.size() > 0 ) {
+                    update oiupdList;
+                }
+            }
+
+            return true;
+        } catch (Exception ex) {
+            system.debug('=====' + ex);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + '( ' + od.id + ' )'));
+            Database.rollback(sp);
+            return false;
+        }
+
+        return true;
+    }
+    //public String getRecordName() {
+    //   return 'Hello ' + (String)mysObject.get('name') + ' (' + (Id)mysObject.get('Id') + ')';
+    //}
+    public void init2() {
+        odpdf = new Order();
+        List<Order> opdfList = new List<Order>();
+
+        if (Id != null) {
+            opdfList = [select id, Discount_D__c, ShippingHandling_Tax__c, Name, OrderNumber, AccountId, OpportunityId, PaymentCondition__c, PaymentCondition_D__c, DeliveryDate__c, EndUser__r.Email, EndUser__r.Name, PDF_SignatureDate__c, PDF_SignaturePlace__c, PDF_B_Add__c, PDF_B_contactperson__c, PDF_SELLER__c,
+                        PDF_THE_SELLER__c, PDF_S_Adds__c, PDF_S_Address__c, PDF_S_TEL__c, PDF_S_FAX__c, PDF_S_Bank_Name__c, PDF_S_Bank_Address__c, PDF_S_Branch__c, PDF_QA__c, PDF_QA2__c, PDF_B_Department__c,
+                        PDF_S_Account_No__c, PDF_S_Swift_Code__c, PDF_S_Account_Name__c, PDF_C_Add__c, PDF_C_contactperson__c, PDF_NotifyFlag__c, PDF_B_Attri__c, Dealer__c,
+                        PDF_N_NotifyParty__c, PDF_NOTIFY_PARTY__c, PDF_N_Address__c, PDF_N_Add__c, PDF_N_TEL__c, PDF_N_FAX__c, PDF_N_CONTACT__c, PDF_I_Report__c,
+                        PDF_N_CONTACTPERSON__c, PDF_Sp_Shipment_Term__c, PDF_Sp_DestinationPort__c, PDF_Sp_DestinationPort_E__c, PDF_Sp_ShippingTerms__c, PDF_Sp_Freight__c, PDF_Forwarder__c,
+                        PDF_Sp_insurance__c, PDF_Sp_SHIPPINGMARK__c, PDF_Bi_AllBill__c, PDF_Bi_manufacturers__c, PDF_Bi_manufacturersEn__c, PDF_Bi_q1__c, PDF_Bi_airway__c, PDF_SignaturePlaces__c,
+                        PDF_Bi_copyairway__c, PDF_Bi_invoice__c, PDF_Bi_Insurance__c, PDF_Bi_Packing__c, PDF_Bi_Quality__c, PDF_Bi_Origin__c, PDF_F_FAX__c, CustomerContractPrice__c,
+                        PDF_Bi_Non_Wooden__c, PDF_Co_Contract__c, PDF_Co_Contract_E__c, PDF_Co_BContra__c, PDF_Co_BContra_E__c, PDF_Co_SContra__c, PDF_Co_SContra_E__c, PDF_C_Consignee__c, PDF_C_THECONSIGNE__c, PDF_F_TEL__c,
+                        PDF_C_Address__c, PDF_C_TEL__c, PDF_C_FAX__c, PDF_C_CONTACT__c , PDF_G_TrAndPre__c , PDF_G_SpecNo__c, PDF_F_Add__c, PDF_F_ContactPerson__c,
+                        Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c, Shipment_Term__c, Shipment_Term_D__c, Shipment_Term2__c, Shipment_Term2_D__c,
+                        SpecialDeliveryAccount__c, SpecialDeliveryAccount_D__c, SpecialDeliveryContact2__c, SpecialDeliveryContact2_D__c, PDF_Order_No__c, DeliveryTimeText__c, DeliveryTimeTextEn__c, Total_price_E__c, ContractPriceTotal__c,
+                        PDF_Shipment_Term2_Text__c, PDF_PaymentTerms__c, PDF_PaymentTerms_E__c, PDF_Sign_Name__c, PDF_Sign_Title__c
+                        from Order
+                        where id = :Id];
+            ndtList = [select id, U8_Code__c, Quantity__c, Part_Number__c, Name_of_Goods__c from NDT_Produce__c where NDTOrder__c = :Id order by Id];
+        }
+        if (opdfList.size() > 0) {
+            odpdf = opdfList[0];
+            printSetInfo = [select id, U8__c, discount__c, discountprice__c, PriceNDT__c, Total_AmountNDT__c, Remark__c, Order__c, No__c, Goods__c, Unit__c, Qty__c , UnitPrice__c, Total_Amount__c, NameOfGood__c from Order_Print_SetInfo__c where Order__c = :odpdf.Id order by No__c];
+        }
+        TrAndPre = Decimal.valueOf(odpdf.PDF_G_TrAndPre__c == null ? '0' : odpdf.PDF_G_TrAndPre__c);
+        dis = odpdf.Discount_D__c;
+        Account acc = [select id, Name, EnglishName__c, Sub_Use__c, Address1__c, Fax, Phone from Account where id = :odpdf.AccountId];
+        Opp = [select id, Name, Amount, ProductSegment__c, SubDealer__c, TradeType__c, SyncedQuoteId, Quote_TotalPrice__c from Opportunity where id = :odpdf.OpportunityId];
+
+        specialDeliveryAddress = new Account();
+        if (odpdf.SpecialDeliveryAccount_D__c != null) {
+            specialDeliveryAddress = [select Id, Name, EnglishName__c, Address1__c, Phone, Fax from Account where Id = :odpdf.SpecialDeliveryAccount_D__c];
+        }
+        specialDeliveryContact = new Contact();
+        if (odpdf.SpecialDeliveryContact2_D__c != null) {
+            specialDeliveryContact = [select Id, Name, Email from Contact where Id = :odpdf.SpecialDeliveryContact2_D__c];
+        }
+
+        List<Quote> quoList = [select Id, Name, CreatedDate, OpportunityId, Opportunity.Dealer__c, Opportunity.DealerSalesStaffName__c, AccountId, PrintPrice__c, TotalPrice,
+                               DeliveryLeadTime__c, PaymentTerms__c, ExpirationDate, Warranty__c, Opportunity.TradeType__c,
+                               SetName1__c, SetQty1__c, SetName2__c, SetQty2__c, SetName3__c, SetQty3__c, SetName4__c, SetQty4__c, SetName5__c, SetQty5__c,
+                               SetName6__c, SetQty6__c, SetName7__c, SetQty7__c, SetName8__c, SetQty8__c, SetName9__c, SetQty9__c, SetName10__c, SetQty10__c,
+                               SetName11__c, SetQty11__c, SetName12__c, SetQty12__c, SetName13__c, SetQty13__c, SetName14__c, SetQty14__c, SetName15__c, SetQty15__c,
+                               SetName16__c, SetQty16__c, SetName17__c, SetQty17__c, SetName18__c, SetQty18__c, SetName19__c, SetQty19__c, SetName20__c, SetQty20__c,
+                               SetName21__c, SetQty21__c, SetName22__c, SetQty22__c, SetName23__c, SetQty23__c, SetName24__c, SetQty24__c, SetName25__c, SetQty25__c,
+                               SetName26__c, SetQty26__c, SetName27__c, SetQty27__c, SetName28__c, SetQty28__c, SetName29__c, SetQty29__c, SetName30__c, SetQty30__c
+                               from Quote
+                               where id = :Opp.SyncedQuoteId];
+
+        Quote quo = new Quote();
+        printRecords = new List<SetInfo>();
+        //Decimal TotalMoney = 0;
+        TotalMoney = 0;
+        if (Opp.Amount != null) {
+            TotalMoney = odpdf.ContractPriceTotal__c; //Opp.Quote_TotalPrice__c;
+            if ((Opp.ProductSegment__c == 'BS' || Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI' ) && Opp.TradeType__c == 'Tax Exemption') {
+                TotalMoney = TotalMoney.setScale(2, System.RoundingMode.HALF_UP);
+            } else {
+                TotalMoney = TotalMoney.setScale(0, System.RoundingMode.HALF_UP);
+            }
+        }
+
+        if (quoList.size() > 0) {
+            //璇环閲屾湁鍚屾鎬荤殑鎶ヤ环锛屼骇鍝佷娇鐢ㄦ姤浠烽噷鐨勪骇鍝侊紝
+            quo = quoList[0];
+            // 鎶ヤ环浜у搧淇℃伅
+            List<QuoteLineItem> qliList = [select Id, QuoteId, Quantity, UnitPrice, Subtotal, TotalPrice, Description, Set__c,
+                                           Product2Id, Product2.ProductCode, Product2.Description, Product2.Name, Product2.Product_ECCode__c
+                                           from QuoteLineItem
+                                           where QuoteId = :Opp.SyncedQuoteId
+                                                   //order by Set__c, LineNumber];
+                                                   order by Id];
+
+            //pageCnt = 1;
+            String strSetCnt = System.Label.QuoteEntryMaxSet;
+            Integer intSetCnt = Integer.valueOf(strSetCnt);
+            Integer cnt = 1;
+            /*            for (Integer i = 1; i <= intSetCnt; i++) {
+                            String sName = (String) quo.get('SetName' + i + '__c');
+                            if (sName != null && sName.length() > 0) {
+                                String setName = 'set' + (i < 10 ? '0' : '') + i;
+                                SetInfo si = new SetInfo(cnt, setName, quo, qliList);
+                                printRecords.add(si);
+                                //pageCnt += si.pCnt;
+                                cnt += 1;
+                            }
+                        }*/
+            SetInfo sio = new SetInfo(1, qliList);
+            printRecords.add(sio);
+
+        } else {
+            //璇环閲屾病鏈夊悓姝ヤ腑鐨勬姤浠凤紝浜у搧浣跨敤璇环閲岀殑浜у搧锛�
+            List<OpportunityLineItem> oliList = [select Id, TotalPrice, Subtotal, Quantity, Product2Id, Product2.ProductCode, Product2.Name,
+                                                 Product2.Description, Description, OpportunityId, Product2.Product_ECCode__c
+                                                 from OpportunityLineItem
+                                                 where OpportunityId = :odpdf.OpportunityId
+                                                         order by Id];
+            SetInfo sio = new SetInfo(1, oliList);
+            printRecords.add(sio);
+        }
+
+        contra = new Contract(odpdf, acc, specialDeliveryAddress.Name, specialDeliveryAddress.Address1__c, specialDeliveryAddress.Phone, specialDeliveryAddress.Fax, specialDeliveryContact.Name);
+        //OSSA澶栬锤濂楄淇℃伅鑷姩甯﹀嚭
+
+
+
+    }
+
+
+    private static Map<String, String> QAapiMap = new Map<String, String> {
+        '12涓湀' => 'twelve(12) months',
+        '15涓湀' => 'fifteen(15) months',
+        '18涓湀' => 'eighteen(18) months',
+        '21涓湀' => 'twenty-one(21) months',
+        '24涓湀' => 'twenty-four(24) months',
+        '27涓湀' => 'twenty-seven(27) months',
+        '30涓湀' => 'thirty(30) months',
+        '33涓湀' => 'thirty-three(33) months',
+        '36涓湀' => 'thirty-six(36) months',
+        '48涓湀' => 'forty-eight(48) months',
+        '60涓湀' => 'sixty(60) months',
+        '39涓湀' => 'thirty-nine (39) months',
+        '51涓湀' => 'fifty-one (51) monthss',
+        '63涓湀' => 'sixty-three (63) months'
+    };
+
+    public class SetInfo {
+        private Integer maxLine = 36;
+
+        public String units {get; private set;}
+        public String description {get; private set;}
+        public Integer qty {get; private set;}
+        public Decimal total {get; private set;}
+        public Decimal cost {get; private set;}
+        public List<List<LineInfo>> setPage {get; private set;}
+        public Integer pCnt {get; private set;}
+
+        /*        public SetInfo(Integer no, String setName, Quote info, List<QuoteLineItem> qliList) {
+                    units = String.valueOf(no);
+                    String fieldName = setName.substring(3);
+                    fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
+                    description = (String) info.get('SetName' + fieldName + '__c');
+                    Decimal d_qty = (Decimal) info.get('SetQty' + fieldName + '__c');
+                    qty = d_qty == null ? 1 : d_qty.intValue();
+                    total = 0;
+                    cost = 0;
+
+                    setPage = new List<List<LineInfo>>();
+                    //pCnt = 0;
+                    Integer i = 0;
+                    //Integer tmp = 0;
+                    List<LineInfo> sPage = new List<LineInfo>();
+                    for (QuoteLineItem qli : qliList) {
+                        if (qli.Set__c == setName) {
+                            i += 1;
+                            LineInfo line = new LineInfo(i,qli, qty);
+                            //LineInfo line = new LineInfo(i, qli, 1, isPrintPrice=='true');
+                            if (i > 1) {
+                                sPage.add(line);
+                                //tmp += line.lineCost;
+                            } else {
+                                //system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
+                                sPage = new List<LineInfo>();
+                                setPage.add(sPage);
+                                sPage.add(line);
+                                //tmp = line.lineCost;
+                                //pCnt += 1;
+                            }
+                            cost += line.subTotal;
+                            total += line.subTotal * qty;
+                        }
+                    }
+                    //system.debug('=====pCnt:' + pCnt);
+                }*/
+
+        public SetInfo(Integer no, List<QuoteLineItem> quoLinItemList) {
+            units = String.valueOf(no);
+            description = '闈炲瑁�';
+            qty = 1;
+            total = 0;
+            cost = 0;
+
+            setPage = new List<List<LineInfo>>();
+            //pCnt = 0;
+            Integer i = 0;
+            //Integer tmp = 0;
+            List<LineInfo> sPage = new List<LineInfo>();
+            for (QuoteLineItem qli : quoLinItemList) {
+                i += 1;
+                LineInfo line = new LineInfo(i, qli);
+                if (i > 1) {
+                    sPage.add(line);
+                    //tmp += line.lineCost;
+                } else {
+                    //system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
+                    sPage = new List<LineInfo>();
+                    setPage.add(sPage);
+                    sPage.add(line);
+                    //tmp = line.lineCost;
+                    //pCnt += 1;
+                }
+                cost += line.subTotal;
+                total += line.subTotal;
+            }
+
+        }
+
+        public SetInfo(Integer no, List<OpportunityLineItem> oppLinItemList) {
+            units = String.valueOf(no);
+            description = '闈炲瑁�';
+            qty = 1;
+            total = 0;
+            cost = 0;
+            setPage = new List<List<LineInfo>>();
+            //pCnt = 0;
+            Integer i = 0;
+            //Integer tmp = 0;
+            List<LineInfo> sPage = new List<LineInfo>();
+            for (OpportunityLineItem oli : oppLinItemList) {
+                i += 1;
+                LineInfo line = new LineInfo(i, oli);
+                if (i > 1) {
+                    sPage.add(line);
+                    //tmp += line.lineCost;
+                } else {
+                    //system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
+                    sPage = new List<LineInfo>();
+                    setPage.add(sPage);
+                    sPage.add(line);
+                    //tmp = line.lineCost;
+                    //pCnt += 1;
+                }
+                cost += line.subTotal;
+                total += line.subTotal;
+            }
+
+        }
+
+    }
+
+
+    // PDF鏄庣粏琛屼俊鎭�
+    public class LineInfo {
+        public Integer lineNo {get; private set;}
+        public String productName {get; private set;}
+        public String productEC {get; private set;}
+        public Decimal subTotal {get; private set;}
+        public Integer quantity {get; private set;}
+        public String U8Code {get; private set;}
+        /*public LineInfo(Integer i, QuoteLineItem info, Integer qty) {
+            lineNo = i;
+            productName = info.Product2.Name;
+            productEC = info.Product2.Product_ECCode__c;
+            Decimal d_quantity = info.Quantity / qty;
+            quantity = d_quantity.intValue();
+            subTotal = info.TotalPrice / qty;
+        }*/
+
+        public LineInfo(Integer i, QuoteLineItem quoLinItem) {
+            lineNo = i;
+            productName = quoLinItem.Product2.Name;
+            productEC = quoLinItem.Product2.Product_ECCode__c;
+            quantity = quoLinItem.Quantity.intValue();
+            subTotal = quoLinItem.TotalPrice;
+            U8Code = null;
+        }
+
+        public LineInfo(Integer i, OpportunityLineItem oppLinItem) {
+            lineNo = i;
+            productName = oppLinItem.Product2.Name;
+            productEC = oppLinItem.Product2.Product_ECCode__c;
+            quantity = oppLinItem.Quantity.intValue();
+            subTotal = oppLinItem.TotalPrice;
+            U8Code  = oppLinItem.Product2.ProductCode;
+        }
+
+    }
+
+
+
+    class Contract {
+        public String SignatureDate { get; private set; } //绛捐鏃ユ湡涓�
+        public String SignatureDates { get; private set; } //绛捐鏃ユ湡鑻�
+        public Order order { get; private set; }
+        public Account account { get; private set; }
+        public String AllBills { get; private set; }
+        public String QAeng { get; private set; }
+        public String QAeng2 { get; private set; }
+        public String ShippingTerms { get; private set; }
+
+        public String pdf_c_consignee { get; private set; }
+        public String pdf_c_address { get; private set; }
+        public String pdf_c_tel { get; private set; }
+        public String pdf_c_fax { get; private set; }
+        public String pdf_c_contact { get; private set; }
+
+        public Contract(Order o, Account acc, String name, String address, String phone, String fax, String name2) {
+            order = o;
+            account = acc;
+            SignatureDate = o.PDF_SignatureDate__c == null ? '' : o.PDF_SignatureDate__c.format('yyyy骞碝M鏈坉d鏃�');
+            SignatureDates = o.PDF_SignatureDate__c == null ? '' : o.PDF_SignatureDate__c.formatGMT('d-MMM-yyyy');
+            if (o.PDF_Bi_AllBill__c == '闅忚揣') {
+                AllBills = 'with';
+            } else if (o.PDF_Bi_AllBill__c == '涓嶉殢璐�') {
+                AllBills = 'not with';
+            }
+            QAeng = QAapiMap.get(o.PDF_QA__c);
+            QAeng2 = QAapiMap.get(o.PDF_QA2__c);
+            if (o.PDF_Sp_ShippingTerms__c == '娴疯繍') {
+                ShippingTerms = 'by sea';
+            } else if (o.PDF_Sp_ShippingTerms__c == '绌鸿繍') {
+                ShippingTerms = 'by air';
+            } else if (o.PDF_Sp_ShippingTerms__c == '闄嗚繍') {
+                ShippingTerms = 'by land';
+            }
+
+            pdf_c_consignee = name;
+            pdf_c_address = address;
+            pdf_c_tel = phone;
+            pdf_c_fax = fax;
+            pdf_c_contact = name2;
+        }
+    }
+
+    public class DetailInfo {
+        public OrderItem orderItem { get; set; }
+        public Integer lineno { get; set; }
+        public String otcode { get; set; }
+        public String eccode { get; set; }
+        public Integer quantity { get; set; }
+        public Decimal price { get; set; }
+        public Decimal totalprice { get; set; }
+        public String factory { get; set; }
+        public String ccode { get; set; }
+        public String name {get; set;}
+        public String registrationCode {get; set;}
+        public Decimal price_d {get; set;}
+        public String discount {get; set;}
+
+        public DetailInfo(Integer line) {
+            orderItem = new OrderItem();
+            lineno = line;
+            otcode = null;
+            eccode = null;
+            quantity = null;
+            price = null;
+            totalprice = null;
+            factory = null;
+            ccode = null;
+            name = null;
+            registrationCode = null;
+            discount = null;
+        }
+
+        public DetailInfo(Integer line, OrderItem oi, Decimal dis) {
+            discount = dis + '%';
+            orderItem = oi;
+            lineno = line;
+            otcode = oi.PriceBookEntry.Product2.ProductCode;
+            otcode = otcode.startsWith('00000000000') ? otcode.substring(11) : otcode;
+            eccode = oi.PriceBookEntry.Product2.Product_ECCode__c;
+            //eccode = eccode.startsWith('00000000000') ? eccode.substring(11) : eccode;
+            Decimal qty = oi.Quantity;
+            quantity = qty.intValue();
+            price = oi.UnitPrice;
+            price = price.setScale(2, System.RoundingMode.HALF_UP);
+            totalprice = qty * price;
+            totalprice = totalprice.setScale(2, System.RoundingMode.HALF_UP);
+            factory = oi.Factory__c;
+            ccode = oi.PriceBookEntry.Product2.Product_CCode__c;
+            name = oi.PriceBookEntry.Product2.Name;
+            registrationCode = oi.PriceBookEntry.Product2.registrationCode__c;
+            if (dis != null ) {
+                price_d = totalprice * (1 - (dis / 100));
+                price_d = price_d.setScale(2, System.RoundingMode.HALF_UP);
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderPdfController.cls-meta.xml b/scr/classes/OrderPdfController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderPdfController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderPdfControllerTest.cls b/scr/classes/OrderPdfControllerTest.cls
new file mode 100644
index 0000000..fccaee2
--- /dev/null
+++ b/scr/classes/OrderPdfControllerTest.cls
@@ -0,0 +1,601 @@
+@isTest
+private class OrderPdfControllerTest {
+
+    @isTest static void test_init() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'IE'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id,
+            ProductSegment__c = 'IE'
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'USD';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'USD',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            Role  = 'End user',
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'IESalesContract'];
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'USD',
+            AccountId = user.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = contact.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderContract?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdfController controller = new OrderPdfController();
+
+        controller.init();
+
+        controller.saveBtn();
+
+        controller.printBtn();
+    }
+
+    @isTest static void test_init2() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account parent = new Account(
+            Name = '*',
+            FacilityName__c = 'parent',
+            PostCode__c = '123456'
+        );
+        insert parent;
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ParentId = parent.Id
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'USD';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'USD',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Set__c = 'set01'
+        );
+        insert qli;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            Role  = 'End user',
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'IESalesContract'];
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'USD',
+            AccountId = user.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = contact.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderPdf?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdfController controller = new OrderPdfController();
+
+        //controller.init();
+        controller.init2();
+        //controller.init();
+    }
+
+    @isTest static void test_init2_2() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account parent = new Account(
+            Name = '*',
+            FacilityName__c = 'parent',
+            PostCode__c = '123456'
+        );
+        insert parent;
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ParentId = parent.Id
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'NDT',
+            ProductSegment__c = 'NDT',
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'USD';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'USD',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            Role  = 'End user',
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'IESalesContract'];
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'USD',
+            AccountId = user.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = contact.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderPdf?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdfController controller = new OrderPdfController();
+
+        controller.init2();
+    }
+ @isTest static void test_init2_3() {
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer NDT'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'NDT'
+        );
+        Account delivery = new Account(
+            Name = '*',
+            FacilityName__c = 'delivery',
+            PostCode__c = '123456',
+            ProductSegment__c = 'NDT'
+        );
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id,
+            ProductSegment__c = 'NDT'
+        );
+        insert new List<Account> {buyer, delivery, user};
+
+        Contact delivery_contact = new Contact(
+            LastName = 'delivery_contact',
+            AccountId = delivery.Id
+        );
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert new List<Contact> {delivery_contact, contact};
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'NDT',
+            ProductSegment__c = 'NDT',
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'USD'
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'USD';
+        insert entry1;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'USD',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Tax Exemption',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Dealer__c = buyer.Id,
+            SpecialDeliveryAddress__c = delivery.Id,
+            SpecialDeliveryContact__c = delivery_contact.Id,
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            Role  = 'End user',
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'IESalesContract'];
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'USD',
+            AccountId = user.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = contact.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        PageReference page = new PageReference('/apex/OrderContract?id=' + order.Id);
+        System.Test.setCurrentPage(page);
+        OrderPdfController controller = new OrderPdfController();
+
+        controller.init();
+
+        controller.saveBtn();
+
+        controller.printBtn();
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/OrderPdfControllerTest.cls-meta.xml b/scr/classes/OrderPdfControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderPdfControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderShippingNotificationController.cls b/scr/classes/OrderShippingNotificationController.cls
new file mode 100644
index 0000000..0f541b6
--- /dev/null
+++ b/scr/classes/OrderShippingNotificationController.cls
@@ -0,0 +1,145 @@
+public with sharing class OrderShippingNotificationController {
+
+    public String type { get; set; }
+
+    // 璁㈠崟
+    public Order ra { get; set; }
+    // 璁㈠崟ID
+    public Id raid { get; private set; }
+    // 璁㈠崟璁板綍绫诲瀷
+    public String recordtype { get; private set; }
+    
+    public Boolean hasError { get; private set; }
+    public String baseUrl { get; private set; }    
+
+    public OrderShippingNotificationController() {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+        type = ApexPages.currentPage().getParameters().get('recordtype');
+
+    }
+
+    public OrderShippingNotificationController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+        type = ApexPages.currentPage().getParameters().get('recordtype');
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+        hasError = false;
+        ra = new Order();
+        List<Order> raList = [select Id, Name,ContractCode__c, ShippingNotes__c,RecordTypeId,ShippingRecieverEmailAdr__c, OppExpectedDeliveryDate__c, ContractLink__c from Order where Id = :raid];
+        if (raList.size() > 0) {
+            ra = raList[0];
+        }
+       
+        ra.ShippingNotes__c = '鏈熸湜鍙戣揣鏃ユ湡:' + ra.OppExpectedDeliveryDate__c;
+
+    }
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+
+        String ShippingNotes = ra.ShippingNotes__c;
+        if (ShippingNotes == null || ShippingNotes.trim().length() == 0) {
+            ra.ShippingNotes__c.addError('璇疯緭鍏ュ唴瀹广��');
+            hasError=true;
+            return null;
+        }
+
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+        // 鐩稿叧鐢ㄦ埛妫�绱�
+        List<Id> ccList = new List<Id>();
+//      ccList.add(ra.Person_In_Charge__c);
+//      ccList.add(ra.ApplyUser__c);
+//        if (cc.JingliApprovalManager__c != null) {
+//            ccList.add(cc.JingliApprovalManager__c);
+//        }
+//       if (cc.SalesManager__c != null) {
+//            ccList.add(cc.SalesManager__c);
+//        }
+//        if (cc.BuchangApprovalManager__c != null) {
+//            ccList.add(cc.BuchangApprovalManager__c);
+//        }
+//        if (cc.BuchangApprovalManagerSales__c != null) {
+//            ccList.add(cc.BuchangApprovalManagerSales__c);
+//        }
+//        if (cc.ZongjianApprovalManager__c != null) {
+//            ccList.add(cc.ZongjianApprovalManager__c);
+//        }
+        Map<Id, User> userMap = new Map<Id, User>([
+            select Id, Name, Email from User where Id in :ccList
+        ]);
+        // 鏀朵俊鑰�
+        String toName = '';
+        List<String> toMailList = new List<String>();
+        toName = ra.ShippingRecieverEmailAdr__c;
+        toMailList.add(ra.ShippingRecieverEmailAdr__c);
+
+        // 鍘熷簲绛旀矡閫氫俊鎭�
+//        String oldShippingNotes = ra.ShippingNotes__c;
+        // 鐜板簲绛旀矡閫氫俊鎭�
+//        String URL = baseUrl + '/production/' + ra.Id;
+        String temp = '';
+        temp += ra.ShippingNotes__c;
+/***
+        if (oldShippingNotes != null && oldShippingNotes.trim().length() > 0) {
+            temp += '\n\n' + oldShippingNotes;
+        } else {
+            //浜�2016-07-01鍔犲叆<a></a>
+            temp += '\n\n澶囧搧鍊熷嚭鐢宠閾炬帴锛� ' + baseUrl + '/' + ra.Id +' ';
+        }
+***/
+        try {
+            // 鏇存柊搴旂瓟娌熼��
+            ra.ShippingNotes__c = temp;
+
+    //        update ra;
+    //        ra.ShippingNotes__c = '';
+
+            //Create a dummy instance of outbound email object
+    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
+            //set a roolback point
+    //        Savepoint sp = Database.setSavepoint();
+            //set desired email template id
+    //        message.templateId = 'xxxxxx';
+            //set the target object record id(this is mandatory while using email template)
+    //        Id recId = [select Id from Contact where Email != null limit 1].id;
+    //        message.targetObjectId = recId;
+            //fire dummy email
+    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
+            //roll back to savepoint so that email is not sent
+    //        Database.rollback(sp);
+            //Create insatnce of actual email
+            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
+            //get the bode from above dummy instance and set it to your actual email
+            //messageNEW.HTMLBody = message.getHtmlBody();
+              messageNEW.HTMLBody = temp;
+              messageNEW.Subject = '鍙戣揣鎻愰啋:璁㈠崟'+ ra.ContractCode__c;
+            //messageNEW.PlainTextBody = temp;
+            //set desired email addresses
+            messageNEW.setCharset('UTF-8');
+            messageNEW.toAddresses = toMailList;
+ //           messageNEW.ccAddresses = ccMailList;
+            //send the mail
+            messaging.sendEmail(new Messaging.SingleEmailMessage[] {messageNEW});
+            ra.ShippingNotes__c = '';
+
+
+        } catch (Exception ex) {
+            system.debug('=====' + ex.getMessage());
+            hasError = true;
+            ApexPages.addMessages(ex);
+            return null;
+        }
+
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderShippingNotificationController.cls-meta.xml b/scr/classes/OrderShippingNotificationController.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/OrderShippingNotificationController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderShippingNotificationControllerTest.cls b/scr/classes/OrderShippingNotificationControllerTest.cls
new file mode 100644
index 0000000..37cb0ae
--- /dev/null
+++ b/scr/classes/OrderShippingNotificationControllerTest.cls
@@ -0,0 +1,79 @@
+@isTest
+public with sharing class OrderShippingNotificationControllerTest {
+
+    static testMethod void myTest1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+       
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            ExpectedDeliveryDate__c = Date.today(),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            ShippingNotes__c = '',
+            ShippingRecieverEmailAdr__c = ''
+        );
+        insert odr;
+        
+         //鍙戣揣鎻愰啋杈撳叆鐢婚潰
+        PageReference page = new PageReference('/apex/OrderShippingNotification?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        
+        OrderShippingNotificationController controller = new OrderShippingNotificationController();
+        
+
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name,ContractCode__c, ShippingNotes__c,ShippingRecieverEmailAdr__c, OppExpectedDeliveryDate__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init();
+        System.assertEquals('鏈熸湜鍙戣揣鏃ユ湡:' + odr1.OppExpectedDeliveryDate__c, controller.ra.ShippingNotes__c);
+        System.assertEquals(odr1.ShippingRecieverEmailAdr__c, controller.ra.ShippingRecieverEmailAdr__c);
+        
+        
+        //鍙戦�佹寜閽�
+        controller.ra.ShippingNotes__c = 'test1';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+
+
+
+    }
+
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/OrderShippingNotificationControllerTest.cls-meta.xml b/scr/classes/OrderShippingNotificationControllerTest.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/OrderShippingNotificationControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderSplitRatioController.cls b/scr/classes/OrderSplitRatioController.cls
new file mode 100644
index 0000000..3074fc8
--- /dev/null
+++ b/scr/classes/OrderSplitRatioController.cls
@@ -0,0 +1,85 @@
+public without sharing class OrderSplitRatioController {
+	public String UsId { get; set; }
+	public String BsAgm { get; set; }
+	public String AppSta { get; set; }
+	public String new_profileId { get; set; }
+	String oldResponse;
+	//璁㈠崟
+	public Order ord { get; set; }
+	public Order ra1 { get; set; }
+    public Order cc { get; set; }
+    public Boolean hasError { get; private set; }
+	// 璁㈠崟ID
+    public Id raid { get; private set; }
+    public String baseUrl { get; private set; }
+
+	public OrderSplitRatioController() {
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = ApexPages.currentPage().getParameters().get('raid');
+	}
+	public OrderSplitRatioController(ApexPages.StandardController stdController) {
+        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        raid = stdController.getId();
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public void init() {
+    	//鏂扮殑鑾峰彇浜哄憳绠�妗D
+        new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        new_profileId = new_profileId.substring(0,15);
+    	AppSta = '';
+        hasError = false;
+        ord = new Order();
+        cc = new Order();
+        List<Order> raList = [select Id, Name, Dealer__c,SplitRatio__c,SplitRatiotext__c,CrossCooperativeDealerText__c,SplitRatioFormule__c,BS_AsistGenManger_BS__c,ApproveStatus__c from Order where Id = :raid];
+        UsId = UserInfo.getUserId().subString(0, 15);
+        if (raList.size() > 0) {
+            ord = raList[0];
+            BsAgm = raList[0].BS_AsistGenManger_BS__c;
+            if(BsAgm != null){
+                BsAgm = BsAgm.substring(0, 15);
+            }
+
+            if(raList[0].ApproveStatus__c == 'Submit' || raList[0].ApproveStatus__c == 'OrderSubmit'){
+            	AppSta = '1';
+            }
+        }
+        /*System.debug('AppSta='+AppSta);
+        System.debug('new_profileId='+new_profileId);
+        System.debug('BsAgm='+BsAgm);*/
+    }
+    
+     // 鐢婚潰鍒濆鍖� UP
+    public void init1() {
+    	AppSta = '';
+        hasError = false;
+        ra1 = new Order();
+        List<Order> ra1List = [select Id, Name, Dealer__c,Dealer_A__r.Name,Dealer_B__r.Name ,SplitRatio__c,SplitRatiotext__c,CrossCooperativeDealerText__c,SplitRatioFormule__c,BS_AsistGenManger_BS__c from Order where Id = :raid];
+        UsId = UserInfo.getUserId().subString(0, 15);
+        if (ra1List.size() > 0) {
+            ra1 = ra1List[0];
+        }
+    }
+
+
+
+    // 淇濆瓨鎸夐挳
+    public PageReference saveBtn() {
+        hasError = false;
+        String response = ra1.SplitRatio__c;
+       /* if (String.isBlank(ra1.SplitRatio__c)) {
+    		String SplitRatiotext = ra1.Dealer_A__r.Name +' '+ ra1.SplitRatio__c +' '+ ra1.Dealer_B__r.Name;
+    		ra1.SplitRatiotext__c = SplitRatiotext;
+            ra1.
+    	    update ra1;
+    	}else {
+    		update ra1;
+    	}*/
+        ra1.dealer_A_Name__c = ra1.Dealer_A__r.Name;
+        ra1.dealer_B_Name__c = ra1.Dealer_B__r.Name;
+        update ra1;
+        
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderSplitRatioController.cls-meta.xml b/scr/classes/OrderSplitRatioController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrderSplitRatioController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderSplitRatioControllerTest.cls b/scr/classes/OrderSplitRatioControllerTest.cls
new file mode 100644
index 0000000..8c82908
--- /dev/null
+++ b/scr/classes/OrderSplitRatioControllerTest.cls
@@ -0,0 +1,282 @@
+@isTest
+private class OrderSplitRatioControllerTest {
+   static testMethod void myTest1() {
+   		List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        String AppSta = '';
+        String BsAgm = '';
+        String new_profileId = '';
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS'
+        );
+        insert buyer;
+
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+        
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'BS'
+        );
+        insert pricebook;
+        
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = accIE.Id
+        );
+        insert contact;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            Role = 'End user',
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order odr = new Order(
+            Name = '',
+            CurrencyIsoCode = 'CNY',
+            Status = 'Draft',
+            CrossCooperativeDealerText__c = 'hehe',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Submit',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id,
+            BS_AsistGenManger_BS__c = '00528000000YSeOAAW'
+        );
+        insert odr;
+        
+         //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OrderSplitRatioPopUp?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        
+        OrderSplitRatioController controller = new OrderSplitRatioController();
+        
+
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name, Dealer__c,SplitRatio__c,CrossCooperativeDealerText__c,SplitRatioFormule__c,BS_AsistGenManger_BS__c,ApproveStatus__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        
+        //鍙戦�佹寜閽�
+        controller.ra1.SplitRatio__c = '5 : 5';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+
+    static testMethod void myTest2() {
+    	List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        String AppSta = '';
+        String BsAgm = '';
+        String new_profileId = '';
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS'
+        );
+        insert buyer;
+
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'BS'
+        );
+        insert pricebook;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = accIE.Id
+        );
+        insert contact;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            Role = 'End user',
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order odr = new Order(
+            Name = '',
+            CurrencyIsoCode = 'CNY',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Submit',
+            OpportunityId = opp.Id,
+            CrossCooperativeDealerText__c = 'hehe',
+            EffectiveDate = Date.today(),
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id,
+            BS_AsistGenManger_BS__c = '00528000000YSeOAAW'
+        );
+        insert odr;
+        
+        //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OrderSplitRatioPopUp?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        OrderSplitRatioController controller = new OrderSplitRatioController();
+        
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name, Dealer__c,SplitRatio__c,CrossCooperativeDealerText__c,SplitRatioFormule__c,BS_AsistGenManger_BS__c,ApproveStatus__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init1();
+        //System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1.SplitRatio__c = '5 : 5';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+     static testMethod void myTest3() {
+     	List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+         List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+         String AppSta = '';
+         String BsAgm = '';
+         Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCodeD__c='000000',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'BS'
+        );
+        insert pricebook;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = accIE.Id
+        );
+        insert contact;
+         
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            //Dealer__c = '鍛靛懙',
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct'
+        );
+        insert opp;
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            Role = 'End user',
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Order odr = new Order(
+            Name = '',
+            CurrencyIsoCode = 'CNY',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Submit',
+            OpportunityId = opp.Id,
+            CrossCooperativeDealerText__c = 'hehe',
+            EffectiveDate = Date.today(),
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id,
+            BS_AsistGenManger_BS__c = '00528000000YSeOAAW'
+        );
+        insert odr;
+        
+        //鐢婚潰杩佺Щ--鐣欒█鐢婚潰
+        PageReference page = new PageReference('/apex/OrderSplitRatioPopUp?raid=' + odr.Id );
+        System.Test.setCurrentPage(page);
+        OrderSplitRatioController controller = new OrderSplitRatioController();
+        
+        //鍙栧緱璁㈠崟
+        Order odr1 = [select Id, Name, Dealer__c,SplitRatio__c,CrossCooperativeDealerText__c,SplitRatioFormule__c,BS_AsistGenManger_BS__c,ApproveStatus__c from Order where Id = :odr.Id];
+
+        //鍒濆鍖�
+        controller.init();
+        //System.assertEquals('', controller.ra1.OCN_Internal_Notes__c);
+        
+        //鍙戦�佹寜閽�
+        controller.ra1 = odr1;
+        controller.ra1.SplitRatio__c = '';
+
+        //淇濆瓨鍚�
+        controller.saveBtn();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderSplitRatioControllerTest.cls-meta.xml b/scr/classes/OrderSplitRatioControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrderSplitRatioControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderTriggerHandler.cls b/scr/classes/OrderTriggerHandler.cls
new file mode 100644
index 0000000..00b94a5
--- /dev/null
+++ b/scr/classes/OrderTriggerHandler.cls
@@ -0,0 +1,3521 @@
+public without sharing class OrderTriggerHandler {
+    /**
+     * [liApprove description]
+     * 鏉庨儴闀垮鎵规帶鍒�
+     */
+    public static void liApprove(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        Order ord = newList[0];
+        if (ord.LiApprove__c == true && ord.If_Supervise__c == true) {
+             ord.addError('鎵瑰噯闇�瑕佸彇娑圽'涓村簥鏍囪瘑\'鐨勫嬀閫夈��');
+         }
+    }
+    /**
+     * [addressCopy description]
+     * 鏀惰揣鍦板潃鎷锋枃鏈�
+     */
+    public static void addressCopy(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<String> IDList = new List<String>();
+        for (Order ord : newList) {
+            Order old = oldMap.get(ord.Id);
+            if (old.SpecialDeliveryContact2_D__c != ord.SpecialDeliveryContact2_D__c) {
+                ord.Shipping_Address_TextD__c = old.Shipping_Address_D__c;
+            }
+            if (old.SpecialDeliveryContact2__c != ord.SpecialDeliveryContact2__c) {
+                //鍥犲湪鍚堝悓瀹℃壒鍓� SpecialDeliveryContact2__c 涓虹┖ 锛屽洜姝� old.Shipping_Address__c 涓虹┖
+                
+                // ord.Shipping_Address_Text__c = old.Shipping_Address__c;
+                //鍥犲湪鍚堝悓瀹℃壒鍚� 鍦ㄦ洿鏂板墠 SpecialDeliveryContact2__c  涓虹┖ ord.Shipping_Address__c 涓虹┖
+                // ord.Shipping_Address_Text__c = ord.Shipping_Address__c;
+                // 鍥犳锛岀洿鎺ヨ幏鍙朣pecialDeliveryContact2_D__c鐨勫湴鍧�锛岀粰 閫佽揣鍦板潃(鏂囨湰) 璧嬪��
+                // 20200918-XHL锛屽悎鍚屽鎵瑰悗 閫佽揣鍦板潃(鏂囨湰) 瀛楁鍘熷悕 鏀惰揣鍦板潃(鏂囨湰) 娌℃湁璧嬪�兼垚鍔燂紝鍋氬嚭濡備笅淇敼锛屼笂杈逛负瑙i噴
+                ord.Shipping_Address_Text__c = ord.Shipping_Address_D__c;
+                //閫佽揪鏂瑰叕鍙�(鍏紡) ==> 閫佽揪鏂瑰叕鍙�(鏂囨湰)
+                // 20200918-XHL WLIG-BTGAPE Start
+                ord.SpecialDeliveryAccountText__c = ord.SpecialDeliveryAccountFormula__c;
+                //閫佽揪鏂硅仈绯讳汉(鍏紡) ==> 閫佽揪鏂硅仈绯讳汉(鏂囨湰)
+                ord.SpecialDeliveryContactText__c = ord.SpecialDeliveryContactFormula__c;
+                // 20200918-XHL WLIG-BTGAPE End
+            }
+        }
+    }
+    /**
+     * [checkAdderss description]
+     * 鏀惰揣鍦板潃鎺у埗
+     */
+    public static void checkAdderss(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+
+        for (Order ord : newList) {
+            Order old = oldMap.get(ord.Id);
+            if (ord.Is_Already_Splited__c == true && ord.ProductSegment__c == 'BS' && ord.Opportunity != null && ord.ApproveStatus__c == 'OrderPass' && (ord.Shipping_Address__c != old.Shipping_Address__c || ord.Shipping_Address_D__c != old.Shipping_Address_D__c || ord.SpecialDeliveryAccount_D__c != old.SpecialDeliveryAccount_D__c || ord.SpecialDeliveryAccount__c != old.SpecialDeliveryAccount__c || ord.SpecialDeliveryContact2_D__c != old.SpecialDeliveryContact2_D__c || ord.SpecialDeliveryContact2__c != old.SpecialDeliveryContact2__c)) {
+                Opportunity oppor = [select id, AccountId, Dealer__r.DummyDealer__c, Dealer__r.ParentID, Account.MarketVerticals__c, Trade_Type_D__c from Opportunity where id = :ord.OpportunityId];
+
+                if (oppor.Account.MarketVerticals__c == 'Clinical' && oppor.Trade_Type_D__c == 'Taxation' ) {
+                    ord.addError('鍐呰锤鍖荤枟璁㈠崟鎵瑰噯鍚庢媶鍒�,涓嶈兘淇敹璐у湴鍧�');
+                }
+            }
+        }
+    }
+    /**
+     * [check description]
+     * LS鍐呰锤鍖荤枟鍚堝悓璇佺収妫�鏌ワ紝OSSA杈愬皠浜у搧妫�鏌ワ紝浜у搧棣栬惀鐘舵�佹鏌�
+     */
+    public static void check(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        String oppId = newList[0].OpportunityId;
+        Date endDate = Date.valueOf('2019-12-28');
+        String stri = '';
+        if (newList[0].ProductSegment__c == 'BS' && (newList[0].ApproveStatus__c == 'Draft' || newList[0].ApproveStatus__c == 'Reject' || newList[0].ApproveStatus__c == 'OrderDraft' || newList[0].ApproveStatus__c == 'OrderReject' )) {
+            Opportunity oppor = [select id, AccountId, Dealer__r.DummyDealer__c, Dealer__r.ParentID, Account.MarketVerticals__c, Trade_Type_D__c from Opportunity where id = :oppId];
+            if (oppor.Account.MarketVerticals__c == 'Clinical' && oppor.Trade_Type_D__c == 'Taxation' && (newList[0].date_P__c > endDate || newList[0].date_P__c == null)) {
+                newList[0].If_Supervise__c = true;
+                if (oppor.Dealer__r.DummyDealer__c == true) {
+                    newList[0].check__c = LicenseCheckUtil.LicenseCheck(oppor.AccountId);
+                } else {
+                    newList[0].check__c = LicenseCheckUtil.LicenseCheck(oppor.Dealer__r.ParentID);
+                    //newList[0].addCheck__c = LicenseCheckUtil.AddressCheck(oppor.Dealer__r.ParentID,newList[0].Shipping_Address_D__c) == true ? '1' : '0';
+                }
+            } else {
+                system.debug('*()*');
+            }
+
+        }
+        if (newList[0].ProductSegment__c == 'ANI' || newList[0].ProductSegment__c == 'NDT') {
+            List<OpportunityLineItem> oliList = [select id, Product2.If_Exempt_Product__c, Product2.If_Radiation_Product__c, Opportunity.DealerId__c from OpportunityLineItem where opportunityId = :oppId];
+            Boolean hasA = false;
+            for (OpportunityLineItem oli : oliList) {
+                if (oli.Product2.If_Exempt_Product__c == false && oli.Product2.If_Radiation_Product__c == true) {
+                    hasA = true;
+                }
+            }
+            if (hasA == true) {
+                stri =  LicenseCheckUtil.LicenseCheck1(oliList[0].Opportunity.DealerId__c);
+                system.debug(stri);
+                newList[0].check__c = (stri == '0' ? '1':stri);
+            }
+            if(Trigger.isInsert){
+                String result = '';
+                String olympusAccountId = System.label.Olympus_Id;
+                Map<String, Integer> getModelQuantityMap = RadiationUtil.GetOpportunityLineMap(oppId);
+
+                
+
+                 if (newList[0].ProductSegment__c == 'ANI' && newList[0].TradeType__c == '鍐呰锤' ) {
+                    String errorStr = RadiationUtil.GetCertificationDetail(oliList[0].Opportunity.DealerId__c,getModelQuantityMap);
+                    if(errorStr != ''){
+                        newList[0].addError(errorStr +'涓嶈兘鍒涘缓鍚堝悓');
+                    }
+                    //stri =  LicenseCheckUtil.LicenseCheck1(oliList[0].Opportunity.DealerId__c);
+                    
+                    system.debug('2222222'+getModelQuantityMap);
+                    String accountDealerErrorMessage = RadiationUtil.updateCertificationDetails(oliList[0].Opportunity.DealerId__c, null, getModelQuantityMap, false);
+                    String olympusDealerErrorMessage = RadiationUtil.updateCertificationDetails(olympusAccountId, null, getModelQuantityMap, false) == '' ? '' : '浠櫙閫氬彲閿�鍞暟閲忎笉瓒�';
+                    //result = accountDealerErrorMessage + (olympusDealerErrorMessage == '' ? '' : '濂ユ灄宸存柉鍙攢鍞暟閲忎笉瓒�') ;
+                    Boolean temp = accountDealerErrorMessage.startsWith('浣犱笉鑳�');
+                    String strOly = LicenseCheckUtil.LicenseCheckOly();
+                    if(temp){
+                         newList[0].addError('浜у搧涓寘鍚笉鑳介攢鍞殑杈愬皠浜у搧绯诲垪' +'涓嶈兘鍒涘缓鍚堝悓');
+                    }else{
+                        if(olympusDealerErrorMessage == '-1'){
+                            newList[0].addError('浜у搧涓寘鍚笉鑳介攢鍞殑杈愬皠浜у搧绯诲垪' +'涓嶈兘鍒涘缓鍚堝悓');
+                        }else if(olympusDealerErrorMessage != ''){
+                             newList[0].addError(olympusDealerErrorMessage +'涓嶈兘鍒涘缓鍚堝悓');
+                        }
+
+                        if(stri == '1'){
+                            if(accountDealerErrorMessage != '' && strOly == '1'){
+                                newList[0].addError(accountDealerErrorMessage +'涓嶈兘鍒涘缓鍚堝悓');
+                            }else if(accountDealerErrorMessage != '' && strOly == '0'){
+                                newList[0].check__c = accountDealerErrorMessage;
+                            }
+                        }
+                    }
+                    
+                }
+            }
+
+        }
+        if (Trigger.isInsert) {
+
+
+
+            List<OpportunityLineItem> qliList = [select id, Product2.NMPAStatus__c, Product2.ProductCode ,oppLiVerifyProductValid__c from OpportunityLineItem where opportunityId = :oppId];
+            String str = '';
+            Boolean isok = true;
+            for (OpportunityLineItem qli : qliList) {
+                // WLIG-BTA8C2 XHL 20200925 -Start
+                // 鍚堝悓鍙樻洿 骞朵笖 璇环浜у搧鐨� 楠岃瘉浜у搧鏈夋晥鎬� 涓� false 鏃惰烦杩囬獙璇�
+                if (newList[0].OrderIsChange__c && qli.oppLiVerifyProductValid__c == false) {
+                // WLIG-BTA8C2 XHL 20200925 -End
+                } else {
+                   if (qli.Product2.NMPAStatus__c == '棣栬惀鐘舵�佸彉鏇�' || qli.Product2.NMPAStatus__c == '棣栬惀涓嶉�氳繃') {
+                        str += (' ' + qli.Product2.ProductCode);
+                        isok = false;
+                    } 
+                }
+                
+            }
+            if (isok == false) {
+                newList[0].addError(str + '棣栬惀鏈�氳繃');
+            }
+        }
+    }
+    public static void setIsNew(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<String> oppidList = new List<String>();
+        for (Order newOrd : newList) {
+           /* if(newOrd.SubDealer__c == '鏃�'){
+                newOrd.SubDealer__c = '';
+            }*/
+            oppIdList.add(newOrd.OpportunityId);
+            /*if (String.isNotBlank(newOrd.org_order__c)) {
+                newOrd.SharedFlag__c = false;
+            }*/
+        }
+
+
+
+        List<AggregateResult> orderCnt = [select Count(Id) ocnt, OpportunityId from Order where OpportunityId = :oppIdList and Status__c = 'Active' group by OpportunityId];
+        Map<String, Integer> orderCntMap = new Map<String, Integer>();
+        for (AggregateResult temp : orderCnt) {
+            orderCntMap.put((String) temp.get('OpportunityId'), (Integer) temp.get('ocnt'));
+        }
+        // String profileId = UserInfo.getProfileId().substring(0, 15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        //String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+        for (Order newOrd : newList) {
+            if (new_profileId <> System.Label.SystemAdmin && new_profileId <> System.Label.SystemAdmin2
+                && orderCntMap.containsKey(newOrd.OpportunityId) == true && orderCntMap.get(newOrd.OpportunityId) > 0) {
+                newOrd.addError('瀛樺湪鏈夋晥鍚堝悓锛屼笉鑳藉垱寤哄垱鏂板悎鍚岋紒');
+            }
+        }
+        //鐜嬮箯浼� 鏂板缓鍜屽悓鏃�,鍜岃浠峰姣斿鎴枫�佹渶缁堢敤鎴�
+        //鎴村畤锛屾坊鍔犲悎鍚屽叧鑱旈�昏緫
+        List<Opportunity> oppList = [select id,Association_Opportunity__c,CrossCooperativeProject__c,HeadOfCooperationArea__c,CrossCooperativeDealer__r.ManagementCode_F__c,CrossCooperativeDealer__r.Name,SyncedQuoteId, SyncedQuote.PaymentTerms__c, TradeType__c, Quote_PaymentTerms__c,AccountId,customerType__c,useing__c,compo_opp__c,RecordTypeId from Opportunity where id = :oppidList];
+        Map<String, String> syncedQuoteIdMap = new Map<String, String>();
+        Map<String, String> paymentTermsMap = new Map<String, String>();
+        Map<String, String> tradeTypeMap = new Map<String, String>();
+        Map<String,String> oppAccountMap = new Map<String,String>();
+        Map<String,Opportunity> oppMap = new Map<String,Opportunity>();
+
+        for (Opportunity opp : oppList) {
+            syncedQuoteIdMap.put(opp.id, opp.SyncedQuoteId);
+            //paymentTermsMap.put(opp.id, opp.SyncedQuote.PaymentTerms__c);
+            paymentTermsMap.put(opp.Id, opp.Quote_PaymentTerms__c);
+            system.debug('paymentTermsMap:' + paymentTermsMap);
+            tradeTypeMap.put(opp.id, opp.TradeType__c);
+            oppAccountMap.put(opp.Id,opp.AccountId);
+            oppMap.put(opp.Id,opp);
+        }
+
+        for (Order newOrd : newList) {
+            if(newOrd.ProductSegment__c == 'IE' && newOrd.IE_SP8_D__c != oppMap.get(newOrd.OpportunityId).compo_opp__c){
+                newOrd.addError('涓嶈兘淇敼鐗规畩鏉′欢COMPO');
+            }
+
+
+
+            /*if(newOrd.ProductSegment__c == 'BS'){
+                String temp = oppMap.get(newOrd.OpportunityId).useing__c;
+                if(newOrd.SP_61D__c != (temp == ''?false:true)){
+                    newOrd.addError('涓嶈兘淇敼鐗规畩鏉′欢 OEM 閲囪喘');
+                }
+            }*/
+            if (OrderDivisionController.OrderDivision == true) {
+                /*                if (newOrd.ApproveStatus__c == 'Submit') {
+                                    newOrd.ApproveStatus__c = 'Draft';
+                                } else if (newOrd.ApproveStatus__c == 'OrderSubmit') {
+                                    newOrd.ApproveStatus__c = 'OrderDraft';
+                                } else {
+                                    // 淇濇寔鐘舵��
+                                }*/
+                // 淇濇寔鐘舵��
+            } else if (newOrd.IsCopy__c == true) {
+                // 淇濇寔鐘舵��
+            } else if (newOrd.Order_IsSpecial__c == true || newOrd.Order_IsSpecial_Service__c == true) {
+                newOrd.ApproveStatus__c = 'Draft';
+                newOrd.date_P__c = null;
+            } else {
+                newOrd.ApproveStatus__c = 'OrderDraft';
+                newOrd.date_P__c = null;
+            }
+            newOrd.CrossCooperativeProject__c = oppMap.get(newOrd.OpportunityId) == null ? false :oppMap.get(newOrd.OpportunityId).CrossCooperativeProject__c;
+            newOrd.SP_901D__c = oppMap.get(newOrd.OpportunityId) == null ? false :oppMap.get(newOrd.OpportunityId).CrossCooperativeProject__c;
+            newOrd.CrossCooperativeDealerCode__c = oppMap.get(newOrd.OpportunityId) == null ? '' :oppMap.get(newOrd.OpportunityId).CrossCooperativeDealer__r.ManagementCode_F__c;
+            newOrd.HeadOfCooperationArea__c = oppMap.get(newOrd.OpportunityId) == null ? null :oppMap.get(newOrd.OpportunityId).HeadOfCooperationArea__c;
+            newOrd.CrossCooperativeDealerText__c = oppMap.get(newOrd.OpportunityId) == null ? null :oppMap.get(newOrd.OpportunityId).CrossCooperativeDealer__r.Name;
+            newOrd.is_Direct__c = oppMap.get(newOrd.OpportunityId) == null ? false : (oppMap.get(newOrd.OpportunityId).RecordTypeId == '0120T0000003Ser' ? true : false);
+
+            //鐜嬮箯浼熸柊鍔狅紝鍚堝悓涓甫鍏� 璇环 璐告槗绠$悊瀹㈡埛鍒嗙被  寮�濮�
+            newOrd.TradeMagCategory__c = oppMap.get(newOrd.OpportunityId) == null ? '' :oppMap.get(newOrd.OpportunityId).customerType__c;
+            //鐜嬮箯浼熸柊鍔狅紝鍚堝悓涓甫鍏� 璇环 璐告槗绠$悊瀹㈡埛鍒嗙被  缁撴潫
+            newOrd.IsNew__c = true;
+            newOrd.QuoteId = syncedQuoteIdMap.get(newOrd.OpportunityId);
+            newOrd.PaymentTerms__c = paymentTermsMap.get(newOrd.OpportunityId);
+            newOrd.Status__c = 'Active';
+
+            //IE,鍙湁compo琚�変腑,鍒欎笉闇�瑕佸鎵� gwy 2021-06-02
+            if(newOrd.ProductSegment__c=='IE' && newOrd.Status__c == 'Active' && newOrd.OrderDraft__c == false
+                    && newOrd.IE_SP5_D__c == false && newOrd.IE_SP6_D__c == false && newOrd.IE_SP7_D__c == false && newOrd.IE_SP8_D__c == true){
+                    newOrd.ApproveStatus__c = 'Pass';
+                    newOrd.IsSpPassed__c = true;
+                    newOrd.IE_SP8__c = true;
+                }
+            //IE,鍙湁compo琚�変腑,鍒欎笉闇�瑕佸鎵� gwy 2021-06-02
+
+            boolean individualCase = newOrd.RecordTypeId == System.Label.RT_Contract_IndividualCase_ANI ||
+                                     newOrd.RecordTypeId == System.Label.RT_Contract_IndividualCase_BS  ||
+                                     newOrd.RecordTypeId == System.Label.RT_Contract_IndividualCase_IE  ||
+                                     newOrd.RecordTypeId == System.Label.RT_Contract_IndividualCase_NDT ||
+                                     newOrd.RecordTypeId == System.Label.RT_Contract_IndividualCase_RVI;
+
+            if (UserInfo.getUserType() == 'PowerPartner' || newOrd.RecordTypeId == System.Label.RT_ServiceContract || newOrd.RecordTypeId == '0120T0000003nka'
+                    || newOrd.RecordTypeId == System.Label.RT_ServiceContractIE || newOrd.RecordTypeId == System.Label.RT_ServiceContractRVI || individualCase) {
+                // 澶栬锤閫佽揪鏂归粯璁や负澶栬锤鍏徃
+                if (tradeTypeMap.get(newOrd.OpportunityId) == System.Label.Trade_Type) {
+                    newOrd.SpecialDeliveryAccount_D__c = newOrd.ForeignTradeCompany_D__c;
+                }
+            } else {
+                newOrd.SP_11D__c = newOrd.SP_11__c;
+                newOrd.SP_901D__c = newOrd.SP_901__c;
+                newOrd.SP_101D__c = newOrd.SP_101__c;
+                newOrd.SP_102D__c = newOrd.SP_102__c;
+                newOrd.SP_103D__c = newOrd.SP_103__c;
+                newOrd.SP_106D__c = newOrd.SP_106__c;
+                newOrd.SP_107D__c = newOrd.SP_107__c;
+                newOrd.Theoinp_D__c = newOrd.Theoinp__c;
+                newOrd.SP_745D__c = newOrd.SP_745__c;
+                newOrd.SP_111D__c = newOrd.SP_111__c;
+                newOrd.SP_121D__c = newOrd.SP_121__c;
+                newOrd.SP_131D__c = newOrd.SP_131__c;
+                newOrd.SP_141D__c = newOrd.SP_141__c;
+                newOrd.SP_151D__c = newOrd.SP_151__c;
+                newOrd.SP_161D__c = newOrd.SP_161__c;
+                newOrd.SP_171D__c = newOrd.SP_171__c;
+                newOrd.SP_181D__c = newOrd.SP_181__c;
+                newOrd.SP_191D__c = newOrd.SP_191__c;
+                newOrd.SP_201D__c = newOrd.SP_201__c;
+                newOrd.SP_202D__c = newOrd.SP_202__c;
+                newOrd.SP_21D__c = newOrd.SP_21__c;
+                newOrd.SP_22D__c = newOrd.SP_22__c;
+                newOrd.SP_31D__c = newOrd.SP_31__c;
+                newOrd.SP_32D__c = newOrd.SP_32__c;
+                newOrd.SP_33D__c = newOrd.SP_33__c;
+                newOrd.SP_41D__c = newOrd.SP_41__c;
+                newOrd.SP_51D__c = newOrd.SP_51__c;
+                newOrd.SP_52D__c = newOrd.SP_52__c;
+                newOrd.SP_61D__c = newOrd.SP_61__c;
+                newOrd.SP_62D__c = newOrd.SP_62__c;
+                newOrd.SP_71D__c = newOrd.SP_71__c;
+                newOrd.SP_81D__c = newOrd.SP_81__c;
+                newOrd.SP_91D__c = newOrd.SP_91__c;
+                //newOrd.ConditionContract_D__c = newOrd.ConditionContract__c;
+                newOrd.Contract_StatusD__c = newOrd.Contract_Status__c;
+                newOrd.CustomerContractPriceD__c = newOrd.CustomerContractPrice__c;
+                //newOrd.EffectiveDateD__c = newOrd.EffectiveDate;
+                newOrd.OlympusContractPricesD__c = newOrd.OlympusContractPrices__c;
+                newOrd.EndUserD__c = newOrd.EndUser__c;
+
+                newOrd.IE_SP1_D__c = newOrd.IE_SP1__c;
+                newOrd.IE_SP2_D__c = newOrd.IE_SP2__c;
+                newOrd.IE_SP3_D__c = newOrd.IE_SP3__c;
+                newOrd.IE_SP4_D__c = newOrd.IE_SP4__c;
+                newOrd.IE_SP5_D__c = newOrd.IE_SP5__c;
+                newOrd.IE_SP6_D__c = newOrd.IE_SP6__c;
+                newOrd.IE_SP7_D__c = newOrd.IE_SP7__c;
+                newOrd.IE_SP8_D__c = newOrd.IE_SP8__c;
+
+                newOrd.RVI_SP1_D__c = newOrd.RVI_SP1__c;
+                newOrd.RVI_SP2_D__c = newOrd.RVI_SP2__c;
+                newOrd.RVI_SP3_D__c = newOrd.RVI_SP3__c;
+                newOrd.RVI_SP4_D__c = newOrd.RVI_SP4__c;
+                newOrd.RVI_SP5_D__c = newOrd.RVI_SP5__c;
+                newOrd.RVI_SP6_D__c = newOrd.RVI_SP6__c;
+
+                newOrd.NDT_SP1_D__c = newOrd.NDT_SP1__c;
+                newOrd.NDT_SP2_D__c = newOrd.NDT_SP2__c;
+                newOrd.NDT_SP3_D__c = newOrd.NDT_SP3__c;
+                newOrd.NDT_SP4_D__c = newOrd.NDT_SP4__c;
+                newOrd.NDT_SP5_D__c = newOrd.NDT_SP5__c;
+                newOrd.NDT_SP6_D__c = newOrd.NDT_SP6__c;
+                newOrd.NDT_SP7_D__c = newOrd.NDT_SP7__c;
+                newOrd.NDT_SP8_D__c = newOrd.NDT_SP8__c;
+                newOrd.NDT_SP9_D__c = newOrd.NDT_SP9__c;
+                newOrd.NDT_SP10_D__c = newOrd.NDT_SP10__c;
+                newOrd.NDT_SP11_D__c = newOrd.NDT_SP11__c;
+
+                newOrd.ANI_SP1_D__c = newOrd.ANI_SP1__c;
+                newOrd.ANI_SP2_D__c = newOrd.ANI_SP2__c;
+                newOrd.ANI_SP3_D__c = newOrd.ANI_SP3__c;
+                newOrd.ANI_SP4_D__c = newOrd.ANI_SP4__c;
+                newOrd.ANI_SP5_D__c = newOrd.ANI_SP5__c;
+                newOrd.ANI_SP6_D__c = newOrd.ANI_SP6__c;
+
+                newOrd.NormalDis_SerContractCondition_D__c = newOrd.NormalDis_SerContractCondition__c;
+                newOrd.HighDis_SerContractCondition_D__c = newOrd.HighDis_SerContractCondition__c;
+                newOrd.SpecialDis_SerContractCondition_D__c = newOrd.SpecialDis_SerContractCondition__c;
+                newOrd.Warranty_SerContractCondition_D__c = newOrd.Warranty_SerContractCondition__c;
+
+                newOrd.Discount_D__c = newOrd.Discount__c;
+                newOrd.Olympus_Price_BeforeDiscount_D__c = newOrd.Olympus_Price_BeforeDiscount__c;
+                newOrd.PaymentCondition_D__c = newOrd.PaymentCondition__c;
+                newOrd.SpecialDelivery_D__c = newOrd.SpecialDelivery__c;
+                newOrd.SpecialDeliveryContact_D__c = newOrd.SpecialDeliveryContact__c;
+                newOrd.SpecialDeliveryPhone_D__c = newOrd.SpecialDeliveryPhone__c;
+                newOrd.SpecialDeliveryAddress_D__c = newOrd.SpecialDeliveryAddress__c;
+                newOrd.SpecialParkage_D__c = newOrd.SpecialParkage__c;
+                newOrd.SpecialWarranty_D__c = newOrd.SpecialWarranty__c;
+                newOrd.DealerProfit_D__c = newOrd.DealerProfit__c;
+                newOrd.SpecialDelDate_D__c = newOrd.SpecialDelDate__c;
+                newOrd.OtherApply_D__c = newOrd.OtherApply__c;
+
+                newOrd.Andor_D__c = newOrd.Andor__c;
+                newOrd.Bitplane_D__c = newOrd.Bitplane__c;
+                newOrd.CoolLED_D__c = newOrd.CoolLED__c;
+                newOrd.Lumen_D__c = newOrd.Lumen__c;
+                newOrd.Lumenera_D__c = newOrd.Lumenera__c;
+                newOrd.Media_Cybernetics_D__c = newOrd.Media_Cybernetics__c;
+                newOrd.Narishige_D__c = newOrd.Narishige__c;
+                newOrd.Newport_D__c = newOrd.Newport__c;
+                newOrd.OSIS_Germany_D__c = newOrd.OSIS_Germany__c;
+                newOrd.OSIS_Singapore_D__c = newOrd.OSIS_Singapore__c;
+                newOrd.Photometrics_D__c = newOrd.Photometrics__c;
+                newOrd.Prior_Scientific_D__c = newOrd.Prior_Scientific__c;
+                newOrd.Q_Imaging_D__c = newOrd.Q_Imaging__c;
+                newOrd.Tokai_Hit_D__c = newOrd.Tokai_Hit__c;
+                newOrd.Other_Third_D__c = newOrd.Other_Third__c;
+                newOrd.ServiceFee_D__c = newOrd.ServiceFee__c;
+                newOrd.AlongProduct_D__c = newOrd.AlongProduct__c;
+                newOrd.Cost_D__c = newOrd.Cost__c;
+                newOrd.Cost_D__c = newOrd.Cost__c;
+                newOrd.Sub_DealerC_D__c = newOrd.Sub_DealerC__c;
+
+
+
+                newOrd.ForeignTradeCompany_D__c = newOrd.ForeignTradeCompany__c;
+                // 澶栬锤閫佽揪鏂归粯璁や负澶栬锤鍏徃
+                if (tradeTypeMap.get(newOrd.OpportunityId) == System.Label.Trade_Type) {
+                    newOrd.SpecialDeliveryAccount__c = newOrd.ForeignTradeCompany__c;
+                }
+                newOrd.SpecialDeliveryAccount_D__c = newOrd.SpecialDeliveryAccount__c;
+                newOrd.SpecialDeliveryContact2_D__c = newOrd.SpecialDeliveryContact2__c;
+
+                newOrd.Shipment_Term_D__c = newOrd.Shipment_Term__c;
+                newOrd.Shipment_Term2_D__c = newOrd.Shipment_Term2__c;
+            }
+        }
+        //鐜嬮箯浼� 鏂板缓鍜屽悓鏃�,鍜岃浠峰姣斿鎴枫�佹渶缁堢敤鎴�
+        //娣诲姞 寮�濮�
+        /*
+        List<OpportunityContactRole> role_list = new List<OpportunityContactRole>();
+        role_list = [select Id,Role,IsPrimary,OpportunityId,ContactId from OpportunityContactRole where OpportunityId = :oppidList and Role  = 'End user' and IsPrimary = true];
+        Map<String,String> roleMap = new Map<String,String>();
+        for(OpportunityContactRole oppor:role_list){
+            roleMap.put(oppor.OpportunityId,oppor.ContactId);
+        }
+        for(Order orOne:newList){
+            System.debug(oppAccountMap.get(orOne.OpportunityId)+'---'+orOne.AccountId);
+            System.debug(roleMap.get(orOne.OpportunityId)+'---'+orOne.EndUserD__c);
+            if (oppAccountMap.containsKey(orOne.OpportunityId)) {
+                if(oppAccountMap.get(orOne.OpportunityId) != orOne.AccountId || !roleMap.containsKey(orOne.OpportunityId) || orOne.EndUserD__c != roleMap.get(orOne.OpportunityId)){
+                    orOne.addError('瀹㈡埛鍚嶆垨鏈�缁堢敤鎴蜂笌璇环涓嶄竴鑷达紒');
+                }
+            }
+        }
+        */
+        //鐜嬮箯浼熸坊鍔� 缁撴潫
+
+    }
+
+    public static void setPriceBook(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<String> oppidList = new List<String>();
+        for (Order o : newList) {
+            oppidList.add(o.OpportunityId);
+        }
+        List<Opportunity> oppList = [select Id, Pricebook2Id from Opportunity where Id = :oppidList];
+        Map<String, String> pricebookMap = new Map<String, String>();
+        for (Opportunity opp : oppList) {
+            pricebookMap.put(opp.Id, opp.Pricebook2Id);
+        }
+        for (Order o : newList) {
+            o.Pricebook2Id = pricebookMap.get(o.OpportunityId);
+        }
+    }
+
+    public static void addItem(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<String> oppidList = new List<String>();
+        Boolean  hasBS = false;
+        List<OrderShare> salesOwnershareList = new List<OrderShare>();
+        for (Order o : newList) {
+            oppidList.add(o.OpportunityId);
+            // 璺ㄧ渷浠藉悎浣滈」鐩� 涓虹湡 骞朵笖 鍚堝悓瀹℃壒浜轰笉鏄┖锛屽皢鍚堝悓鍏变韩缁欏鎵逛汉 Start
+            if (o.CrossCooperativeProject__c && String.isNotBlank(o.SalesOwner_BS__c)) {
+                salesOwnershareList.add(DataAssembly(o.Id,o.SalesOwner_BS__c));
+            }
+            // 璺ㄧ渷浠藉悎浣滈」鐩� 涓虹湡 骞朵笖 鍚堝悓瀹℃壒浜轰笉鏄┖锛屽皢鍚堝悓鍏变韩缁欏鎵逛汉 End
+        }
+        if (salesOwnershareList.size() > 0) {
+            insert salesOwnershareList;
+        }
+        // XHL20210830
+        List<OpportunityTeamMember> oppTM = new List<OpportunityTeamMember>();
+        // 鏌ユ壘璇环涓嬭浠峰洟闃�,鐢ㄦ埛蹇呴』鏈夋晥
+        oppTM = [select userId,opportunityId,user.IsActive,opportunity.OwnerId from OpportunityTeamMember where user.IsActive = true AND  opportunityId In :oppidList];
+        if(oppTM.size() >0){
+            Map<Id,Map<Id,OrderShare>> orderShareMap = new Map<Id,Map<Id,OrderShare>>();
+            for (Order newOrd : newList) {
+                for (OpportunityTeamMember otm : oppTM) {
+                    // 鎺掗櫎 瀹㈡埛鍥㈤槦鐢ㄦ埛 鏄� 鍚堝悓鎵�鏈変汉
+                    // 鎺掗櫎 瀹㈡埛鍥㈤槦鐢ㄦ埛 鏄� 璇环鎵�鏈変汉
+                    if(otm.OpportunityId == newOrd.OpportunityId && otm.userId != newOrd.OwnerId){
+
+                        Map<Id,OrderShare> shareMap = new Map<Id,OrderShare>();
+                        if (orderShareMap.containsKey(newOrd.Id)) {
+                            shareMap = orderShareMap.get(newOrd.Id);
+                        }
+                        
+                        shareMap.put(otm.UserId,DataAssembly(newOrd.Id,otm.UserId));
+                        //鎺掗櫎 鍚堝悓鎵�鏈変汉 涓� 璇环鎵�鏈変汉 鐩稿悓
+                        if (newOrd.OwnerId != otm.opportunity.OwnerId) {
+                        
+                            shareMap.put(otm.opportunity.OwnerId,DataAssembly(newOrd.Id,otm.opportunity.OwnerId));
+                          
+                        }
+                        orderShareMap.put(newOrd.Id,shareMap);  
+                        
+                        
+                    }
+                }
+            }
+            if (orderShareMap.size() > 0 ) {
+                List<OrderShare> shareList = new List<OrderShare>();
+                for (Id orderId :orderShareMap.keySet()) {
+                    Map<Id,OrderShare> shareMap = orderShareMap.get(orderId);
+                    for (Id userId: shareMap.keySet()) {
+                        shareList.add(shareMap.get(userId));
+                    }
+                }
+
+                if (shareList.size() > 0) {
+                    insert shareList;
+                }
+            }
+        }
+
+       /* List<OpportunityTeamMember> oppTM = new List<OpportunityTeamMember>();
+        oppTM = [select userId,opportunityId,user.IsActive from OpportunityTeamMember where opportunityId = :oppidList];
+        if(oppTM.size() >0){
+            List<OrderShare> shareList = new List<OrderShare>();
+            for (Order newOrd : newList) {
+                for (OpportunityTeamMember otm : oppTM) {
+                    if(otm.OpportunityId == newOrd.OpportunityId && otm.User.IsActive == true){
+                        system.debug(newOrd.Id);
+                        System.debug(otm.UserId);
+                        OrderShare aos = new OrderShare(
+                                    RowCause = 'Manual',
+                                    orderId = newOrd.Id,
+                                    UserOrGroupId = otm.UserId,
+                                    OrderAccessLevel = 'Edit');
+                                shareList.add(aos);
+                    }
+                }
+            }
+            System.debug(shareList);
+            insert shareList;
+        }*/
+       
+
+        List<String> quoidList = new List<String>();
+        Map<String, String> opp2quoMap = new Map<String, String>();
+        List<Opportunity> oppList = [select Id, SyncedQuoteId,Association_Opportunity__c from Opportunity where Id = :oppidList];
+
+        /* List<DecideQuoteProductSet__c> dqpList = new List<DecideQuoteProductSet__c>();
+         dqpList = [select id from DecideQuoteProductSet__c  where DecideOpportunity__c in :oppIdList];
+        */
+       
+        Map<String,String> associationMap = new Map<String,String>();
+        for (Opportunity opp : oppList) {
+            if (opp.SyncedQuoteId != null) {
+                quoidList.add(opp.SyncedQuoteId);
+                opp2quoMap.put(opp.Id, opp.SyncedQuoteId);
+            }
+            if(opp.Association_Opportunity__c != null){
+                associationMap.put(opp.Id,opp.Association_Opportunity__c);
+            }
+        }
+
+        List<Order> updateOrderList = new List<Order>();
+        if(associationMap.size() > 0){
+            List<Order> ordList = new List<Order>();
+            ordList = [select id,Association_Order__c,OpportunityId from Order where OpportunityId in : associationMap.values() and Status__c = 'Active'];
+            if(ordList.size() > 0){
+                for(Order neword : newList){
+                    if(associationMap.containsKey(neword.OpportunityId)){
+                        for(Order o : ordList){
+                            if(o.OpportunityId == associationMap.get(neword.OpportunityId)){
+                                Order neworder = new Order();
+                                neworder.Id = neword.Id;
+                                neworder.Association_Order__c = o.Id;
+                                //neword.Association_Order__c = o.Id;
+                                Order order = new Order();
+                                order.Id = o.Id;
+                                order.Association_Order__c = neword.Id;
+                                updateOrderList.add(order);
+                                updateOrderList.add(neworder);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        List<OpportunityLineItem> oliList = [select Id, OpportunityId, Description, Quantity, ProductSegment__c, PricebookEntryId, PricebookEntry.CostPrice__c, UnitPrice from OpportunityLineItem where OpportunityId = :oppidList order by OpportunityId,Id];
+        Map<String, List<OpportunityLineItem>> oliMap = new Map<String, List<OpportunityLineItem>>();
+        String pre_oppid = '';
+        List<OpportunityLineItem> tmpList = null;
+        for (OpportunityLineItem oli : oliList) {
+            if (oli.ProductSegment__c == 'BS') {
+                hasBS = true;
+            }
+            if (pre_oppid == '' || oli.OpportunityId != pre_oppid) {
+                //syetem.debug('=====new list : key = ' + oli.OpportunityId);52200
+                tmpList = new List<OpportunityLineItem>();
+                oliMap.put(oli.OpportunityId, tmpList);
+                tmpList.add(oli);
+                pre_oppid = oli.OpportunityId;
+            } else {
+                tmpList.add(oli);
+                //syetem.debug('=====list : ' + tmpList);
+            }
+
+            // tmpList = new List<OpportunityLineItem>();
+            // if (oliMap.containsKey(oli.OpportunityId)) {
+            //     oliMap.get(oli.OpportunityId).add(oli);
+            // } else {
+            //     oliMap.put(oli.OpportunityId, tmpList);
+            //     oliMap.get(oli.OpportunityId).add(oli);
+            // }
+
+
+
+        }
+        //syetem.debug('=====oliMap : ' + oliMap);
+        Map<String, List<QuoteLineItem>> qliMap = new Map<String, List<QuoteLineItem>>();
+        String pre_quoid = '';
+        List<QuoteLineItem> tmpList2 = null;
+        Map<String, List<DecideQuoteProductSet__c>> dqpMap = new Map<String, List<DecideQuoteProductSet__c>>();
+
+        if (hasBS) {
+            List<QuoteLineItem> qliList = [select Id, QuoteId, Description, Quantity, PricebookEntryId, PricebookEntry.CostPrice__c, UnitPrice from QuoteLineItem where QuoteId = :quoidList order by QuoteId,Id];
+
+            for (QuoteLineItem qli : qliList) {
+                if (pre_quoid == '' || qli.QuoteId != pre_quoid) {
+                    //syetem.debug('=====new list : key = ' + qli.QuoteId);
+                    tmpList2 = new List<QuoteLineItem>();
+                    qliMap.put(qli.QuoteId, tmpList2);
+                    tmpList2.add(qli);
+                    pre_quoid = qli.QuoteId;
+                } else {
+                    tmpList2.add(qli);
+                    //syetem.debug('=====list : ' + tmpList2);
+                }
+            }
+            //syetem.debug('=====qliMap : ' + qliMap);
+            List<DecideQuoteProductSet__c> dqpList = new List<DecideQuoteProductSet__c>();
+            dqpList = [select id, DecideOpportunity__c from DecideQuoteProductSet__c  where DecideOpportunity__c in :oppIdList];
+            for (DecideQuoteProductSet__c dqp : dqpList) {
+                if (dqpMap.containsKey(dqp.DecideOpportunity__c)) {
+                    dqpMap.get(dqp.DecideOpportunity__c).add(dqp);
+                } else {
+                    dqpMap.put(dqp.DecideOpportunity__c, new List<DecideQuoteProductSet__c>());
+                    dqpMap.get(dqp.DecideOpportunity__c).add(dqp);
+                }
+            }
+        }
+
+
+
+        /*if(hasBS){
+            List<DecideQuoteProductSet__c> dqpList = new List<DecideQuoteProductSet__c>();
+            dqpList = [select id,DecideOpportunity__c from DecideQuoteProductSet__c  where DecideOpportunity__c in :oppIdList];
+            for(DecideQuoteProductSet__c dqp : dqpList){
+                dqpMap.put(dqp.DecideOpportunity__c, dqp);
+            }
+
+        }*/
+
+
+
+        List<OrderItem> insList = new List<OrderItem>();
+        List<DecideQuoteProductSet__c> updateList = new List<DecideQuoteProductSet__c>();
+
+        for (Order o : newList) {
+            if (qliMap.containsKey(opp2quoMap.get(o.OpportunityId)) == true) {
+                for (QuoteLineItem qli : qliMap.get(opp2quoMap.get(o.OpportunityId))) {
+                    OrderItem oi = new OrderItem();
+                    oi.Description = qli.Description;
+                    oi.Quantity = qli.Quantity;
+                    oi.PricebookEntryId = qli.PricebookEntryId;
+                    oi.UnitPrice = qli.UnitPrice;
+                    oi.OrderId = o.Id;
+                    oi.QuoteLineItemId = qli.Id;
+                    oi.TotalCostPrice_Text__c = qli.PricebookEntry.CostPrice__c * qli.Quantity;
+                    insList.add(oi);
+                }
+            } else {
+                if (oliMap.get(o.OpportunityId) != null) {
+                    for (OpportunityLineItem oli : oliMap.get(o.OpportunityId)) {
+                        OrderItem oi = new OrderItem();
+                        oi.Description = oli.Description;
+                        oi.Quantity = oli.Quantity;
+                        oi.PricebookEntryId = oli.PricebookEntryId;
+                        oi.UnitPrice = oli.UnitPrice;
+                        oi.OrderId = o.Id;
+                        oi.TotalCostPrice_Text__c = oli.PricebookEntry.CostPrice__c * oli.Quantity;
+                        insList.add(oi);
+                    }
+                }
+            }
+
+            if (dqpMap.size() > 0 && dqpMap.containsKey(o.OpportunityId)) {
+                // DecideQuoteProductSet__c temp = dqpMap.get(o.OpportunityId);
+                for (DecideQuoteProductSet__c temp : dqpMap.get(o.OpportunityId)) {
+                    temp.DecideOrder__c = o.id;
+                }
+                updateList.addAll(dqpMap.get(o.OpportunityId));
+            }
+
+        }
+        if (insList.size() > 0) insert insList;
+        if (updateList.size() > 0) update updateList;
+        if (updateOrderList.size() > 0) update updateOrderList;
+    }
+
+    public static void updateForDealer(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        //for寰幆閲屾湁鐢ㄥ埌鑾峰彇绠�妗d俊鎭紝鏂扮殑鑾峰彇绠�妗f湁SQOL 鏀惧埌for寰幆澶栭潰
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        //String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+       
+        for (Order newOrd : newList) {
+            Order oldOrd = oldMap.get(newOrd.Id);
+            if(newOrd.CrossCooperativeProject__c && CherkCrossComperativeChanged(newOrd,oldOrd)){
+                newOrd.addError('鍒涘缓鍚堝悓鍚庝笉鑳戒慨鏀笰浠g悊鍟嗗拰B浠g悊鍟�');
+            }
+           /* if(newOrd.SubDealer__c == '鏃�'){
+                newOrd.SubDealer__c = '';
+            }*/
+//            if (oldOrd.ShippedDate__c != null && oldOrd.ShippedDate__c != newOrd.ShippedDate__c) {
+//                newOrd.addError('鍑鸿揣鏃ユ湡濉啓鍚庝笉鑳戒慨鏀广��');
+//            }
+            system.debug('=====' + newOrd.SP_11D__c + '|' + oldOrd.SP_11D__c);
+            system.debug('=====' + newOrd.SP_101D__c + '|' + oldOrd.SP_101D__c);
+            system.debug('=====' + newOrd.SP_102D__c + '|' + oldOrd.SP_102D__c);
+            system.debug('=====' + newOrd.SP_103D__c + '|' + oldOrd.SP_103D__c);
+            system.debug('=====' + newOrd.SP_106D__c + '|' + oldOrd.SP_106D__c);
+            system.debug('=====' + newOrd.SP_107D__c + '|' + oldOrd.SP_107D__c);
+            system.debug('=====' + newOrd.Theoinp_D__c + '|' + oldOrd.Theoinp_D__c);
+            system.debug('=====' + newOrd.SP_745D__c + '|' + oldOrd.SP_745D__c);
+            system.debug('=====' + newOrd.SP_111D__c + '|' + oldOrd.SP_111D__c);
+            system.debug('=====' + newOrd.SP_121D__c + '|' + oldOrd.SP_121D__c);
+            system.debug('=====' + newOrd.SP_131D__c + '|' + oldOrd.SP_131D__c);
+            system.debug('=====' + newOrd.SP_141D__c + '|' + oldOrd.SP_141D__c);
+            system.debug('=====' + newOrd.SP_151D__c + '|' + oldOrd.SP_151D__c);
+            system.debug('=====' + newOrd.SP_161D__c + '|' + oldOrd.SP_161D__c);
+            system.debug('=====' + newOrd.SP_171D__c + '|' + oldOrd.SP_171D__c);
+            system.debug('=====' + newOrd.SP_181D__c + '|' + oldOrd.SP_181D__c);
+            system.debug('=====' + newOrd.SP_191D__c + '|' + oldOrd.SP_191D__c);
+            system.debug('=====' + newOrd.SP_201D__c + '|' + oldOrd.SP_201D__c);
+            system.debug('=====' + newOrd.SP_202D__c + '|' + oldOrd.SP_202D__c);
+            system.debug('=====' + newOrd.SP_21D__c + '|' + oldOrd.SP_21D__c);
+            system.debug('=====' + newOrd.SP_22D__c + '|' + oldOrd.SP_22D__c);
+            system.debug('=====' + newOrd.SP_31D__c + '|' + oldOrd.SP_31D__c);
+            system.debug('=====' + newOrd.SP_32D__c + '|' + oldOrd.SP_32D__c);
+            system.debug('=====' + newOrd.SP_33D__c + '|' + oldOrd.SP_33D__c);
+            system.debug('=====' + newOrd.SP_41D__c + '|' + oldOrd.SP_41D__c);
+            system.debug('=====' + newOrd.SP_51D__c + '|' + oldOrd.SP_51D__c);
+            system.debug('=====' + newOrd.SP_52D__c + '|' + oldOrd.SP_52D__c);
+            system.debug('=====' + newOrd.SP_61D__c + '|' + oldOrd.SP_61D__c);
+            system.debug('=====' + newOrd.SP_62D__c + '|' + oldOrd.SP_62D__c);
+            system.debug('=====' + newOrd.SP_71D__c + '|' + oldOrd.SP_71D__c);
+            system.debug('=====' + newOrd.SP_81D__c + '|' + oldOrd.SP_81D__c);
+            system.debug('=====' + newOrd.SP_91D__c + '|' + oldOrd.SP_91D__c);
+            system.debug('=====' + newOrd.IE_SP1_D__c + '|' + oldOrd.IE_SP1_D__c);
+            system.debug('=====' + newOrd.IE_SP2_D__c + '|' + oldOrd.IE_SP2_D__c);
+            system.debug('=====' + newOrd.IE_SP3_D__c + '|' + oldOrd.IE_SP3_D__c);
+            system.debug('=====' + newOrd.IE_SP4_D__c + '|' + oldOrd.IE_SP4_D__c);
+            system.debug('=====' + newOrd.IE_SP5_D__c + '|' + oldOrd.IE_SP5_D__c);
+            system.debug('=====' + newOrd.IE_SP6_D__c + '|' + oldOrd.IE_SP6_D__c);
+            system.debug('=====' + newOrd.IE_SP7_D__c + '|' + oldOrd.IE_SP7_D__c);
+            system.debug('=====' + newOrd.IE_SP8_D__c + '|' + oldOrd.IE_SP8_D__c);
+            system.debug('=====' + newOrd.RVI_SP1_D__c + '|' + oldOrd.RVI_SP1_D__c);
+            system.debug('=====' + newOrd.RVI_SP2_D__c + '|' + oldOrd.RVI_SP2_D__c);
+            system.debug('=====' + newOrd.RVI_SP3_D__c + '|' + oldOrd.RVI_SP3_D__c);
+            system.debug('=====' + newOrd.RVI_SP4_D__c + '|' + oldOrd.RVI_SP4_D__c);
+            system.debug('=====' + newOrd.RVI_SP5_D__c + '|' + oldOrd.RVI_SP5_D__c);
+            system.debug('=====' + newOrd.RVI_SP6_D__c + '|' + oldOrd.RVI_SP6_D__c);
+            system.debug('=====' + newOrd.NDT_SP1_D__c + '|' + oldOrd.NDT_SP1_D__c);
+            system.debug('=====' + newOrd.NDT_SP2_D__c + '|' + oldOrd.NDT_SP2_D__c);
+            system.debug('=====' + newOrd.NDT_SP3_D__c + '|' + oldOrd.NDT_SP3_D__c);
+            system.debug('=====' + newOrd.NDT_SP4_D__c + '|' + oldOrd.NDT_SP4_D__c);
+            system.debug('=====' + newOrd.NDT_SP5_D__c + '|' + oldOrd.NDT_SP5_D__c);
+            system.debug('=====' + newOrd.NDT_SP6_D__c + '|' + oldOrd.NDT_SP6_D__c);
+            system.debug('=====' + newOrd.NDT_SP7_D__c + '|' + oldOrd.NDT_SP7_D__c);
+            system.debug('=====' + newOrd.NDT_SP8_D__c + '|' + oldOrd.NDT_SP8_D__c);
+            system.debug('=====' + newOrd.NDT_SP9_D__c + '|' + oldOrd.NDT_SP9_D__c);
+            system.debug('=====' + newOrd.NDT_SP10_D__c + '|' + oldOrd.NDT_SP10_D__c);
+            system.debug('=====' + newOrd.NDT_SP11_D__c + '|' + oldOrd.NDT_SP11_D__c);
+            system.debug('=====' + newOrd.ANI_SP1_D__c + '|' + oldOrd.ANI_SP1_D__c);
+            system.debug('=====' + newOrd.ANI_SP2_D__c + '|' + oldOrd.ANI_SP2_D__c);
+            system.debug('=====' + newOrd.ANI_SP3_D__c + '|' + oldOrd.ANI_SP3_D__c);
+            system.debug('=====' + newOrd.ANI_SP4_D__c + '|' + oldOrd.ANI_SP4_D__c);
+            system.debug('=====' + newOrd.ANI_SP5_D__c + '|' + oldOrd.ANI_SP5_D__c);
+            system.debug('=====' + newOrd.ANI_SP6_D__c + '|' + oldOrd.ANI_SP6_D__c);
+            system.debug('=====' + newOrd.Discount_D__c + '|' + oldOrd.Discount_D__c);
+            system.debug('=====' + newOrd.Olympus_Price_BeforeDiscount_D__c + '|' + oldOrd.Olympus_Price_BeforeDiscount_D__c);
+            system.debug('=====' + newOrd.PaymentCondition_D__c + '|' + oldOrd.PaymentCondition_D__c);
+            system.debug('=====' + newOrd.SpecialDelivery_D__c + '|' + oldOrd.SpecialDelivery_D__c);
+            system.debug('=====' + newOrd.SpecialDeliveryContact_D__c + '|' + oldOrd.SpecialDeliveryContact_D__c);
+            system.debug('=====' + newOrd.SpecialDeliveryPhone_D__c + '|' + oldOrd.SpecialDeliveryPhone_D__c);
+            system.debug('=====' + newOrd.SpecialDeliveryAddress_D__c + '|' + oldOrd.SpecialDeliveryAddress_D__c);
+            system.debug('=====' + newOrd.SpecialParkage_D__c + '|' + oldOrd.SpecialParkage_D__c);
+            system.debug('=====' + newOrd.SpecialWarranty_D__c + '|' + oldOrd.SpecialWarranty_D__c);
+            system.debug('=====' + newOrd.DealerProfit_D__c + '|' + oldOrd.DealerProfit_D__c);
+            system.debug('=====' + newOrd.SpecialDelDate_D__c + '|' + oldOrd.SpecialDelDate_D__c);
+            system.debug('=====' + newOrd.OtherApply_D__c + '|' + oldOrd.OtherApply_D__c);
+            system.debug('=====' + newOrd.NormalDis_SerContractCondition_D__c + '|' + oldOrd.NormalDis_SerContractCondition_D__c);
+            system.debug('=====' + newOrd.HighDis_SerContractCondition_D__c + '|' + oldOrd.HighDis_SerContractCondition_D__c);
+            system.debug('=====' + newOrd.SpecialDis_SerContractCondition_D__c + '|' + oldOrd.SpecialDis_SerContractCondition_D__c);
+            system.debug('=====' + newOrd.Warranty_SerContractCondition_D__c + '|' + oldOrd.Warranty_SerContractCondition_D__c);
+            boolean sp_change =
+                newOrd.SP_11D__c != oldOrd.SP_11D__c ||
+                newOrd.SP_901D__c != oldOrd.SP_901D__c ||
+                newOrd.SP_101D__c != oldOrd.SP_101D__c ||
+                newOrd.SP_102D__c != oldOrd.SP_102D__c ||
+                newOrd.SP_103D__c != oldOrd.SP_103D__c ||
+                newOrd.SP_106D__c != oldOrd.SP_106D__c ||
+                newOrd.SP_107D__c != oldOrd.SP_107D__c ||
+                newOrd.SP_745D__c != oldOrd.SP_745D__c ||
+                newOrd.SP_111D__c != oldOrd.SP_111D__c ||
+                newOrd.SP_121D__c != oldOrd.SP_121D__c ||
+                newOrd.SP_131D__c != oldOrd.SP_131D__c ||
+                newOrd.SP_141D__c != oldOrd.SP_141D__c ||
+                newOrd.SP_151D__c != oldOrd.SP_151D__c ||
+                newOrd.SP_161D__c != oldOrd.SP_161D__c ||
+                newOrd.SP_171D__c != oldOrd.SP_171D__c ||
+                newOrd.SP_181D__c != oldOrd.SP_181D__c ||
+                newOrd.SP_191D__c != oldOrd.SP_191D__c ||
+                newOrd.SP_201D__c != oldOrd.SP_201D__c ||
+                newOrd.SP_202D__c != oldOrd.SP_202D__c ||
+                newOrd.SP_21D__c != oldOrd.SP_21D__c ||
+                newOrd.SP_22D__c != oldOrd.SP_22D__c ||
+                newOrd.SP_31D__c != oldOrd.SP_31D__c ||
+                newOrd.SP_32D__c != oldOrd.SP_32D__c ||
+                newOrd.SP_33D__c != oldOrd.SP_33D__c ||
+                newOrd.SP_41D__c != oldOrd.SP_41D__c ||
+                newOrd.SP_51D__c != oldOrd.SP_51D__c ||
+                newOrd.SP_52D__c != oldOrd.SP_52D__c ||
+                newOrd.SP_61D__c != oldOrd.SP_61D__c ||
+                newOrd.SP_62D__c != oldOrd.SP_62D__c ||
+                newOrd.SP_71D__c != oldOrd.SP_71D__c ||
+                newOrd.SP_81D__c != oldOrd.SP_81D__c ||
+                newOrd.SP_91D__c != oldOrd.SP_91D__c ||
+                newOrd.Theoinp_D__c != oldOrd.Theoinp_D__c ||
+                newOrd.IE_SP1_D__c != oldOrd.IE_SP1_D__c ||
+                newOrd.IE_SP2_D__c != oldOrd.IE_SP2_D__c ||
+                newOrd.IE_SP3_D__c != oldOrd.IE_SP3_D__c ||
+                newOrd.IE_SP4_D__c != oldOrd.IE_SP4_D__c ||
+                newOrd.IE_SP5_D__c != oldOrd.IE_SP5_D__c ||
+                newOrd.IE_SP6_D__c != oldOrd.IE_SP6_D__c ||
+                newOrd.IE_SP7_D__c != oldOrd.IE_SP7_D__c ||
+                newOrd.IE_SP8_D__c != oldOrd.IE_SP8_D__c ||
+                newOrd.RVI_SP1_D__c != oldOrd.RVI_SP1_D__c ||
+                newOrd.RVI_SP2_D__c != oldOrd.RVI_SP2_D__c ||
+                newOrd.RVI_SP3_D__c != oldOrd.RVI_SP3_D__c ||
+                newOrd.RVI_SP4_D__c != oldOrd.RVI_SP4_D__c ||
+                newOrd.RVI_SP5_D__c != oldOrd.RVI_SP5_D__c ||
+                newOrd.RVI_SP6_D__c != oldOrd.RVI_SP6_D__c ||
+                newOrd.NDT_SP1_D__c != oldOrd.NDT_SP1_D__c ||
+                newOrd.NDT_SP2_D__c != oldOrd.NDT_SP2_D__c ||
+                newOrd.NDT_SP3_D__c != oldOrd.NDT_SP3_D__c ||
+                newOrd.NDT_SP4_D__c != oldOrd.NDT_SP4_D__c ||
+                newOrd.NDT_SP5_D__c != oldOrd.NDT_SP5_D__c ||
+                newOrd.NDT_SP6_D__c != oldOrd.NDT_SP6_D__c ||
+                newOrd.NDT_SP7_D__c != oldOrd.NDT_SP7_D__c ||
+                newOrd.NDT_SP8_D__c != oldOrd.NDT_SP8_D__c ||
+                newOrd.NDT_SP9_D__c != oldOrd.NDT_SP9_D__c ||
+                newOrd.NDT_SP10_D__c != oldOrd.NDT_SP10_D__c ||
+                newOrd.NDT_SP11_D__c != oldOrd.NDT_SP11_D__c ||
+                newOrd.ANI_SP1_D__c != oldOrd.ANI_SP1_D__c ||
+                newOrd.ANI_SP2_D__c != oldOrd.ANI_SP2_D__c ||
+                newOrd.ANI_SP3_D__c != oldOrd.ANI_SP3_D__c ||
+                newOrd.ANI_SP4_D__c != oldOrd.ANI_SP4_D__c ||
+                newOrd.ANI_SP5_D__c != oldOrd.ANI_SP5_D__c ||
+                newOrd.ANI_SP6_D__c != oldOrd.ANI_SP6_D__c ||
+                (newOrd.Discount_D__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.Discount_D__c)).setScale(2).setScale(0)) != (oldOrd.Discount_D__c == null ? 0 : Decimal.valueOf(String.valueOf(oldOrd.Discount_D__c)).setScale(2).setScale(0)) ||
+                (newOrd.Olympus_Price_BeforeDiscount_D__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.Olympus_Price_BeforeDiscount_D__c)).setScale(2).setScale(0)) != (oldOrd.Olympus_Price_BeforeDiscount_D__c == null ? 0 : Decimal.valueOf(String.valueOf(oldOrd.Olympus_Price_BeforeDiscount_D__c)).setScale(2).setScale(0)) ||
+                newOrd.PaymentCondition_D__c != oldOrd.PaymentCondition_D__c ||
+                newOrd.SpecialDelivery_D__c != oldOrd.SpecialDelivery_D__c ||
+                newOrd.SpecialDeliveryContact_D__c != oldOrd.SpecialDeliveryContact_D__c ||
+                newOrd.SpecialDeliveryPhone_D__c != oldOrd.SpecialDeliveryPhone_D__c ||
+                newOrd.SpecialDeliveryAddress_D__c != oldOrd.SpecialDeliveryAddress_D__c ||
+                newOrd.SpecialParkage_D__c != oldOrd.SpecialParkage_D__c ||
+                newOrd.SpecialWarranty_D__c != oldOrd.SpecialWarranty_D__c ||
+                newOrd.DealerProfit_D__c != oldOrd.DealerProfit_D__c ||
+                newOrd.SpecialDelDate_D__c != oldOrd.SpecialDelDate_D__c ||
+                newOrd.OtherApply_D__c != oldOrd.OtherApply_D__c ||
+                newOrd.NormalDis_SerContractCondition_D__c != oldOrd.NormalDis_SerContractCondition_D__c ||
+                newOrd.HighDis_SerContractCondition_D__c != oldOrd.HighDis_SerContractCondition_D__c ||
+                newOrd.SpecialDis_SerContractCondition_D__c != oldOrd.SpecialDis_SerContractCondition_D__c ||
+                newOrd.Warranty_SerContractCondition_D__c != oldOrd.Warranty_SerContractCondition_D__c;
+
+            system.debug('=====' + newOrd.CustomerContractPriceD__c + '|' + oldOrd.CustomerContractPriceD__c);
+            system.debug('=====' + newOrd.OlympusContractPricesD__c + '|' + oldOrd.OlympusContractPricesD__c);
+            system.debug('=====' + newOrd.EndUserD__c + '|' + oldOrd.EndUserD__c);
+            system.debug('=====' + newOrd.IsUpload__c + '|' + oldOrd.IsUpload__c);
+            system.debug('=====' + newOrd.Andor_D__c + '|' + oldOrd.Andor_D__c);
+            system.debug('=====' + newOrd.Bitplane_D__c + '|' + oldOrd.Bitplane_D__c);
+            system.debug('=====' + newOrd.CoolLED_D__c + '|' + oldOrd.CoolLED_D__c);
+            system.debug('=====' + newOrd.Lumen_D__c + '|' + oldOrd.Lumen_D__c);
+            system.debug('=====' + newOrd.Lumenera_D__c + '|' + oldOrd.Lumenera_D__c);
+            system.debug('=====' + newOrd.Media_Cybernetics_D__c + '|' + oldOrd.Media_Cybernetics_D__c);
+            system.debug('=====' + newOrd.Narishige_D__c + '|' + oldOrd.Narishige_D__c);
+            system.debug('=====' + newOrd.Newport_D__c + '|' + oldOrd.Newport_D__c);
+            system.debug('=====' + newOrd.OSIS_Germany_D__c + '|' + oldOrd.OSIS_Germany_D__c);
+            system.debug('=====' + newOrd.OSIS_Singapore_D__c + '|' + oldOrd.OSIS_Singapore_D__c);
+            system.debug('=====' + newOrd.Photometrics_D__c + '|' + oldOrd.Photometrics_D__c);
+            system.debug('=====' + newOrd.Prior_Scientific_D__c + '|' + oldOrd.Prior_Scientific_D__c);
+            system.debug('=====' + newOrd.Q_Imaging_D__c + '|' + oldOrd.Q_Imaging_D__c);
+            system.debug('=====' + newOrd.Tokai_Hit_D__c + '|' + oldOrd.Tokai_Hit_D__c);
+            system.debug('=====' + newOrd.Other_Third_D__c + '|' + oldOrd.Other_Third_D__c);
+            system.debug('=====' + newOrd.ServiceFee_D__c + '|' + oldOrd.ServiceFee_D__c);
+            system.debug('=====' + newOrd.AlongProduct_D__c + '|' + oldOrd.AlongProduct_D__c);
+            system.debug('=====' + newOrd.Cost_D__c + '|' + oldOrd.Cost_D__c);
+            system.debug('=====' + newOrd.ForeignTradeCompany_D__c + '|' + oldOrd.ForeignTradeCompany_D__c);
+            system.debug('=====' + newOrd.SpecialDeliveryAccount_D__c + '|' + oldOrd.SpecialDeliveryAccount_D__c);
+            system.debug('=====' + newOrd.SpecialDeliveryContact2_D__c + '|' + oldOrd.SpecialDeliveryContact2_D__c);
+            system.debug('=====' + newOrd.Shipment_Term_D__c + '|' + oldOrd.Shipment_Term_D__c);
+            system.debug('=====' + newOrd.Shipment_Term2_D__c + '|' + oldOrd.Shipment_Term2_D__c);
+            system.debug('*************' + newOrd.IsUpload__c + '****' + oldOrd.IsUpload__c + '****' + newOrd.Is_Already_Splited__c + '****' + newOrd.ApproveStatus__c);
+            system.debug('*************' + (newOrd.IsUpload__c != oldOrd.IsUpload__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true)));
+            boolean contract_change =
+                (newOrd.CustomerContractPriceD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.CustomerContractPriceD__c)).setScale(2).setScale(0)) != (oldOrd.CustomerContractPriceD__c == null ? 0 : Decimal.valueOf(String.valueOf(oldOrd.CustomerContractPriceD__c)).setScale(2).setScale(0)) ||
+                (newOrd.OlympusContractPricesD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.OlympusContractPricesD__c)).setScale(2).setScale(0)) != (oldOrd.OlympusContractPricesD__c == null ? 0 : Decimal.valueOf(String.valueOf(oldOrd.OlympusContractPricesD__c)).setScale(2).setScale(0)) ||
+                newOrd.EndUserD__c != oldOrd.EndUserD__c ||
+                (newOrd.IsUpload__c != oldOrd.IsUpload__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true)) ||
+
+                newOrd.Andor_D__c != oldOrd.Andor_D__c ||
+                newOrd.Bitplane_D__c != oldOrd.Bitplane_D__c ||
+                newOrd.CoolLED_D__c != oldOrd.CoolLED_D__c ||
+                newOrd.Lumen_D__c != oldOrd.Lumen_D__c ||
+                newOrd.Lumenera_D__c != oldOrd.Lumenera_D__c ||
+                newOrd.Media_Cybernetics_D__c != oldOrd.Media_Cybernetics_D__c ||
+                newOrd.Narishige_D__c != oldOrd.Narishige_D__c ||
+                newOrd.Newport_D__c != oldOrd.Newport_D__c ||
+                newOrd.OSIS_Germany_D__c != oldOrd.OSIS_Germany_D__c ||
+                newOrd.OSIS_Singapore_D__c != oldOrd.OSIS_Singapore_D__c ||
+                newOrd.Photometrics_D__c != oldOrd.Photometrics_D__c ||
+                newOrd.Prior_Scientific_D__c != oldOrd.Prior_Scientific_D__c ||
+                newOrd.Q_Imaging_D__c != oldOrd.Q_Imaging_D__c ||
+                newOrd.Tokai_Hit_D__c != oldOrd.Tokai_Hit_D__c ||
+                newOrd.Other_Third_D__c != oldOrd.Other_Third_D__c ||
+                newOrd.ServiceFee_D__c != oldOrd.ServiceFee_D__c ||
+                newOrd.AlongProduct_D__c != oldOrd.AlongProduct_D__c ||
+                newOrd.Cost_D__c != oldOrd.Cost_D__c ||
+
+                newOrd.ForeignTradeCompany_D__c != oldOrd.ForeignTradeCompany_D__c ||
+                newOrd.Shipment_Term_D__c != oldOrd.Shipment_Term_D__c ||
+                newOrd.Shipment_Term2_D__c != oldOrd.Shipment_Term2_D__c ||
+                (newOrd.SpecialDeliveryAccount_D__c != oldOrd.SpecialDeliveryAccount_D__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true)) ||
+                (newOrd.SpecialDeliveryContact2_D__c != oldOrd.SpecialDeliveryContact2_D__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true));
+
+            system.debug('=====' + newOrd.CustomerContractPriceD__c + '|' + oldOrd.CustomerContractPriceD__c);
+            system.debug('=====' + newOrd.OlympusContractPricesD__c + '|' + oldOrd.OlympusContractPricesD__c);
+            system.debug('=====' + newOrd.EndUserD__c + '|' + oldOrd.EndUserD__c);
+            system.debug('=====' + newOrd.AlongProduct_D__c + '|' + oldOrd.AlongProduct_D__c);
+            system.debug('=====' + newOrd.ServiceFee_D__c + '|' + oldOrd.ServiceFee_D__c);
+            boolean contractInfo_change =
+                (newOrd.CustomerContractPriceD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.CustomerContractPriceD__c)).setScale(2).setScale(0)) != (oldOrd.CustomerContractPriceD__c == null ? 0 : Decimal.valueOf(String.valueOf(oldOrd.CustomerContractPriceD__c)).setScale(2).setScale(0)) ||
+                (newOrd.OlympusContractPricesD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.OlympusContractPricesD__c)).setScale(2).setScale(0)) != (oldOrd.OlympusContractPricesD__c == null ? 0 : Decimal.valueOf(String.valueOf(oldOrd.OlympusContractPricesD__c)).setScale(2).setScale(0)) ||
+                newOrd.EndUserD__c !=  oldOrd.EndUserD__c ||
+                newOrd.AlongProduct_D__c != oldOrd.AlongProduct_D__c ||
+                newOrd.ServiceFee_D__c != oldOrd.ServiceFee_D__c;
+
+            boolean pdf_change = newOrd.IsUpload__c != oldOrd.IsUpload__c;
+
+            //浜у搧閰嶇疆
+            // boolean product_change = newOrd.ProductConfig_D__c != oldOrd.ProductConfig_D__c && oldOrd.Pr;
+
+            if (newOrd.Contract_StatusD__c != oldOrd.Contract_StatusD__c && newOrd.Contract_StatusD__c == 'Cancel') {
+                if (sp_change == false && contract_change == false) {
+                    newOrd.ApproveStatus__c = 'OrderDraft';
+                    newOrd.date_P__c = null;
+                } else {
+                    newOrd.addError('鍙栨秷鍚堝悓鏃讹紝涓嶈兘鏀瑰彉鍏朵粬椤圭洰銆�');
+                }
+            }
+
+            // String profileId = UserInfo.getProfileId().substring(0, 15);
+
+            boolean is_admin = new_profileId == System.Label.SystemAdmin || new_profileId == System.Label.SystemAdmin2 || new_profileId == System.Label.SystemAdmin_GPI;
+            if (newOrd.IsSpPassed__c == true && (sp_change == true || contractInfo_change == true) && OrderDivisionController.OrderDivision == false && is_admin == false) {
+                newOrd.addError('鐗规畩鏉′欢鎵瑰噯鍚庯紝涓嶈兘鏇存敼銆�');
+            }
+
+            system.debug('***************' + newOrd.IsOrderPassed__c + '***' + sp_change + '***' + contract_change + '***' + OrderDivisionController.OrderDivision + '***' + is_admin + '');
+            if (newOrd.IsOrderPassed__c == true && (sp_change == true || contract_change == true) && OrderDivisionController.OrderDivision == false && is_admin == false) {
+                newOrd.addError('鍚堝悓鎵瑰噯鍚庯紝涓嶈兘鏇存敼銆�');
+            }
+
+
+            if (OrderDivisionController.OrderDivision == true) {
+                /*                if (newOrd.ApproveStatus__c == 'Submit') {
+                                    newOrd.ApproveStatus__c = 'Draft';
+                                } else if (newOrd.ApproveStatus__c == 'OrderSubmit') {
+                                    newOrd.ApproveStatus__c = 'OrderDraft';
+                                } else {
+                                    // 淇濇寔鐘舵��
+                                }*/
+                // 淇濇寔鐘舵��
+            } else if (sp_change && (newOrd.Order_IsSpecial__c == true || newOrd.Order_IsSpecial_Service__c == true)) {
+                system.debug('=====Draft 1=====');
+                newOrd.ApproveStatus__c = 'Draft';
+                newOrd.date_P__c = null;
+            } else if (contract_change && (newOrd.Order_IsSpecial__c == true || newOrd.Order_IsSpecial_Service__c == true) && newOrd.IsSpPassed__c == false) {
+                system.debug('=====Draft 2=====');
+                newOrd.ApproveStatus__c = 'Draft';
+                newOrd.date_P__c = null;
+            }  else if (contract_change ||
+                        (newOrd.Order_IsSpecial__c != oldOrd.Order_IsSpecial__c && newOrd.Order_IsSpecial__c == false) ||
+                        (newOrd.Order_IsSpecial_Service__c != oldOrd.Order_IsSpecial_Service__c && newOrd.Order_IsSpecial_Service__c == false)) {
+                system.debug('=====OrderDraft 1=====');
+                newOrd.ApproveStatus__c = 'OrderDraft';
+                neword.date_P__c = null;
+            } /*else if(product_change && newOrd.Is_Already_Splited__c == false && oldOrd.ProductConfig_D__c != null){      //
+                system.debug('=====Draft 3=====');
+                newOrd.ApproveStatus__c = 'Draft';
+                newOrd.ProductConfig_IsChanged__c = true;
+            }*/
+
+            boolean sp_change2 = newOrd.SpecialField_IsChanged_ANI__c    ||
+                                 newOrd.SpecialField_IsChanged_BS__c     ||
+                                 newOrd.SpecialField_IsChanged_BS_1__c   ||
+                                 newOrd.SpecialField_IsChanged_Common__c ||
+                                 newOrd.SpecialField_IsChanged_IE__c     ||
+                                 newOrd.SpecialField_IsChanged_NDT__c    ||
+                                 newOrd.SpecialField_IsChanged_RVI__c;
+
+            boolean contract_change2 =
+                (newOrd.CustomerContractPrice__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.CustomerContractPrice__c)).setScale(2).setScale(0)) != (newOrd.CustomerContractPriceD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.CustomerContractPriceD__c)).setScale(2).setScale(0)) ||
+                (newOrd.OlympusContractPrices__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.OlympusContractPrices__c)).setScale(2).setScale(0)) != (newOrd.OlympusContractPricesD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.OlympusContractPricesD__c)).setScale(2).setScale(0)) ||
+                newOrd.EndUser__c != newOrd.EndUserD__c ||
+
+                newOrd.Andor__c != newOrd.Andor_D__c ||
+                newOrd.Bitplane__c != newOrd.Bitplane_D__c ||
+                newOrd.CoolLED__c != newOrd.CoolLED_D__c ||
+                newOrd.Lumen__c != newOrd.Lumen_D__c ||
+                newOrd.Lumenera__c != newOrd.Lumenera_D__c ||
+                newOrd.Media_Cybernetics__c != newOrd.Media_Cybernetics_D__c ||
+                newOrd.Narishige__c != newOrd.Narishige_D__c ||
+                newOrd.Newport__c != newOrd.Newport_D__c ||
+                newOrd.OSIS_Germany__c != newOrd.OSIS_Germany_D__c ||
+                newOrd.OSIS_Singapore__c != newOrd.OSIS_Singapore_D__c ||
+                newOrd.Photometrics__c != newOrd.Photometrics_D__c ||
+                newOrd.Prior_Scientific__c != newOrd.Prior_Scientific_D__c ||
+                newOrd.Q_Imaging__c != newOrd.Q_Imaging_D__c ||
+                newOrd.Tokai_Hit__c != newOrd.Tokai_Hit_D__c ||
+                newOrd.Other_Third__c != newOrd.Other_Third_D__c ||
+                newOrd.ServiceFee__c != newOrd.ServiceFee_D__c ||
+                newOrd.AlongProduct__c != newOrd.AlongProduct_D__c ||
+                newOrd.Cost__c != newOrd.Cost_D__c ||
+                newOrd.Sub_DealerC__c != newOrd.Sub_DealerC_D__c ||
+                (newOrd.IsUpload__c != oldOrd.IsUpload__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true)) ||
+                //闄勪欢鏄惁淇敼
+                newOrd.Upload_IsChanged__c ||
+                newOrd.ForeignTradeCompany__c != newOrd.ForeignTradeCompany_D__c ||
+                newOrd.Shipment_Term__c != newOrd.Shipment_Term_D__c ||
+                newOrd.Shipment_Term2__c != newOrd.Shipment_Term2_D__c ||
+                (newOrd.SpecialDeliveryAccount__c != newOrd.SpecialDeliveryAccount_D__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true)) ||
+                (newOrd.SpecialDeliveryContact2__c != newOrd.SpecialDeliveryContact2_D__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true));
+
+            if (newOrd.IsCopy__c && (newOrd.ApproveStatus__c != 'Completed2' && newOrd.ApproveStatus__c != 'OrderSubmit')&& sp_change2 == false && contract_change2) {
+                system.debug('=====OrderDraft 2=====');
+                //system.debug(newOrd.CustomerContractPrice__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.CustomerContractPrice__c)).setScale(2).setScale(0)) != (newOrd.CustomerContractPriceD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.CustomerContractPriceD__c)).setScale(2).setScale(0));
+                //system.debug(newOrd.OlympusContractPrices__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.OlympusContractPrices__c)).setScale(2).setScale(0)) != (newOrd.OlympusContractPricesD__c == null ? 0 : Decimal.valueOf(String.valueOf(newOrd.OlympusContractPricesD__c)).setScale(2).setScale(0));
+                system.debug(newOrd.EndUser__c != newOrd.EndUserD__c);
+                system.debug(newOrd.Andor__c != newOrd.Andor_D__c);
+                system.debug(newOrd.Bitplane__c != newOrd.Bitplane_D__c);
+                system.debug(newOrd.CoolLED__c != newOrd.CoolLED_D__c);
+                system.debug(newOrd.Lumen__c != newOrd.Lumen_D__c);
+                system.debug(newOrd.Lumenera__c != newOrd.Lumenera_D__c);
+                system.debug(newOrd.Media_Cybernetics__c != newOrd.Media_Cybernetics_D__c);
+                system.debug(newOrd.Narishige__c != newOrd.Narishige_D__c);
+                system.debug(newOrd.Newport__c != newOrd.Newport_D__c);
+                system.debug(newOrd.OSIS_Germany__c != newOrd.OSIS_Germany_D__c);
+                system.debug(newOrd.OSIS_Singapore__c != newOrd.OSIS_Singapore_D__c);
+                system.debug(newOrd.Photometrics__c != newOrd.Photometrics_D__c);
+                system.debug(newOrd.Prior_Scientific__c != newOrd.Prior_Scientific_D__c);
+                system.debug(newOrd.Q_Imaging__c != newOrd.Q_Imaging_D__c);
+                system.debug(newOrd.Tokai_Hit__c != newOrd.Tokai_Hit_D__c);
+                system.debug(newOrd.Other_Third__c != newOrd.Other_Third_D__c);
+                system.debug(newOrd.ServiceFee__c != newOrd.ServiceFee_D__c);
+                system.debug(newOrd.AlongProduct__c != newOrd.AlongProduct_D__c);
+                system.debug(newOrd.Cost__c != newOrd.Cost_D__c);
+                system.debug(newOrd.Sub_DealerC__c != newOrd.Sub_DealerC_D__c);
+                system.debug(newOrd.IsUpload__c != oldOrd.IsUpload__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true));
+                system.debug(newOrd.Upload_IsChanged__c);
+                system.debug(newOrd.ForeignTradeCompany__c != newOrd.ForeignTradeCompany_D__c);
+                system.debug(newOrd.Shipment_Term__c != newOrd.Shipment_Term_D__c);
+                system.debug(newOrd.Shipment_Term2__c != newOrd.Shipment_Term2_D__c);
+                system.debug(newOrd.SpecialDeliveryAccount__c != newOrd.SpecialDeliveryAccount_D__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true));
+                system.debug(newOrd.SpecialDeliveryContact2__c != newOrd.SpecialDeliveryContact2_D__c && ((newOrd.Is_Already_Splited__c == true && newOrd.ApproveStatus__c != 'OrderPass') || newOrd.Is_Already_Splited__c != true));
+                system.debug(newOrd.SpecialDeliveryAccount__c+'!'+newOrd.SpecialDeliveryAccount_D__c);
+                system.debug(newOrd.SpecialDeliveryContact2__c+'!'+newOrd.SpecialDeliveryContact2_D__c);
+                system.debug(newOrd.Is_Already_Splited__c+'!'+newOrd.ApproveStatus__c);
+
+
+
+
+                newOrd.ApproveStatus__c = 'OrderDraft';
+                neword.date_P__c = null;
+            } else if (newOrd.IsCopy__c && newOrd.ApproveStatus__c != 'Completed2' && sp_change2 == false && contract_change2 == false) {
+                system.debug('=====CopyStatus=====');
+                newOrd.ApproveStatus__c = newOrd.CopyStatus__c;
+            }
+
+            if (newOrd.SP_11__c != oldOrd.SP_11__c) {
+                newOrd.SP_11D__c = newOrd.SP_11__c;
+            }
+             if (newOrd.SP_901__c != oldOrd.SP_901__c) {
+                newOrd.SP_901D__c = newOrd.SP_901__c;
+            }
+            if (newOrd.SP_101__c != oldOrd.SP_101__c) {
+                newOrd.SP_101D__c = newOrd.SP_101__c;
+            }
+            if (newOrd.SP_102__c != oldOrd.SP_102__c) {
+                newOrd.SP_102D__c = newOrd.SP_102__c;
+            }
+            if (newOrd.SP_103__c != oldOrd.SP_103__c) {
+                newOrd.SP_103D__c = newOrd.SP_103__c;
+            }
+            if (newOrd.SP_106__c != oldOrd.SP_106__c) {
+                newOrd.SP_106D__c = newOrd.SP_106__c;
+            }
+            if (newOrd.SP_107__c != oldOrd.SP_107__c) {
+                newOrd.SP_107D__c = newOrd.SP_107__c;
+            }
+            if (newOrd.Theoinp__c != oldOrd.Theoinp__c) {
+                newOrd.Theoinp_D__c = newOrd.Theoinp__c;
+            }
+            if (newOrd.SP_745__c != oldOrd.SP_745__c) {
+                newOrd.SP_745D__c = newOrd.SP_745__c;
+            }
+            if (newOrd.SP_111__c != oldOrd.SP_111__c) {
+                newOrd.SP_111D__c = newOrd.SP_111__c;
+            }
+            if (newOrd.SP_121__c != oldOrd.SP_121__c) {
+                newOrd.SP_121D__c = newOrd.SP_121__c;
+            }
+            if (newOrd.SP_131__c != oldOrd.SP_131__c) {
+                newOrd.SP_131D__c = newOrd.SP_131__c;
+            }
+            if (newOrd.SP_141__c != oldOrd.SP_141__c) {
+                newOrd.SP_141D__c = newOrd.SP_141__c;
+            }
+            if (newOrd.SP_151__c != oldOrd.SP_151__c) {
+                newOrd.SP_151D__c = newOrd.SP_151__c;
+            }
+            if (newOrd.SP_161__c != oldOrd.SP_161__c) {
+                newOrd.SP_161D__c = newOrd.SP_161__c;
+            }
+            if (newOrd.SP_171__c != oldOrd.SP_171__c) {
+                newOrd.SP_171D__c = newOrd.SP_171__c;
+            }
+            if (newOrd.SP_181__c != oldOrd.SP_181__c) {
+                newOrd.SP_181D__c = newOrd.SP_181__c;
+            }
+            if (newOrd.SP_191__c != oldOrd.SP_191__c) {
+                newOrd.SP_191D__c = newOrd.SP_191__c;
+            }
+            if (newOrd.SP_201__c != oldOrd.SP_201__c) {
+                newOrd.SP_201D__c = newOrd.SP_201__c;
+            }
+            if (newOrd.SP_202__c != oldOrd.SP_202__c) {
+                newOrd.SP_202D__c = newOrd.SP_202__c;
+            }
+
+
+            if (newOrd.SP_21__c != oldOrd.SP_21__c) {
+                newOrd.SP_21D__c = newOrd.SP_21__c;
+            }
+            if (newOrd.SP_22__c != oldOrd.SP_22__c) {
+                newOrd.SP_22D__c = newOrd.SP_22__c;
+            }
+            if (newOrd.SP_31__c != oldOrd.SP_31__c) {
+                newOrd.SP_31D__c = newOrd.SP_31__c;
+            }
+            if (newOrd.SP_32__c != oldOrd.SP_32__c) {
+                newOrd.SP_32D__c = newOrd.SP_32__c;
+            }
+            if (newOrd.SP_33__c != oldOrd.SP_33__c) {
+                newOrd.SP_33D__c = newOrd.SP_33__c;
+            }
+            if (newOrd.SP_41__c != oldOrd.SP_41__c) {
+                newOrd.SP_41D__c = newOrd.SP_41__c;
+            }
+            if (newOrd.SP_51__c != oldOrd.SP_51__c) {
+                newOrd.SP_51D__c = newOrd.SP_51__c;
+            }
+            if (newOrd.SP_52__c != oldOrd.SP_52__c) {
+                newOrd.SP_52D__c = newOrd.SP_52__c;
+            }
+            if (newOrd.SP_61__c != oldOrd.SP_61__c) {
+                newOrd.SP_61D__c = newOrd.SP_61__c;
+            }
+            if (newOrd.SP_62__c != oldOrd.SP_62__c) {
+                newOrd.SP_62D__c = newOrd.SP_62__c;
+            }
+            if (newOrd.SP_71__c != oldOrd.SP_71__c) {
+                newOrd.SP_71D__c = newOrd.SP_71__c;
+            }
+            if (newOrd.SP_81__c != oldOrd.SP_81__c) {
+                newOrd.SP_81D__c = newOrd.SP_81__c;
+            }
+            if (newOrd.SP_91__c != oldOrd.SP_91__c) {
+                newOrd.SP_91D__c = newOrd.SP_91__c;
+            }
+            //if (newOrd.ConditionContract__c != oldOrd.ConditionContract__c) {
+            //  newOrd.ConditionContract_D__c = newOrd.ConditionContract__c;
+            //}
+            if (newOrd.Contract_Status__c != oldOrd.Contract_Status__c) {
+                newOrd.Contract_StatusD__c = newOrd.Contract_Status__c;
+            }
+            if (newOrd.CustomerContractPrice__c != oldOrd.CustomerContractPrice__c) {
+                newOrd.CustomerContractPriceD__c = newOrd.CustomerContractPrice__c;
+            }
+            //if (newOrd.EffectiveDate != oldOrd.EffectiveDate) {
+            //  newOrd.EffectiveDateD__c = newOrd.EffectiveDate;
+            //}
+            if (newOrd.EndUser__c != oldOrd.EndUser__c) {
+                newOrd.EndUserD__c = newOrd.EndUser__c;
+            }
+            if (newOrd.OlympusContractPrices__c != oldOrd.OlympusContractPrices__c) {
+                newOrd.OlympusContractPricesD__c = newOrd.OlympusContractPrices__c;
+            }
+
+            if (newOrd.IE_SP1__c != oldOrd.IE_SP1__c) {
+                newOrd.IE_SP1_D__c = newOrd.IE_SP1__c;
+            }
+            if (newOrd.IE_SP2__c != oldOrd.IE_SP2__c) {
+                newOrd.IE_SP2_D__c = newOrd.IE_SP2__c;
+            }
+            if (newOrd.IE_SP3__c != oldOrd.IE_SP3__c) {
+                newOrd.IE_SP3_D__c = newOrd.IE_SP3__c;
+            }
+            if (newOrd.IE_SP4__c != oldOrd.IE_SP4__c) {
+                newOrd.IE_SP4_D__c = newOrd.IE_SP4__c;
+            }
+            if (newOrd.IE_SP5__c != oldOrd.IE_SP5__c) {
+                newOrd.IE_SP5_D__c = newOrd.IE_SP5__c;
+            }
+            if (newOrd.IE_SP6__c != oldOrd.IE_SP6__c) {
+                newOrd.IE_SP6_D__c = newOrd.IE_SP6__c;
+            }
+            if (newOrd.IE_SP7__c != oldOrd.IE_SP7__c) {
+                newOrd.IE_SP7_D__c = newOrd.IE_SP7__c;
+            }
+            if (newOrd.IE_SP8__c != oldOrd.IE_SP8__c) {
+                newOrd.IE_SP8_D__c = newOrd.IE_SP8__c;
+            }
+
+
+            if (newOrd.RVI_SP1__c != oldOrd.RVI_SP1__c) {
+                newOrd.RVI_SP1_D__c = newOrd.RVI_SP1__c;
+            }
+            if (newOrd.RVI_SP2__c != oldOrd.RVI_SP2__c) {
+                newOrd.RVI_SP2_D__c = newOrd.RVI_SP2__c;
+            }
+            if (newOrd.RVI_SP3__c != oldOrd.RVI_SP3__c) {
+                newOrd.RVI_SP3_D__c = newOrd.RVI_SP3__c;
+            }
+            if (newOrd.RVI_SP4__c != oldOrd.RVI_SP4__c) {
+                newOrd.RVI_SP4_D__c = newOrd.RVI_SP4__c;
+            }
+            if (newOrd.RVI_SP5__c != oldOrd.RVI_SP5__c) {
+                newOrd.RVI_SP5_D__c = newOrd.RVI_SP5__c;
+            }
+            if (newOrd.RVI_SP6__c != oldOrd.RVI_SP6__c) {
+                newOrd.RVI_SP6_D__c = newOrd.RVI_SP6__c;
+            }
+
+            if (newOrd.NDT_SP1__c != oldOrd.NDT_SP1__c) {
+                newOrd.NDT_SP1_D__c = newOrd.NDT_SP1__c;
+            }
+            if (newOrd.NDT_SP2__c != oldOrd.NDT_SP2__c) {
+                newOrd.NDT_SP2_D__c = newOrd.NDT_SP2__c;
+            }
+            if (newOrd.NDT_SP3__c != oldOrd.NDT_SP3__c) {
+                newOrd.NDT_SP3_D__c = newOrd.NDT_SP3__c;
+            }
+            if (newOrd.NDT_SP4__c != oldOrd.NDT_SP4__c) {
+                newOrd.NDT_SP4_D__c = newOrd.NDT_SP4__c;
+            }
+            if (newOrd.NDT_SP5__c != oldOrd.NDT_SP5__c) {
+                newOrd.NDT_SP5_D__c = newOrd.NDT_SP5__c;
+            }
+            if (newOrd.NDT_SP6__c != oldOrd.NDT_SP6__c) {
+                newOrd.NDT_SP6_D__c = newOrd.NDT_SP6__c;
+            }
+            if (newOrd.NDT_SP7__c != oldOrd.NDT_SP7__c) {
+                newOrd.NDT_SP7_D__c = newOrd.NDT_SP7__c;
+            }
+            if (newOrd.NDT_SP8__c != oldOrd.NDT_SP8__c) {
+                newOrd.NDT_SP8_D__c = newOrd.NDT_SP8__c;
+            }
+            if (newOrd.NDT_SP9__c != oldOrd.NDT_SP9__c) {
+                newOrd.NDT_SP9_D__c = newOrd.NDT_SP9__c;
+            }
+            if (newOrd.NDT_SP10__c != oldOrd.NDT_SP10__c) {
+                newOrd.NDT_SP10_D__c = newOrd.NDT_SP10__c;
+            }
+            if (newOrd.NDT_SP11__c != oldOrd.NDT_SP11__c) {
+                newOrd.NDT_SP11_D__c = newOrd.NDT_SP11__c;
+            }
+
+            if (newOrd.ANI_SP1__c != oldOrd.ANI_SP1__c) {
+                newOrd.ANI_SP1_D__c = newOrd.ANI_SP1__c;
+            }
+            if (newOrd.ANI_SP2__c != oldOrd.ANI_SP2__c) {
+                newOrd.ANI_SP2_D__c = newOrd.ANI_SP2__c;
+            }
+            if (newOrd.ANI_SP3__c != oldOrd.ANI_SP3__c) {
+                newOrd.ANI_SP3_D__c = newOrd.ANI_SP3__c;
+            }
+            if (newOrd.ANI_SP4__c != oldOrd.ANI_SP4__c) {
+                newOrd.ANI_SP4_D__c = newOrd.ANI_SP4__c;
+            }
+            if (newOrd.ANI_SP5__c != oldOrd.ANI_SP5__c) {
+                newOrd.ANI_SP5_D__c = newOrd.ANI_SP5__c;
+            }
+            if (newOrd.ANI_SP6__c != oldOrd.ANI_SP6__c) {
+                newOrd.ANI_SP6_D__c = newOrd.ANI_SP6__c;
+            }
+
+            if (newOrd.NormalDis_SerContractCondition__c != oldOrd.NormalDis_SerContractCondition__c) {
+                newOrd.NormalDis_SerContractCondition_D__c = newOrd.NormalDis_SerContractCondition__c;
+            }
+            if (newOrd.HighDis_SerContractCondition__c != oldOrd.HighDis_SerContractCondition__c) {
+                newOrd.HighDis_SerContractCondition_D__c = newOrd.HighDis_SerContractCondition__c;
+            }
+            if (newOrd.SpecialDis_SerContractCondition__c != oldOrd.SpecialDis_SerContractCondition__c) {
+                newOrd.SpecialDis_SerContractCondition_D__c = newOrd.SpecialDis_SerContractCondition__c;
+            }
+            if (newOrd.Warranty_SerContractCondition__c != oldOrd.Warranty_SerContractCondition__c) {
+                newOrd.Warranty_SerContractCondition_D__c = newOrd.Warranty_SerContractCondition__c;
+            }
+
+
+            if (newOrd.Discount__c != oldOrd.Discount__c) {
+                newOrd.Discount_D__c = newOrd.Discount__c;
+            }
+            if (newOrd.Olympus_Price_BeforeDiscount__c != oldOrd.Olympus_Price_BeforeDiscount__c) {
+                newOrd.Olympus_Price_BeforeDiscount_D__c = newOrd.Olympus_Price_BeforeDiscount__c;
+            }
+            if (newOrd.PaymentCondition__c != oldOrd.PaymentCondition__c) {
+                newOrd.PaymentCondition_D__c = newOrd.PaymentCondition__c;
+            }
+            if (newOrd.SpecialDelivery__c != oldOrd.SpecialDelivery__c) {
+                newOrd.SpecialDelivery_D__c = newOrd.SpecialDelivery__c;
+            }
+            if (newOrd.SpecialDeliveryContact__c != oldOrd.SpecialDeliveryContact__c) {
+                newOrd.SpecialDeliveryContact_D__c = newOrd.SpecialDeliveryContact__c;
+            }
+            if (newOrd.SpecialDeliveryPhone__c != oldOrd.SpecialDeliveryPhone__c) {
+                newOrd.SpecialDeliveryPhone_D__c = newOrd.SpecialDeliveryPhone__c;
+            }
+            if (newOrd.SpecialDeliveryAddress__c != oldOrd.SpecialDeliveryAddress__c) {
+                newOrd.SpecialDeliveryAddress_D__c = newOrd.SpecialDeliveryAddress__c;
+            }
+            if (newOrd.SpecialParkage__c != oldOrd.SpecialParkage__c) {
+                newOrd.SpecialParkage_D__c = newOrd.SpecialParkage__c;
+            }
+            if (newOrd.SpecialWarranty__c != oldOrd.SpecialWarranty__c) {
+                newOrd.SpecialWarranty_D__c = newOrd.SpecialWarranty__c;
+            }
+            if (newOrd.DealerProfit__c != oldOrd.DealerProfit__c) {
+                newOrd.DealerProfit_D__c = newOrd.DealerProfit__c;
+            }
+            if (newOrd.SpecialDelDate__c != oldOrd.SpecialDelDate__c) {
+                newOrd.SpecialDelDate_D__c = newOrd.SpecialDelDate__c;
+            }
+            if (newOrd.OtherApply__c != oldOrd.OtherApply__c) {
+                newOrd.OtherApply_D__c = newOrd.OtherApply__c;
+            }
+
+
+            if (newOrd.Andor__c != oldOrd.Andor__c) {
+                newOrd.Andor_D__c = newOrd.Andor__c;
+            }
+            if (newOrd.Bitplane__c != oldOrd.Bitplane__c) {
+                newOrd.Bitplane_D__c = newOrd.Bitplane__c;
+            }
+            if (newOrd.CoolLED__c != oldOrd.CoolLED__c) {
+                newOrd.CoolLED_D__c = newOrd.CoolLED__c;
+            }
+            if (newOrd.Lumen__c != oldOrd.Lumen__c) {
+                newOrd.Lumen_D__c = newOrd.Lumen__c;
+            }
+            if (newOrd.Lumenera__c != oldOrd.Lumenera__c) {
+                newOrd.Lumenera_D__c = newOrd.Lumenera__c;
+            }
+            if (newOrd.Media_Cybernetics__c != oldOrd.Media_Cybernetics__c) {
+                newOrd.Media_Cybernetics_D__c = newOrd.Media_Cybernetics__c;
+            }
+            if (newOrd.Narishige__c != oldOrd.Narishige__c) {
+                newOrd.Narishige_D__c = newOrd.Narishige__c;
+            }
+            if (newOrd.Newport__c != oldOrd.Newport__c) {
+                newOrd.Newport_D__c = newOrd.Newport__c;
+            }
+            if (newOrd.OSIS_Germany__c != oldOrd.OSIS_Germany__c) {
+                newOrd.OSIS_Germany_D__c = newOrd.OSIS_Germany__c;
+            }
+            if (newOrd.OSIS_Singapore__c != oldOrd.OSIS_Singapore__c) {
+                newOrd.OSIS_Singapore_D__c = newOrd.OSIS_Singapore__c;
+            }
+            if (newOrd.Photometrics__c != oldOrd.Photometrics__c) {
+                newOrd.Photometrics_D__c = newOrd.Photometrics__c;
+            }
+            if (newOrd.Prior_Scientific__c != oldOrd.Prior_Scientific__c) {
+                newOrd.Prior_Scientific_D__c = newOrd.Prior_Scientific__c;
+            }
+            if (newOrd.Q_Imaging__c != oldOrd.Q_Imaging__c) {
+                newOrd.Q_Imaging_D__c = newOrd.Q_Imaging__c;
+            }
+            if (newOrd.Tokai_Hit__c != oldOrd.Tokai_Hit__c) {
+                newOrd.Tokai_Hit_D__c = newOrd.Tokai_Hit__c;
+            }
+            if (newOrd.Other_Third__c != oldOrd.Other_Third__c) {
+                newOrd.Other_Third_D__c = newOrd.Other_Third__c;
+            }
+            if (newOrd.ServiceFee__c != oldOrd.ServiceFee__c) {
+                newOrd.ServiceFee_D__c = newOrd.ServiceFee__c;
+            }
+            if (newOrd.AlongProduct__c != oldOrd.AlongProduct__c) {
+                newOrd.AlongProduct_D__c = newOrd.AlongProduct__c;
+            }
+            if (newOrd.Cost__c != oldOrd.Cost__c) {
+                newOrd.Cost_D__c = newOrd.Cost__c;
+            }
+            if (newOrd.Sub_DealerC__c != oldOrd.Sub_DealerC__c) {
+                newOrd.Sub_DealerC_D__c = newOrd.Sub_DealerC__c;
+            }
+
+            if (newOrd.SpecialDeliveryAccount__c != oldOrd.SpecialDeliveryAccount__c) {
+                newOrd.SpecialDeliveryAccount_D__c = newOrd.SpecialDeliveryAccount__c;
+            }
+            if (newOrd.ForeignTradeCompany__c != oldOrd.ForeignTradeCompany__c) {
+                newOrd.ForeignTradeCompany_D__c = newOrd.ForeignTradeCompany__c;
+                // 澶栬锤閫佽揪鏂归粯璁や负澶栬锤鍏徃
+                if (newOrd.TradeType__c == System.Label.Trade_Type) {
+                    newOrd.SpecialDeliveryAccount__c = newOrd.ForeignTradeCompany__c;
+                    newOrd.SpecialDeliveryAccount_D__c = newOrd.ForeignTradeCompany__c;
+                }
+            }
+            if (newOrd.SpecialDeliveryContact2__c != oldOrd.SpecialDeliveryContact2__c) {
+                newOrd.SpecialDeliveryContact2_D__c = newOrd.SpecialDeliveryContact2__c;
+            }
+            if (newOrd.TradeType__c == System.Label.Trade_Type) {
+                if (newOrd.ForeignTradeCompany_D__c != newOrd.SpecialDeliveryAccount_D__c) {
+                    newOrd.SpecialDeliveryAccount_D__c = newOrd.ForeignTradeCompany_D__c;
+                    system.debug('=====set SpecialDeliveryAccount');
+                }
+            }
+
+            if (newOrd.Shipment_Term__c != oldOrd.Shipment_Term__c) {
+                newOrd.Shipment_Term_D__c = newOrd.Shipment_Term__c;
+            }
+            if (newOrd.Shipment_Term2__c != oldOrd.Shipment_Term2__c) {
+                newOrd.Shipment_Term2_D__c = newOrd.Shipment_Term2__c;
+            }
+            if (newOrd.ProductConfig__c != oldOrd.ProductConfig__c) {
+                newOrd.ProductConfig_D__c = newOrd.ProductConfig__c;
+            }
+
+            if (newOrd.ProductConfig_D__c != oldOrd.ProductConfig_D__c && oldOrd.ProductConfig_D__c != null) {
+                newOrd.ProductConfig_IsChanged__c = true;
+            }
+
+            //IE,鍙湁compo琚�変腑,鍒欎笉闇�瑕佸鎵� gwy 2021-06-02
+            if(newOrd.ProductSegment__c=='IE' && newOrd.Status__c == 'Active' && newOrd.OrderDraft__c == false
+                && newOrd.IE_SP5_D__c == false && newOrd.IE_SP6_D__c == false && newOrd.IE_SP7_D__c == false && newOrd.IE_SP8_D__c == true){
+                newOrd.ApproveStatus__c = 'Pass';
+                newOrd.IsSpPassed__c = true;
+                newOrd.IE_SP8__c = true;
+            }
+            //IE,鍙湁compo琚�変腑,鍒欎笉闇�瑕佸鎵� gwy 2021-06-02
+
+        }
+    }
+
+    /**
+     * XHL20210830
+     * SSBD鍚堝悓鍏变韩鏁版嵁鐨勬嫾鎺�
+     * @param  orderId [SSBD鍚堝悓Id]
+     * @param  userId  [寰呭叡浜殑鐢ㄦ埛Id]
+     * @return         [description]
+     */
+    public static OrderShare DataAssembly(String orderId,String userId){
+        OrderShare aos = new OrderShare(
+            RowCause = 'Manual',
+            orderId = orderId,
+            UserOrGroupId = userId,
+            OrderAccessLevel = 'Edit');
+
+        return aos;
+
+    }
+    /**
+     * 鍚堝悓鏉冮檺鍏变韩 XHL20210830
+     * @param newList [description]
+     * @param newMap  [description]
+     * @param oldList [description]
+     * @param oldMap  [description]
+     */
+    public static void setOrderShare (List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<OrderShare> insertOrderShareList = new List<OrderShare>();
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'OrderShare';
+        String datetimeStr = String.valueOf(Datetime.now()).replace('-','').replace(' ','').replace(':','');
+        iflog.MessageGroupNumber__c = datetimeStr;
+        iflog.Log__c = '';
+        Boolean errrorFlag = false;
+
+        for (Order newOrd : newList) {
+            Order oldOrd = oldMap == null ? new Order() : oldMap.get(newOrd.Id);
+            //鍏变韩鏉冮檺璁剧疆鏍囪瘑 鍙樻洿 涓� 鐪� 骞朵笖 鎵�鏈変汉鍙樻洿锛屽皢鍚堝悓鍏变韩缁� 鍘熸墍鏈変汉
+            System.debug('newOrd.SharedFlag__c--->'+newOrd.SharedFlag__c);
+            System.debug('oldOrd.SharedFlag__c--->'+oldOrd.SharedFlag__c);
+            System.debug('newOrd.SharedFlag__c--->'+newOrd.SharedFlag__c);
+            System.debug('newOrd.OwnerId--->'+newOrd.OwnerId);
+            System.debug('oldOrd.OwnerId--->'+oldOrd.OwnerId);
+
+
+            if (newOrd.SharedFlag__c != oldOrd.SharedFlag__c && newOrd.SharedFlag__c && newOrd.OwnerId != oldOrd.OwnerId) {
+                String userId = oldOrd.OwnerId;
+                insertOrderShareList.add(DataAssembly(newOrd.Id,userId));
+            } else {
+
+                if (newOrd.SharedFlag__c != oldOrd.SharedFlag__c && newOrd.SharedFlag__c) {
+                    iflog.Log__c += 'Order Id --->'+ newOrd.Id + '\n';
+                    iflog.Log__c +=  'newOrd.OwnerId--->'+newOrd.OwnerId + '\n';  
+                    iflog.Log__c +=  'oldOrd.OwnerId--->'+oldOrd.OwnerId + '\n';
+                    errrorFlag = true;  
+                }
+            }
+
+        }
+        if (insertOrderShareList.size() > 0) {
+            system.debug('insertOrderShareList--->'+insertOrderShareList);
+            insert insertOrderShareList;
+        }
+
+        if (errrorFlag) {
+            insert iflog;
+        }
+
+
+    }
+
+    public static void dealerOrderApproval(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        // List<OrderShare> insertOrderShareList = new List<OrderShare>();
+        for (Order newOrd : newList) {
+            Order oldOrd = oldMap.get(newOrd.Id);
+            // if (newOrd.OwnerId <> newOrd.OpportunityOwnerId__c && newOrd.OpportunityOwnerId__c <> null && newOrd.OpportunityOwnerId__c <> '') {
+            //     newOrd.OwnerId = newOrd.OpportunityOwnerId__c;
+            //     newOrd.SharedFlag__c = true;
+            // }
+            // XHL20210830
+            if (newOrd.SharedFlag__c != oldOrd.SharedFlag__c && newOrd.SharedFlag__c && newOrd.OwnerId != newOrd.OpportunityOwnerId__c && newOrd.OpportunityOwnerId__c <> null && newOrd.OpportunityOwnerId__c <> '') {
+                newOrd.OwnerId = newOrd.OpportunityOwnerId__c;   
+            }
+
+            if (newOrd.SharedFlag__c != oldOrd.SharedFlag__c && newOrd.SharedFlag__c){
+                // 璺ㄧ渷浠藉悎浣滈」鐩� 涓虹湡 骞朵笖 鍚堝悓瀹℃壒浜轰笉鏄┖锛屽皢瀹℃壒浜鸿祴鍊肩粰鎵�鏈変汉 Start
+                if (newOrd.CrossCooperativeProject__c && String.isNotBlank(newOrd.SalesOwner_BS__c)) {
+                    newOrd.OwnerId = newOrd.SalesOwner_BS__c;
+                }
+                // 璺ㄧ渷浠藉悎浣滈」鐩� 涓虹湡 骞朵笖 鍚堝悓瀹℃壒浜轰笉鏄┖锛屽皢瀹℃壒浜鸿祴鍊肩粰鎵�鏈変汉 End    
+            }
+            
+            // 
+            if (newOrd.ApproveStatus__c != oldOrd.ApproveStatus__c) {
+                if (newOrd.ApproveStatus__c == 'Pass' && newOrd.IsCopy__c == false) {
+                    newOrd.IsSpPassed__c = true;    
+                }
+                //gwy 2021-06-03 淇敼IE鎴愪负鐗规畩瀹℃壒閫氳繃锛屽悗鎮旈�変簡compo,淇敼鍚堝悓涓嶈Е鍙戦敊璇��
+                //杩欐涓嶇敤浜�
+                /*if (newOrd.ApproveStatus__c == 'Pass' && newOrd.IsCopy__c == false) {
+                    if(newOrd.ProductSegment__c=='IE' && newOrd.Status__c == 'Active' 
+                    && newOrd.IE_SP5_D__c == false && newOrd.IE_SP6_D__c == false && newOrd.IE_SP7_D__c == false && newOrd.IE_SP8_D__c == true){
+                       newOrd.IsSpPassed__c = true;
+                    }else{
+                        newOrd.IsSpPassed__c = true;
+                    } 
+                }*/
+                //if (newOrd.ApproveStatus__c == 'Pass' || newOrd.ApproveStatus__c == 'OrderPass') {
+                if (newOrd.ApproveStatus__c == 'OrderPass' && newOrd.IsCopy__c == false) {
+                    // 鍚堝悓鍒涘缓鏃讹紝宓屽叆鐢婚潰鏇存柊owner
+                    //newOrd.OwnerId = newOrd.OpportunityOwnerId__c;
+                    newOrd.Contract_Status__c = newOrd.Contract_StatusD__c;
+
+                    if (newOrd.IsNew__c == true) {
+                        newOrd.IsNew__c = false;
+                    }
+                    if (newOrd.Upload_IsChanged__c == true) {
+                        newOrd.Upload_IsChanged__c = false;
+                    }
+
+                    //if (newOrd.ApproveStatus__c == 'Pass') {
+                    newOrd.SP_11__c = newOrd.SP_11D__c;
+                    newOrd.SP_901__c = newOrd.SP_901D__c;
+                    newOrd.SP_101__c = newOrd.SP_101D__c;
+                    newOrd.SP_102__c = newOrd.SP_102D__c;
+                    newOrd.SP_103__c = newOrd.SP_103D__c;
+                    newOrd.SP_106__c = newOrd.SP_106D__c;
+                    newOrd.SP_107__c = newOrd.SP_107D__c;
+                    newOrd.Theoinp__c = newOrd.Theoinp_D__c;
+                    newOrd.SP_745__c = newOrd.SP_745D__c;
+                    newOrd.SP_111__c = newOrd.SP_111D__c;
+                    newOrd.SP_121__c = newOrd.SP_121D__c;
+                    newOrd.SP_131__c = newOrd.SP_131D__c;
+                    newOrd.SP_141__c = newOrd.SP_141D__c;
+                    newOrd.SP_151__c = newOrd.SP_151D__c;
+                    newOrd.SP_161__c = newOrd.SP_161D__c;
+                    newOrd.SP_171__c = newOrd.SP_171D__c;
+                    newOrd.SP_181__c = newOrd.SP_181D__c;
+                    newOrd.SP_191__c = newOrd.SP_191D__c;
+                    newOrd.SP_201__c = newOrd.SP_201D__c;
+                    newOrd.SP_202__c = newOrd.SP_202D__c;
+                    newOrd.SP_21__c = newOrd.SP_21D__c;
+                    newOrd.SP_22__c = newOrd.SP_22D__c;
+                    newOrd.SP_31__c = newOrd.SP_31D__c;
+                    newOrd.SP_32__c = newOrd.SP_32D__c;
+                    newOrd.SP_33__c = newOrd.SP_33D__c;
+                    newOrd.SP_41__c = newOrd.SP_41D__c;
+                    newOrd.SP_51__c = newOrd.SP_51D__c;
+                    newOrd.SP_52__c = newOrd.SP_52D__c;
+                    newOrd.SP_61__c = newOrd.SP_61D__c;
+                    newOrd.SP_62__c = newOrd.SP_62D__c;
+                    newOrd.SP_71__c = newOrd.SP_71D__c;
+                    newOrd.SP_81__c = newOrd.SP_81D__c;
+                    newOrd.SP_91__c = newOrd.SP_91D__c;
+
+                    newOrd.IE_SP1__c = newOrd.IE_SP1_D__c;
+                    newOrd.IE_SP2__c = newOrd.IE_SP2_D__c;
+                    newOrd.IE_SP3__c = newOrd.IE_SP3_D__c;
+                    newOrd.IE_SP4__c = newOrd.IE_SP4_D__c;
+                    newOrd.IE_SP5__c = newOrd.IE_SP5_D__c;
+                    newOrd.IE_SP6__c = newOrd.IE_SP6_D__c;
+                    newOrd.IE_SP7__c = newOrd.IE_SP7_D__c;
+                    newOrd.IE_SP8__c = newOrd.IE_SP8_D__c;
+
+                    newOrd.RVI_SP1__c = newOrd.RVI_SP1_D__c;
+                    newOrd.RVI_SP2__c = newOrd.RVI_SP2_D__c;
+                    newOrd.RVI_SP3__c = newOrd.RVI_SP3_D__c;
+                    newOrd.RVI_SP4__c = newOrd.RVI_SP4_D__c;
+                    newOrd.RVI_SP5__c = newOrd.RVI_SP5_D__c;
+                    newOrd.RVI_SP6__c = newOrd.RVI_SP6_D__c;
+
+                    newOrd.NDT_SP1__c = newOrd.NDT_SP1_D__c;
+                    newOrd.NDT_SP2__c = newOrd.NDT_SP2_D__c;
+                    newOrd.NDT_SP3__c = newOrd.NDT_SP3_D__c;
+                    newOrd.NDT_SP4__c = newOrd.NDT_SP4_D__c;
+                    newOrd.NDT_SP5__c = newOrd.NDT_SP5_D__c;
+                    newOrd.NDT_SP6__c = newOrd.NDT_SP6_D__c;
+                    newOrd.NDT_SP7__c = newOrd.NDT_SP7_D__c;
+                    newOrd.NDT_SP8__c = newOrd.NDT_SP8_D__c;
+                    newOrd.NDT_SP9__c = newOrd.NDT_SP9_D__c;
+                    newOrd.NDT_SP10__c = newOrd.NDT_SP10_D__c;
+                    newOrd.NDT_SP11__c = newOrd.NDT_SP11_D__c;
+
+                    newOrd.ANI_SP1__c = newOrd.ANI_SP1_D__c;
+                    newOrd.ANI_SP2__c = newOrd.ANI_SP2_D__c;
+                    newOrd.ANI_SP3__c = newOrd.ANI_SP3_D__c;
+                    newOrd.ANI_SP4__c = newOrd.ANI_SP4_D__c;
+                    newOrd.ANI_SP5__c = newOrd.ANI_SP5_D__c;
+                    newOrd.ANI_SP6__c = newOrd.ANI_SP6_D__c;
+
+                    newOrd.NormalDis_SerContractCondition__c = newOrd.NormalDis_SerContractCondition_D__c;
+                    newOrd.HighDis_SerContractCondition__c = newOrd.HighDis_SerContractCondition_D__c;
+                    newOrd.SpecialDis_SerContractCondition__c = newOrd.SpecialDis_SerContractCondition_D__c;
+                    newOrd.Warranty_SerContractCondition__c = newOrd.Warranty_SerContractCondition_D__c;
+
+                    //}
+
+                    newOrd.Discount__c = newOrd.Discount_D__c;
+                    newOrd.Olympus_Price_BeforeDiscount__c = newOrd.Olympus_Price_BeforeDiscount_D__c;
+                    newOrd.PaymentCondition__c = newOrd.PaymentCondition_D__c;
+                    newOrd.SpecialDelivery__c = newOrd.SpecialDelivery_D__c;
+                    newOrd.SpecialDeliveryContact__c = newOrd.SpecialDeliveryContact_D__c;
+                    newOrd.SpecialDeliveryPhone__c = newOrd.SpecialDeliveryPhone_D__c;
+                    newOrd.SpecialDeliveryAddress__c = newOrd.SpecialDeliveryAddress_D__c;
+                    newOrd.SpecialParkage__c = newOrd.SpecialParkage_D__c;
+                    newOrd.SpecialWarranty__c = newOrd.SpecialWarranty_D__c;
+                    newOrd.DealerProfit__c = newOrd.DealerProfit_D__c;
+                    newOrd.SpecialDelDate__c = newOrd.SpecialDelDate_D__c;
+                    newOrd.OtherApply__c = newOrd.OtherApply_D__c;
+
+                    //if (newOrd.ApproveStatus__c == 'OrderPass') {
+                    newOrd.IsOrderPassed__c = true;
+
+                    newOrd.CustomerContractPrice__c = newOrd.CustomerContractPriceD__c;
+                    newOrd.OlympusContractPrices__c = newOrd.OlympusContractPricesD__c;
+                    newOrd.EndUser__c = newOrd.EndUserD__c;
+
+                    newOrd.Andor__c = newOrd.Andor_D__c;
+                    newOrd.Bitplane__c = newOrd.Bitplane_D__c;
+                    newOrd.CoolLED__c = newOrd.CoolLED_D__c;
+                    newOrd.Lumen__c = newOrd.Lumen_D__c;
+                    newOrd.Lumenera__c = newOrd.Lumenera_D__c;
+                    newOrd.Media_Cybernetics__c = newOrd.Media_Cybernetics_D__c;
+                    newOrd.Narishige__c = newOrd.Narishige_D__c;
+                    newOrd.Newport__c = newOrd.Newport_D__c;
+                    newOrd.OSIS_Germany__c = newOrd.OSIS_Germany_D__c;
+                    newOrd.OSIS_Singapore__c = newOrd.OSIS_Singapore_D__c;
+                    newOrd.Photometrics__c = newOrd.Photometrics_D__c;
+                    newOrd.Prior_Scientific__c = newOrd.Prior_Scientific_D__c;
+                    newOrd.Q_Imaging__c = newOrd.Q_Imaging_D__c;
+                    newOrd.Tokai_Hit__c = newOrd.Tokai_Hit_D__c;
+                    newOrd.Other_Third__c = newOrd.Other_Third_D__c;
+                    newOrd.ServiceFee__c = newOrd.ServiceFee_D__c;
+                    newOrd.AlongProduct__c = newOrd.AlongProduct_D__c;
+                    newOrd.Cost__c = newOrd.Cost_D__c;
+                    newOrd.Sub_DealerC__c = newOrd.Sub_DealerC_D__c;
+                    //}
+
+                    newOrd.ForeignTradeCompany__c = newOrd.ForeignTradeCompany_D__c;
+                    newOrd.SpecialDeliveryAccount__c = newOrd.SpecialDeliveryAccount_D__c;
+                    newOrd.SpecialDeliveryContact2__c = newOrd.SpecialDeliveryContact2_D__c;
+
+                    newOrd.Shipment_Term__c = newOrd.Shipment_Term_D__c;
+                    newOrd.Shipment_Term2__c = newOrd.Shipment_Term2_D__c;
+                    newOrd.ProductConfig__c = newOrd.ProductConfig_D__c;
+                }
+
+                if ((newOrd.ApproveStatus__c == 'Reject' || newOrd.ApproveStatus__c == 'OrderReject') && newOrd.IsNew__c == false) {
+                    //if (newOrd.ApproveStatus__c == 'Reject') {
+                    newOrd.SP_11D__c = newOrd.SP_11__c;
+                    newOrd.SP_101D__c = newOrd.SP_101__c;
+                    newOrd.SP_901D__c = newOrd.SP_901__c;
+                    newOrd.SP_102D__c = newOrd.SP_102__c;
+                    newOrd.SP_103D__c = newOrd.SP_103__c;
+                    newOrd.SP_106D__c = newOrd.SP_106__c;
+                    newOrd.SP_107D__c = newOrd.SP_107__c;
+                    newOrd.Theoinp__c = newOrd.Theoinp_D__c;
+                    newOrd.SP_745D__c = newOrd.SP_745__c;
+                    newOrd.SP_111D__c = newOrd.SP_111__c;
+                    newOrd.SP_121D__c = newOrd.SP_121__c;
+                    newOrd.SP_131D__c = newOrd.SP_131__c;
+                    newOrd.SP_141D__c = newOrd.SP_141__c;
+                    newOrd.SP_151D__c = newOrd.SP_151__c;
+                    newOrd.SP_161D__c = newOrd.SP_161__c;
+                    newOrd.SP_171D__c = newOrd.SP_171__c;
+                    newOrd.SP_181D__c = newOrd.SP_181__c;
+                    newOrd.SP_191D__c = newOrd.SP_191__c;
+                    newOrd.SP_201D__c = newOrd.SP_201__c;
+                    newOrd.SP_202D__c = newOrd.SP_202__c;
+                    newOrd.SP_21D__c = newOrd.SP_21__c;
+                    newOrd.SP_22D__c = newOrd.SP_22__c;
+                    newOrd.SP_31D__c = newOrd.SP_31__c;
+                    newOrd.SP_32D__c = newOrd.SP_32__c;
+                    newOrd.SP_33D__c = newOrd.SP_33__c;
+                    newOrd.SP_41D__c = newOrd.SP_41__c;
+                    newOrd.SP_51D__c = newOrd.SP_51__c;
+                    newOrd.SP_52D__c = newOrd.SP_52__c;
+                    newOrd.SP_61D__c = newOrd.SP_61__c;
+                    newOrd.SP_62D__c = newOrd.SP_62__c;
+                    newOrd.SP_71D__c = newOrd.SP_71__c;
+                    newOrd.SP_81D__c = newOrd.SP_81__c;
+                    newOrd.SP_91D__c = newOrd.SP_91__c;
+
+                    newOrd.IE_SP1_D__c = newOrd.IE_SP1__c;
+                    newOrd.IE_SP2_D__c = newOrd.IE_SP2__c;
+                    newOrd.IE_SP3_D__c = newOrd.IE_SP3__c;
+                    newOrd.IE_SP4_D__c = newOrd.IE_SP4__c;
+                    newOrd.IE_SP5_D__c = newOrd.IE_SP5__c;
+                    newOrd.IE_SP6_D__c = newOrd.IE_SP6__c;
+                    newOrd.IE_SP7_D__c = newOrd.IE_SP7__c;
+                    newOrd.IE_SP8_D__c = newOrd.IE_SP8__c;
+
+                    newOrd.RVI_SP1_D__c = newOrd.RVI_SP1__c;
+                    newOrd.RVI_SP2_D__c = newOrd.RVI_SP2__c;
+                    newOrd.RVI_SP3_D__c = newOrd.RVI_SP3__c;
+                    newOrd.RVI_SP4_D__c = newOrd.RVI_SP4__c;
+                    newOrd.RVI_SP5_D__c = newOrd.RVI_SP5__c;
+                    newOrd.RVI_SP6_D__c = newOrd.RVI_SP6__c;
+
+                    newOrd.NDT_SP1_D__c = newOrd.NDT_SP1__c;
+                    newOrd.NDT_SP2_D__c = newOrd.NDT_SP2__c;
+                    newOrd.NDT_SP3_D__c = newOrd.NDT_SP3__c;
+                    newOrd.NDT_SP4_D__c = newOrd.NDT_SP4__c;
+                    newOrd.NDT_SP5_D__c = newOrd.NDT_SP5__c;
+                    newOrd.NDT_SP6_D__c = newOrd.NDT_SP6__c;
+                    newOrd.NDT_SP7_D__c = newOrd.NDT_SP7__c;
+                    newOrd.NDT_SP8_D__c = newOrd.NDT_SP8__c;
+                    newOrd.NDT_SP9_D__c = newOrd.NDT_SP9__c;
+                    newOrd.NDT_SP10_D__c = newOrd.NDT_SP10__c;
+                    newOrd.NDT_SP11_D__c = newOrd.NDT_SP11__c;
+
+                    newOrd.ANI_SP1_D__c = newOrd.ANI_SP1__c;
+                    newOrd.ANI_SP2_D__c = newOrd.ANI_SP2__c;
+                    newOrd.ANI_SP3_D__c = newOrd.ANI_SP3__c;
+                    newOrd.ANI_SP4_D__c = newOrd.ANI_SP4__c;
+                    newOrd.ANI_SP5_D__c = newOrd.ANI_SP5__c;
+                    newOrd.ANI_SP6_D__c = newOrd.ANI_SP6__c;
+
+                    newOrd.NormalDis_SerContractCondition_D__c = newOrd.NormalDis_SerContractCondition__c;
+                    newOrd.HighDis_SerContractCondition_D__c = newOrd.HighDis_SerContractCondition__c;
+                    newOrd.SpecialDis_SerContractCondition_D__c = newOrd.SpecialDis_SerContractCondition__c;
+                    newOrd.Warranty_SerContractCondition_D__c = newOrd.Warranty_SerContractCondition__c;
+
+                    //}
+
+                    newOrd.Discount_D__c = newOrd.Discount__c;
+                    newOrd.Olympus_Price_BeforeDiscount_D__c = newOrd.Olympus_Price_BeforeDiscount__c;
+                    newOrd.PaymentCondition_D__c = newOrd.PaymentCondition__c;
+                    newOrd.SpecialDelivery_D__c = newOrd.SpecialDelivery__c;
+                    newOrd.SpecialDeliveryContact_D__c = newOrd.SpecialDeliveryContact__c;
+                    newOrd.SpecialDeliveryPhone_D__c = newOrd.SpecialDeliveryPhone__c;
+                    newOrd.SpecialDeliveryAddress_D__c = newOrd.SpecialDeliveryAddress__c;
+                    newOrd.SpecialParkage_D__c = newOrd.SpecialParkage__c;
+                    newOrd.SpecialWarranty_D__c = newOrd.SpecialWarranty__c;
+                    newOrd.DealerProfit_D__c = newOrd.DealerProfit__c;
+                    newOrd.SpecialDelDate_D__c = newOrd.SpecialDelDate__c;
+                    newOrd.OtherApply_D__c = newOrd.OtherApply__c;
+
+                    if (newOrd.ApproveStatus__c == 'OrderReject') {
+                        newOrd.CustomerContractPriceD__c = newOrd.CustomerContractPrice__c;
+                        newOrd.OlympusContractPricesD__c = newOrd.OlympusContractPrices__c;
+                        newOrd.EndUserD__c = newOrd.EndUser__c;
+
+                        newOrd.Andor_D__c = newOrd.Andor__c;
+                        newOrd.Bitplane_D__c = newOrd.Bitplane__c;
+                        newOrd.CoolLED_D__c = newOrd.CoolLED__c;
+                        newOrd.Lumen_D__c = newOrd.Lumen__c;
+                        newOrd.Lumenera_D__c = newOrd.Lumenera__c;
+                        newOrd.Media_Cybernetics_D__c = newOrd.Media_Cybernetics__c;
+                        newOrd.Narishige_D__c = newOrd.Narishige__c;
+                        newOrd.Newport_D__c = newOrd.Newport__c;
+                        newOrd.OSIS_Germany_D__c = newOrd.OSIS_Germany__c;
+                        newOrd.OSIS_Singapore_D__c = newOrd.OSIS_Singapore__c;
+                        newOrd.Photometrics_D__c = newOrd.Photometrics__c;
+                        newOrd.Prior_Scientific_D__c = newOrd.Prior_Scientific__c;
+                        newOrd.Q_Imaging_D__c = newOrd.Q_Imaging__c;
+                        newOrd.Tokai_Hit_D__c = newOrd.Tokai_Hit__c;
+                        newOrd.Other_Third_D__c = newOrd.Other_Third__c;
+                        newOrd.ServiceFee_D__c = newOrd.ServiceFee__c;
+                        newOrd.AlongProduct_D__c = newOrd.AlongProduct__c;
+                        newOrd.Cost_D__c = newOrd.Cost__c;
+                        newOrd.Sub_DealerC_D__c = newOrd.Sub_DealerC__c;
+
+                        newOrd.ForeignTradeCompany_D__c = newOrd.ForeignTradeCompany__c;
+                        newOrd.SpecialDeliveryAccount_D__c = newOrd.SpecialDeliveryAccount__c;
+                        newOrd.SpecialDeliveryContact2_D__c = newOrd.SpecialDeliveryContact2__c;
+
+                        newOrd.Shipment_Term_D__c = newOrd.Shipment_Term__c;
+                        newOrd.Shipment_Term2_D__c = newOrd.Shipment_Term2__c;
+                    }
+
+                    newOrd.Contract_StatusD__c = newOrd.Contract_Status__c;
+                    newOrd.ProductConfig_D__c = newOrd.ProductConfig__c;
+
+                    if (newOrd.Upload_IsChanged__c == true) {
+                        newOrd.Upload_IsChanged__c = false;
+                    }
+
+                }
+            }
+        }
+
+        // if (insertOrderShareList.size()>0) {
+        //     system.debug('insertOrderShareList--->'+insertOrderShareList);
+        //     insert insertOrderShareList;
+        // }
+    }
+
+    public static void setApprover(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<String> ownerIdList = new List<String>();
+        Map<String, String> orderToOwner = new Map<String, String>();
+
+        Map<String, SObjectField> sObjectFieldMaps = Schema.getGlobalDescribe().get('Order').getDescribe().fields.getMap();
+
+        Map<String, List<String>> orderMap = new Map<String, List<String>>();
+
+        //瀛樻斁璁㈠崟琛岄」鐩搴旂殑璁㈠崟鐨処D
+        /*List<String> otmIdList = new List<String>();*/
+
+        //瀛樻斁璁㈠崟琛岄」鐩湁浜у搧鐨勮鍗旾D
+        List<String> ordIdList = new List<String>();
+        //鏄惧井闀滈檷绾�,瀹氫箟涓�涓猰ap鐢ㄤ簬鎺ユ敹鏈�涓嬮潰鐨刲evelcheck鏂规硶浼犳潵鐨凪AP銆�
+        Map<Id,String> levelMap = new Map<Id,String>();
+        For (Order newOrder: newList) {
+
+            if (newOrder.UpdateWithAG__c && newOrder.CrossCooperativeProject__c && (newOrder.SplitRatio__c == null || newOrder.SplitRatio__c == '')) {
+                newOrder.addError('璇峰~鍐欎笟缁╂媶鍒嗘瘮渚嬨��');
+            }
+
+            Order oldOrder = oldMap.get(newOrder.Id);
+            //鏄惧井闀滈檷绾�
+            if (newOrder.ProductSegment__c == 'BS') {
+                ordIdList.add(newOrder.Id);
+            }
+            
+
+            if (oldOrder.ApproveStatus__c != newOrder.ApproveStatus__c && (newOrder.ApproveStatus__c == 'Completed' || newOrder.ApproveStatus__c == 'Completed2' || newOrder.ApproveStatus__c == 'CompletedC' || newOrder.ApproveStatus__c == 'CompletedS' )) {
+                ownerIdList.add(newOrder.OpportunityOwnerId__c);
+                ownerIdList.add(newOrder.SalesOwner_BS__c);
+                if(newOrder.CrossCooperativeProject__c){
+                    orderToOwner.put(newOrder.Id, newOrder.SalesOwner_BS__c);
+                }else{
+                    orderToOwner.put(newOrder.Id, newOrder.OpportunityOwnerId__c);
+                }
+            }
+
+            if (newOrder.Description != null && newOrder.Description.length() > 0) {
+                newOrder.Description += ' \r\n ';
+            } if (newOrder.Description == null) {
+                newOrder.Description = '';
+            }
+            if (newOrder.SP_151__c == true && oldOrder.SP_151__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_151__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_161__c == true && oldOrder.SP_161__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_161__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_171__c == true && oldOrder.SP_171__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_171__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_191__c == true && oldOrder.SP_191__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_191__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_201__c == true && oldOrder.SP_201__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_201__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_202__c == true && oldOrder.SP_202__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_202__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_21__c == true && oldOrder.SP_21__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_21__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_22__c == true && oldOrder.SP_22__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_22__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_41__c == true && oldOrder.SP_41__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_41__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_61__c == true && oldOrder.SP_61__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_61__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_81__c == true && oldOrder.SP_81__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_81__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_181__c == true && oldOrder.SP_181__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_181__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_33__c == true && oldOrder.SP_33__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_33__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_11__c == true && oldOrder.SP_11__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_11__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_901__c == true && oldOrder.SP_901__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_901__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_111__c == true && oldOrder.SP_111__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_111__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_101__c == true && oldOrder.SP_101__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_101__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_106__c == true && oldOrder.SP_106__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_106__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_107__c == true && oldOrder.SP_107__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_107__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.Theoinp__c == true && oldOrder.Theoinp__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('Theoinp__c').getDescribe().getLabel() + ' \r\n ';
+            }
+            if (newOrder.SP_745__c == true && oldOrder.SP_745__c == false) {
+                newOrder.Description += sObjectFieldMaps.get('SP_745__c').getDescribe().getLabel() + ' \r\n ';
+            }
+
+            if (newOrder.SP_151__c == false && oldOrder.SP_151__c == true) {
+                newOrder.Description = newOrder.Description.replace(sObjectFieldMaps.get('SP_151__c').getDescribe().getLabel() + ' \r\n ', '');
+            }
+            if (newOrder.SP_161__c == false && oldOrder.SP_161__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_161__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_171__c == false && oldOrder.SP_171__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_171__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_191__c == false && oldOrder.SP_191__c == true) {
+                newOrder.Description = newOrder.Description.replace(sObjectFieldMaps.get('SP_191__c').getDescribe().getLabel() + ' \r\n ', '');
+            }
+            if (newOrder.SP_201__c == false && oldOrder.SP_201__c == true) {
+                newOrder.Description = newOrder.Description.replace(sObjectFieldMaps.get('SP_201__c').getDescribe().getLabel() + ' \r\n ', '');
+            }
+
+            if (newOrder.SP_202__c == false && oldOrder.SP_202__c == true) {
+                newOrder.Description = newOrder.Description.replace(sObjectFieldMaps.get('SP_202__c').getDescribe().getLabel() + ' \r\n ', '');
+            }
+
+            if (newOrder.SP_21__c == false && oldOrder.SP_21__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_21__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_22__c == false && oldOrder.SP_22__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_22__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_41__c == false && oldOrder.SP_41__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_41__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_61__c == false && oldOrder.SP_61__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_61__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_81__c == false && oldOrder.SP_81__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_81__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_181__c == false && oldOrder.SP_181__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_181__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_33__c == false && oldOrder.SP_33__c == true) {
+                newOrder.Description =  newOrder.Description.remove(sObjectFieldMaps.get('SP_33__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_11__c == false && oldOrder.SP_11__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_11__c').getDescribe().getLabel() + ' \r\n ');
+            }
+             if (newOrder.SP_901__c == false && oldOrder.SP_901__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_901__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_111__c == false && oldOrder.SP_111__c == true) {
+                newOrder.Description =  newOrder.Description.remove(sObjectFieldMaps.get('SP_111__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_101__c == false && oldOrder.SP_101__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_101__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_106__c == false && oldOrder.SP_106__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_106__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_107__c == false && oldOrder.SP_107__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_107__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.Theoinp__c == false && oldOrder.Theoinp__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('Theoinp__c').getDescribe().getLabel() + ' \r\n ');
+            }
+            if (newOrder.SP_745__c == false && oldOrder.SP_745__c == true) {
+                newOrder.Description = newOrder.Description.remove(sObjectFieldMaps.get('SP_745__c').getDescribe().getLabel() + ' \r\n ');
+            }
+        }
+
+        //鏄惧井闀滈檷绾�
+        levelMap = levelCheck(ordIdList);
+        //for()
+
+        Map<Id, User> copyUserMap = new Map<Id, User>([
+                    SELECT Id, Name, SalesAsistManager__c, BusinessDepOwner_Tax__c, BusinessDepOwner_WithoutTax__c, SalesManager__c, AsistGenManger__c, CRM_Owner__c,
+                    BS_AsistGenManger__c,BS_AsistBGenManger__c,Department__c,BS_BDepartment__c,BS_GeneralManager__c,BS_INDepartment__c,BS_Department__c,BS_Manager__c
+                    FROM User WHERE Id IN :ownerIdList
+                ]);
+        
+        for (Order newOrder : newList) {
+            Order oldOrder = oldMap.get(newOrder.Id);
+            if (oldOrder.ApproveStatus__c != newOrder.ApproveStatus__c && (newOrder.ApproveStatus__c == 'Completed' || newOrder.ApproveStatus__c == 'Completed2' || newOrder.ApproveStatus__c == 'CompletedC' || newOrder.ApproveStatus__c == 'CompletedS' )) {
+
+                // WLIG-C253VM NDT涓嶢NI鐨勫悎鍚岋紝鍙戦�佺粰 钀ヤ笟绠$悊閮ㄦ媴褰� START
+                if ('NDT'.equals(newOrder.ProductSegment__c)  || 'ANI'.equals(newOrder.ProductSegment__c)) {
+                    String HaiXingYue = System.Label.NDT_ANI_Addressee_HaiXingYue;
+                    String WangJingQi = System.Label.NDT_ANI_Addressee_WangJingQi;
+                    String ZhenJiaLi  = System.Label.NDT_ANI_Addressee_ZhenJiaLi;
+                    String ShangYun  = System.Label.NDT_ANI_Addressee_ShangYun;
+                    if (String.isNotBlank(HaiXingYue) && HaiXingYue.indexOf(newOrder.DealerId__c) >= 0) {
+                        newOrder.NDT_ANI_Addressee__c = HaiXingYue.indexOf(';') >= 0 ?HaiXingYue.split(';')[1]:null;
+                    } else if (String.isNotBlank(WangJingQi) && WangJingQi.indexOf(newOrder.DealerId__c) >= 0 ) {
+                        newOrder.NDT_ANI_Addressee__c = WangJingQi.indexOf(';') >= 0 ?WangJingQi.split(';')[1]:null;
+                    } else if (String.isNotBlank(ZhenJiaLi) && ZhenJiaLi.indexOf(newOrder.DealerId__c) >= 0 ) {
+                        newOrder.NDT_ANI_Addressee__c = ZhenJiaLi.indexOf(';') >= 0 ?ZhenJiaLi.split(';')[1]:null;
+                    } else if (String.isNotBlank(ShangYun) && ShangYun.indexOf(newOrder.DealerId__c) >= 0 ) {
+                        newOrder.NDT_ANI_Addressee__c = ShangYun.indexOf(';') >= 0 ?ShangYun.split(';')[1]:null;
+                    }
+                } 
+
+                // WLIG-C253VM NDT涓嶢NI鐨勫悎鍚岋紝鍙戦�佺粰 钀ヤ笟绠$悊閮ㄦ媴褰� END
+
+
+
+                User u = copyUserMap.get(orderToOwner.get(newOrder.Id));
+                if (u != null && (u.SalesAsistManager__c != null || u.Department__c != null || u.BusinessDepOwner_Tax__c != null || u.BusinessDepOwner_WithoutTax__c != null || u.SalesManager__c != null || u.AsistGenManger__c != null)) {
+                    if(newOrder.CrossCooperativeProject__c == false){
+                        newOrder.SalesOwner_BS__c = newOrder.OpportunityOwnerId__c;
+                    }
+                    
+                    newOrder.SalesAsistManager_BS__c = u.SalesAsistManager__c == null ? u.Id : u.SalesAsistManager__c;
+                    // 褰撻粍骞虫睙鐨処E瀹岀◣鍚堝悓锛屼互涓嬬渷浠戒笟鍔¢儴瀹℃壒浜轰负閮戣蕉鐩� 2018/11/30
+                    if (newOrder.ProductSegment__c == 'IE' && u.Id == '00528000000YVFs' && (newOrder.Province__c == '娌冲崡' || newOrder.Province__c == '灞变笢'
+                            || newOrder.Province__c == '骞夸笢' || newOrder.Province__c == '绂忓缓' || newOrder.Province__c == '閲嶅簡' || newOrder.Province__c == '婀栧崡'
+                            || newOrder.Province__c == '婀栧寳')) { //2018/1/31 IE鍗庡崡,鍗楁柟,鍖楁柟 閮�->闃�
+                        newOrder.BusinessDepOwnerTax_BS__c = '0050K000009Qbjg';
+                    } else {
+                        newOrder.BusinessDepOwnerTax_BS__c = u.BusinessDepOwner_Tax__c == null ? u.Id : u.BusinessDepOwner_Tax__c;
+                        //newOrder.BusinessDepOwnerTax_BS__c = '0050K000009Qbjg';
+                    }
+
+                    // 褰撻粍骞虫睙鐨処E瀹岀◣鍚堝悓鍏朵粬鐪佷唤锛屼笟鍔¢儴瀹℃壒浜轰负闃欐枃娲� 2018/11/30
+                    // RVI瀹岀◣鍚堝悓涓氬姟閮ㄥ鎵逛汉淇敼  2017/5/4
+                    //       if (newOrder.ProductSegment__c == 'RVI' && (newOrder.Area_RVI_Approve__c == '鍗庝笢' || newOrder.Area_RVI_Approve__c == '瑗垮崡'
+                    //       )){
+                    //          newOrder.BusinessDepOwnerTax_BS__c = '00528000000YSW5';
+                    //       }
+                    // RVI瀹岀◣鍚堝悓涓氬姟閮ㄥ鎵逛汉淇敼  2017/5/4
+                    //     else {newOrder.BusinessDepOwnerTax_BS__c = u.BusinessDepOwner_Tax__c == null ? u.Id : u.BusinessDepOwner_Tax__c;}
+                    newOrder.BusinessDepOwnerWithoutTax_BS__c = u.BusinessDepOwner_WithoutTax__c == null ? u.Id : u.BusinessDepOwner_WithoutTax__c;
+                    newOrder.BS_Manager_BS__c = u.BS_Manager__c == null ? u.Id : u.BS_Manager__c;
+                    newOrder.SalesManager_BS__c = u.SalesManager__c == null ? u.Id : u.SalesManager__c;
+                    newOrder.AsistGenManger_BS__c = u.AsistGenManger__c == null ? u.Id : u.AsistGenManger__c;
+                    newOrder.CRM_Owner__c = u.CRM_Owner__c == null ? u.Id : u.CRM_Owner__c;
+                    if (newOrder.ProductSegment__c == 'BS') {
+                        newOrder.BS_Manager_BS__c         = u.BS_Manager__c         == null ? u.Id : u.BS_Manager__c;
+                        newOrder.BS_Department_BS__c      = u.BS_Department__c      == null ? u.Id : u.BS_Department__c;
+                        newOrder.BS_INDepartment_BS__c    = u.BS_INDepartment__c    == null ? u.Id : u.BS_INDepartment__c;
+                        newOrder.BS_GeneralManager_BS__c  = u.BS_GeneralManager__c  == null ? u.Id : u.BS_GeneralManager__c;
+                        newOrder.BS_BDepartment_BS__c     = u.BS_BDepartment__c     == null ? u.Id : u.BS_BDepartment__c;
+                        newOrder.BS_AsistBGenManger_BS__c = u.BS_AsistBGenManger__c == null ? u.Id : u.BS_AsistBGenManger__c;
+                        newOrder.BS_AsistGenManger_BS__c  = u.BS_AsistGenManger__c  == null ? u.Id : u.BS_AsistGenManger__c;
+
+                        newOrder.BS_MandAGM__c  = u.BS_Manager__c         == u.BS_AsistGenManger__c ? true : false;
+                        newOrder.BS_AGMandD__c  = u.BS_AsistGenManger__c  == u.BS_Department__c ? true : false;
+                        newOrder.BS_DandAB__c   = u.BS_Department__c      == u.BS_AsistBGenManger__c ? true : false;
+                        newOrder.BS_ABGandBD__c = u.BS_AsistBGenManger__c == u.BS_BDepartment__c ? true : false;
+                        newOrder.BS_BDandIND__c = u.BS_BDepartment__c     == u.BS_INDepartment__c ? true : false;
+                        newOrder.BS_INDandGM__c = u.BS_INDepartment__c    == u.BS_GeneralManager__c ? true : false;
+                    }
+                }
+
+
+                if (newOrder.ProductSegment__c != 'BS') {
+                    newOrder.SalesOwner_BS__c = newOrder.OpportunityOwnerId__c;
+                }
+            }
+            //鐜嬮箯浼熸柊鍔狅紝闈濷T_IT鐢ㄦ埛鏇存柊鍚堝悓鏃惰褰曟渶鍚庢洿鏂版椂闂村拰鏇存柊鐢ㄦ埛
+            if (UserInfo.getUserId().substring(0,15) != '00528000004ooQW') {
+                newOrder.OrderUpdateDateTime__c = Datetime.now();
+                newOrder.OrderUpdateUser__c = UserInfo.getUserId();
+            }
+            //if (newOrder.RecordTypeId == '01228000000NJt8') {
+            if (newOrder.ProductSegment__c == 'BS' && newOrder.Is_TAX__c == true && newOrder.AccoutMatketD__c == 'Clinical') {
+                //鏄惧井闀滈檷绾�
+                newOrder.Level_Category__c = levelMap.get(newOrder.id);
+            }   
+            //}
+        }
+    }
+
+
+// Added by hanchao for profitcaculation check
+    public static void ProfitApproveCheck(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        //String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        for (Order newOrder : newList) {
+            Order oldOrder = oldMap.get(newOrder.Id);
+            // String profileId = UserInfo.getProfileId().subString(0,15);
+//   if (profileId.subString(0,15) == System.label.Business_department && newOrder.Discount_D__c != null && newOrder.BusinessOwner_IsApproved__c == true &&
+//   newOrder.BusinessOwner_IsApproved__c != oldOrder.BusinessOwner_IsApproved__c && (newOrder.Ben_2__c == null || newOrder.Ben_3__c == null
+//       || newOrder.Ben_4__c == null || newOrder.Ben_5__c == null || newOrder.Ben_6__c == null || newOrder.Ben_7__c == null)) {
+//       newOrder.addError('鏈夋姌鎵f椂锛屼笟鍔¢儴浜哄憳闇�瑕佸~鍐欏埄鐩婅绠楀�笺��');
+//        }
+
+            if ( new_profileId.subString(0, 15) == System.label.Business_department
+                && newOrder.ApproveStatus__c == 'OrderPass' &&
+                    newOrder.ApproveStatus__c != oldOrder.ApproveStatus__c && (newOrder.OrderDate__c == null || newOrder.SAP_Contract__c == null)) {
+                newOrder.addError('鎵瑰噯璁㈠崟鏃讹紝涓氬姟閮ㄤ汉鍛樺繀椤诲~鍐橲AP璁㈠崟缂栧彿鍜岃鍗曟棩銆�');
+            }
+        }
+    }
+
+// Added by hanchao for trade management category check 171016
+    public static void TradeMagCategoryCheck(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        for (Order newOrder : newList) {
+            Order oldOrder = oldMap.get(newOrder.Id);
+            // String profileId = UserInfo.getProfileId().subString(0,15);
+
+            if (new_profileId.subString(0, 15) == System.label.BusinessMagDep
+                && (newOrder.ApproveStatus__c == 'OrderSubmit' ||
+                    newOrder.ApproveStatus__c == 'OrderDraft') && newOrder.BusMagApp__c == true && newOrder.BusMagApp__c != oldOrder.BusMagApp__c ) {
+                if (newOrder.TradeMagCategory__c == null) {
+                    newOrder.addError('鎵瑰噯璁㈠崟鏃讹紝涓氬姟绠$悊閮ㄤ汉鍛樺繀椤婚�夋嫨璐告槗绠$悊瀹㈡埛鍒嗙被銆�');
+                } else if ((newOrder.TradeMagCategory__c == 'B' || newOrder.TradeMagCategory__c == 'C' || newOrder.TradeMagCategory__c == 'C-') && newOrder.TradeMagNo__c == null) {
+                    newOrder.addError('璐告槗绠$悊瀹㈡埛鍒嗙被涓築锛孋鎴朇-鏃讹紝蹇呴』杈撳叆璐告槗绠$悊缂栧彿銆�');
+                }
+            }
+        }
+    }
+
+// add by hanchao 2017/02/09
+    public static void BackToPreStatus(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        for (Order newOrder : newList) {
+            Order oldOrder = oldMap.get(newOrder.Id);
+            // String profileId = UserInfo.getProfileId();
+            if (newOrder.BackToPreStatus__c != oldOrder.BackToPreStatus__c && newOrder.BackToPreStatus__c == true) {
+                newOrder.ApproveStatus__c = newOrder.BeforeSubmitStatus__c;
+                newOrder.RecordTypeId = newOrder.BeforeSubmitRecordType__c;
+                newOrder.BackToPreStatus__c = false;
+            }
+            if ((newOrder.SpecialDeliveryAccount_D__c != oldOrder.SpecialDeliveryAccount_D__c || newOrder.SpecialDeliveryContact2_D__c != oldOrder.SpecialDeliveryContact2_D__c) && newOrder.ApproveStatus__c == 'OrderPass') {
+                newOrder.SpecialDeliveryAccount__c = newOrder.SpecialDeliveryAccount_D__c;
+                newOrder.SpecialDeliveryContact2__c = newOrder.SpecialDeliveryContact2_D__c;
+            }
+
+        }
+    }
+
+    public static void setOpportunity(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        /*if(StaticParameter.OrderTriggerIsUpdate){
+            //StaticParameter.OrderTriggerIsUpdate = false;
+            return;
+        }*/
+        system.debug('@#@#@#@#'+StaticParameter.OrderTriggerIsUpdate);
+        List<Opportunity> updList = new List<Opportunity>();
+        Map<String,Opportunity> oppMap = new Map<String,Opportunity>();
+        for (Order newOrder : newList) {
+            Order oldOrder = oldMap.get(newOrder.Id);
+            System.debug(newOrder.Name);
+            System.debug(oldOrder.Name);
+            if( StaticParameter.temp == false){
+                Opportunity opp = new Opportunity();
+                opp.Id = newOrder.OpportunityId;
+                if (newOrder.OrderDate__c != oldOrder.OrderDate__c) {
+                    opp.Order_Date__c = newOrder.OrderDate__c;
+                }
+                if (newOrder.DeliveryTime__c != oldOrder.DeliveryTime__c) {
+                    opp.DeliveryDate__c = newOrder.DeliveryTime__c;
+                }
+
+                System.debug(newOrder.Name);
+                System.debug(oldOrder.Name);
+                if (newOrder.Name != oldOrder.Name) {
+                    opp.InquiryResult__c = newOrder.Name;
+                }
+                if(newOrder.ProductSegment__c == 'BS' && newOrder.SubDealer__c != oldOrder.SubDealer__c){
+                    opp.SubDealer__c = newOrder.SubDealer__c;
+                }
+                opp.CanChangeOpp__c = (newOrder.ApproveStatus__c== 'OrderSubmit' || newOrder.ApproveStatus__c == 'OrderPass') ? false : true;
+                opp.OrderId__c = newOrder.Id;
+                // oppMap.put(newOrder.OpportunityId,opp);
+                String oppId = newOrder.OpportunityId;
+                // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 Start
+                if(String.isNotBlank(oppId)){
+                    oppMap.put(newOrder.OpportunityId,opp);
+                }
+                // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 End
+                // oppMap.put(newOrder.OpportunityId,opp);
+                system.debug('@@@@@@@@@@@@@@@@@!!!!'+opp);
+                //updList.add(opp);
+            }
+
+            //鐜嬮箯浼熸柊鍔犲紑濮� 璐告槗绠$悊瀹㈡埛鍒嗙被锛岃浠峰悎鍚屼繚鎸佷竴鑷达紝鍚堝悓淇敼鏇存柊璇环
+            if(oldOrder.TradeMagCategory__c != newOrder.TradeMagCategory__c){
+                //鏇存柊璇环璺宠繃璇环鏇存柊鍚庣殑trigger
+                StaticParameter.OpportunityTriggerIsUpdate = true;
+                if(oppMap.containsKey(newOrder.OpportunityId)){
+                    oppMap.get(newOrder.OpportunityId).customerType__c = newOrder.TradeMagCategory__c;
+                }else{
+                    // Opportunity opp = new Opportunity();
+                    // opp.Id = newOrder.OpportunityId;
+                    // opp.customerType__c = newOrder.TradeMagCategory__c;
+                    // oppMap.put(newOrder.OpportunityId,opp);
+                    // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 Start
+                    String oppId = newOrder.OpportunityId;
+                    if(String.isNotBlank(oppId)){
+                        Opportunity opp = new Opportunity();
+                        opp.Id = newOrder.OpportunityId;
+                        opp.customerType__c = newOrder.TradeMagCategory__c;
+                        oppMap.put(newOrder.OpportunityId,opp);
+                    }
+                    // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 End
+                }
+            }
+            //鐜嬮箯浼熸柊鍔犵粨鏉� 璐告槗绠$悊瀹㈡埛鍒嗙被锛岃浠峰悎鍚屼繚鎸佷竴鑷达紝鍚堝悓淇敼鏇存柊璇环
+
+            // 鐜嬮箯浼� 鍚堝悓鏄疘E锛�3.COMPO鍕鹃�夛紝鏇存柊瀵瑰簲璇环condition__c瀛楁
+            // 寮�濮�
+            if(newOrder.ProductSegment__c=='IE' && newOrder.IE_SP8_D__c != oldOrder.IE_SP8_D__c && String.valueOf(newOrder.Status__c) == 'Active'){
+                System.debug('淇敼鍚堝悓鏇存柊璇环 COMPO');
+               if(oppMap.containsKey(newOrder.OpportunityId)){
+                    if(newOrder.IE_SP8_D__c){
+                        oppMap.get(newOrder.OpportunityId).condition__c = 'Y';
+                    }else{
+                        oppMap.get(newOrder.OpportunityId).condition__c = '';
+                    }
+               }else{
+                    // Opportunity opp1 = new Opportunity();
+                    // opp1.Id = newOrder.OpportunityId;
+                    // if(newOrder.IE_SP8_D__c){
+                    //     opp1.condition__c = 'Y';
+                    // }else{
+                    //     opp1.condition__c = '';
+                    // }
+                    // updList.add(opp1);
+                    String opp1Id = newOrder.OpportunityId;
+                    // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 Start
+                    if (String.isNotBlank(opp1Id)) {
+                        Opportunity opp1 = new Opportunity();
+                        opp1.Id = opp1Id;
+                        if(newOrder.IE_SP8_D__c){
+                            opp1.condition__c = 'Y';
+                        }else{
+                            opp1.condition__c = '';
+                        }
+                        updList.add(opp1);
+                    }
+                    // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 End
+               }
+            }
+            //鐜嬮箯浼� 缁撴潫
+
+            //鐜嬮箯浼� 寮�濮�
+            //璇环鍏宠仈鐨勫悎鍚屽鎵瑰畬鎴愶紝鏈塖AP鍚堝悓缂栧彿鍜岃鍗曟棩 璇环鍋滄鍙戦�侀偖浠讹紙涓嶅啀瀵硅浠锋洿鏂拌繘琛屾鏌ヨ窡韪級
+            if((newOrder.ApproveStatus__c == 'OrderPass' && newOrder.ApproveStatus__c != oldOrder.ApproveStatus__c) || (newOrder.OrderDate__c !=null &&  newOrder.SAP_Contract__c!=null ) &&(newOrder.OrderDate__c != oldOrder.OrderDate__c || newOrder.SAP_Contract__c != oldOrder.SAP_Contract__c ) && StaticParameter.OpportunityTriggerIsUpdate == false){
+                System.debug('Order StaticParameter.OpportunityTriggerIsUpdate:'+StaticParameter.OpportunityTriggerIsUpdate);
+                StaticParameter.OpportunityTriggerIsUpdate = true;
+                if(oppMap.containsKey(newOrder.OpportunityId)){
+                    oppMap.get(newOrder.OpportunityId).IsSendEmail__c = false;
+                }else{
+                    // Opportunity opp1 = new Opportunity();
+                    // opp1.Id = newOrder.OpportunityId;
+                    // opp1.IsSendEmail__c = false;
+                    // updList.add(opp1);
+                    String opp1Id = newOrder.OpportunityId;
+                    // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 Start
+                    if (String.isNotBlank(opp1Id)) {
+                        Opportunity opp1 = new Opportunity();
+                        opp1.Id = newOrder.OpportunityId;
+                        opp1.IsSendEmail__c = false;
+                        updList.add(opp1);
+                    }
+                    // 鍥犺鍗曟暟鎹腑鍖呭惈鏈� 娌℃湁璇环鐨勫巻鍙叉暟鎹� 鐗规澶勭悊 XHL 20210705 End
+                }
+            }
+            //璇环鍏宠仈鐨勫悎鍚屽鎵瑰畬鎴愶紝鏈塖AP鍚堝悓缂栧彿鍜岃鍗曟棩 璇环鍋滄鍙戦�侀偖浠讹紙涓嶅啀瀵硅浠锋洿鏂拌繘琛屾鏌ヨ窡韪級
+            //鐜嬮箯浼� 缁撴潫 
+        }
+        updList.addAll(oppMap.values());
+        
+        if (updList.size() > 0){
+           /* StaticParameter.OppChangeopp = true;
+            StaticParameter.OppCanChangeOpp = true;
+            StaticParameter.temp = true;*/
+            for(Opportunity o : updList){
+                System.debug(o);
+            }
+            update updList;
+        }
+    }
+
+    public static void setQuote(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        /*if(StaticParameter.OrderTriggerIsUpdate){
+            //StaticParameter.OrderTriggerIsUpdate = false;
+            return;
+        }*/
+        List<Quote> updList = new List<Quote>();
+        List<Opportunity> updList2 = new List<Opportunity>();
+        for (Order newOrder : newList) {
+            Order oldOrder = oldMap.get(newOrder.Id);
+            if (newOrder.QuoteId != null &&
+                    (newOrder.ApproveStatus__c != oldOrder.ApproveStatus__c && newOrder.ApproveStatus__c == 'Reject' ||
+                     newOrder.ProductListApproveStatus__c != oldOrder.ProductListApproveStatus__c && newOrder.ProductListApproveStatus__c == 'Reject'
+                    )
+               ) {
+                Quote quo = new Quote(Id = newOrder.QuoteId, Is_Decided__c = false);
+                updList.add(quo);
+                Opportunity opp = new Opportunity(Id = newOrder.OpportunityId, Is_Decided__c = false);
+                updList2.add(opp);
+            }
+        }
+
+        if (updList.size() > 0) update updList;
+        if (updList2.size() > 0) update updList2;
+    }
+
+    public static void setTransferValue(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<String> oppidList = new List<String>();
+        List<String> quoidList = new List<String>();
+        Boolean updateOrderAccount = false;
+        Boolean hasBS = false;
+        Boolean sharedFlag = false;
+        for (Order target : newList) {
+            oppIdList.add(target.OpportunityId);
+            quoidList.add(target.QuoteId);
+            if(Trigger.isUpdate ){
+                Order old = oldMap.get(target.Id);
+                // 鍚堝悓瀹㈡埛鎴栨渶缁堢敤鎴峰彉鏇磋繘琛屾暟鎹獙璇�
+                if (old.AccountId != target.AccountId || old.EndUserD__c != target.EndUserD__c) {
+                    updateOrderAccount = true; 
+                }
+                if (target.SharedFlag__c && !old.SharedFlag__c) {
+                    sharedFlag = true;
+                }
+            } else if (Trigger.isInsert) {
+                updateOrderAccount = true;
+            } 
+        }
+
+       
+
+        Map<String,String> oppAccountMap = new Map<String,String>();
+        Map<String, Opportunity> oppMap = new Map<String, Opportunity>();
+        List<Opportunity> oppList = [select id, Amount, Quote_Discount__c, Quote_Subtotal__c, Quote_PaymentTerms_Text__c, Quote_Warranty__c, ProductSegment__c,
+                                     Quote_CustomPrice__c, Quote_ShipmentTerm__c, Quote_ShipmentTerm2__c, Quote_TotalPrice__c, IE_local_cost__c,AccountId,
+                                     Account.MarketingStrategyCreated__c,Account.Province__c ,Account.Sub_Use__c ,Account.AreaForIEApproveText__c ,
+                                     Account.serviceCreate__c ,Account.ProvinceStr__c 
+                                     from Opportunity where id = :oppidList];
+        for (Opportunity opp : oppList) {
+            oppMap.put(opp.id, opp);
+            oppAccountMap.put(opp.Id,opp.AccountId);
+            if (opp.ProductSegment__c == 'BS') {
+                hasBS = true;
+            }
+        }
+        if (updateOrderAccount) {
+            // WLIG-C3M68P XHL 20210607 Start
+            // 鏂板缓涓庡彉鏇村悎鍚屽鎴枫�佹渶缁堢敤鎴锋椂,鍜岃浠峰姣斿鎴枫�佹渶缁堢敤鎴凤紝鑻ヤ笉鐩稿悓鐩存帴鎶ラ敊鎻愰啋
+            CustomerConsistency(oppidList,oppAccountMap,newList);
+            // WLIG-C3M68P XHL 20210607 End
+        }
+        Map<String, Quote> quoMap = new Map<String, Quote>();
+        if (hasBS) {
+            List<Quote> quoList = [select id, Discount, Subtotal, Warranty__c, Custom_Price_Total_Text__c, Shipment_Term__c, Shipment_Term2__c, TotalPrice from Quote where id = :quoidList];
+            for (Quote quo : quoList) {
+                quoMap.put(quo.id, quo);
+            }
+        }
+        for (Order target : newList) {
+            Opportunity opp = oppMap.get(target.OpportunityId);
+            Quote quo = quoMap.get(target.QuoteId);
+            if (opp != null) {
+                target.MarketingStrategyCreated__c = opp.Account.MarketingStrategyCreated__c ;//甯傚満鎴樼暐閮ㄥ垱寤�(瀹㈡埛)
+                target.Province_acc__c = opp.Account.Province__c ;//鐪�(瀹㈡埛)
+                target.Sub_Use__c = opp.Account.Sub_Use__c ;//Sub Use(瀹㈡埛)
+                target.AreaForIEApproveText__c = opp.Account.AreaForIEApproveText__c ;//鍦板尯(IE瀹℃壒鏂囨湰)
+                target.serviceCreate__c = opp.Account.serviceCreate__c ;//鏄惁鏈嶅姟閮ㄥ垱寤�(瀹㈡埛)
+                target.ProvinceStr__c = opp.Account.ProvinceStr__c ;//鐪佷唤鏂囨湰(瀹㈡埛)    
+            }
+            
+            if (target.Status__c != 'Active') {
+                continue;
+            }
+
+            if (quo != null) {
+                target.Discount_D__c = quo.Discount;
+                //target.Olympus_Price_BeforeDiscount_D__c = quo.Subtotal;
+                target.Olympus_Price_BeforeDiscount_D__c = opp.Quote_Subtotal__c;
+                target.PaymentCondition_D__c = opp.Quote_PaymentTerms_Text__c;
+                Decimal warranty = quo.Warranty__c;
+                target.SpecialWarranty_D__c = warranty == null ? '' : warranty.format();
+                target.CustomerContractPriceD__c = opp.Quote_CustomPrice__c == null ? 0 : opp.Quote_CustomPrice__c;
+                target.Shipment_Term_D__c = quo.Shipment_Term__c;
+                target.Shipment_Term2_D__c = quo.Shipment_Term2__c;
+                //Decimal totalPrice = opp.Amount;
+                Decimal totalPrice = opp.Quote_TotalPrice__c;
+                if (target.ProductSegment__c == 'BS' && target.TradeType__c == System.Label.Trade_Type) {
+                    target.OlympusContractPricesD__c = totalPrice.setScale(2, System.RoundingMode.HALF_UP);
+                } else {
+                    target.OlympusContractPricesD__c = totalPrice.setScale(0, System.RoundingMode.HALF_UP);
+                }
+                //target.OlympusContractPrices__c = target.OlympusContractPricesD__c;
+            } else if (target.ProductSegment__c == 'IE' || target.ProductSegment__c == 'RVI' || target.ProductSegment__c == 'NDT' || target.ProductSegment__c == 'ANI') {
+                target.Discount_D__c = opp.Quote_Discount__c;
+                target.Olympus_Price_BeforeDiscount_D__c = opp.Quote_Subtotal__c;
+                target.PaymentCondition_D__c = opp.Quote_PaymentTerms_Text__c;
+                Decimal warranty = opp.Quote_Warranty__c;
+                target.SpecialWarranty_D__c = warranty == null ? '' : warranty.format();
+                target.CustomerContractPriceD__c = opp.Quote_CustomPrice__c == null ? 0 : opp.Quote_CustomPrice__c;
+                target.Shipment_Term_D__c = opp.Quote_ShipmentTerm__c;
+                target.Shipment_Term2_D__c = opp.Quote_ShipmentTerm2__c;
+                Decimal totalPrice = opp.Quote_TotalPrice__c;
+                if (target.ProductSegment__c != 'NDT' && target.ProductSegment__c != 'ANI') {
+                    target.OlympusContractPricesD__c = totalPrice.setScale(0, System.RoundingMode.HALF_UP);
+                } else {
+                    target.OlympusContractPricesD__c = totalPrice;
+                }
+                //target.OlympusContractPrices__c = target.OlympusContractPricesD__c;
+                target.Cost_D__c = opp.IE_local_cost__c;
+            } else if (target.ProductSegment__c == 'BS' && target.TradeType__c == System.Label.Trade_Type) {
+                Decimal totalPrice = opp.Quote_TotalPrice__c;
+                target.OlympusContractPricesD__c = totalPrice.setScale(2, System.RoundingMode.HALF_UP);
+            }
+        }
+    }
+
+    // Add by hanchao 201708101 for opportunity cancel lost control
+    public static void Cancellostcontrol(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        /*if(StaticParameter.OrderTriggerIsUpdate){
+            //StaticParameter.OrderTriggerIsUpdate = false;
+            return;
+        }*/
+        List<Opportunity> updList = new List<Opportunity>();
+        Map<String, Opportunity> updMap = new Map<String, Opportunity>();
+        for (Order newOrd : newList) {
+            Order oldOrd = oldMap == null ? new Order() : oldMap.get(newOrd.Id);
+            if (newOrd.Status__c != oldOrd.Status__c) {
+                if (updMap.containsKey(newOrd.OpportunityId) == false) {
+                    updMap.put(newOrd.OpportunityId, new Opportunity(Id = newOrd.OpportunityId, ActiveContract__c = false));
+                }
+                Opportunity opp = updMap.get(newOrd.OpportunityId);
+                if (newOrd.Status__c == 'Active') {
+                    opp.ActiveContract__c = true;
+                }
+            }
+        }
+
+        updList = updMap.values();
+        if (updList.size() > 0) update updList;
+    }
+
+    // Add by hanchao 201708102 for opportunity automatically close
+    public static void OppAutoClose(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        /*if(StaticParameter.OrderTriggerIsUpdate){
+            //StaticParameter.OrderTriggerIsUpdate = false;
+            return;
+        }*/
+        List<Opportunity> updList = new List<Opportunity>();
+        Map<String, String> updMap = new Map<String, String>();
+        for (Order newOrd : newList) {
+            Order oldOrd = oldMap == null ? new Order() : oldMap.get(newOrd.Id);
+            if (newOrd.AllDelivery__c >= 1 && newOrd.AllDelivery__c != oldOrd.AllDelivery__c && updMap.containsKey(newOrd.OpportunityId) == false) {
+                updMap.put(newOrd.OpportunityId, newOrd.OpportunityId);
+                Opportunity opp = new Opportunity();
+                opp.Id = newOrd.OpportunityId;
+                opp.StageName = 'Closed Won';
+                updList.add(opp);
+            }
+        }
+        if (updList.size() > 0) update updList;
+    }
+
+    // Add by hanchao 20181210 for productconfigchange
+    /*public static void Productconfigchange(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        List<Order> updList = new List<Order>();
+        Map<String, String> updMap = new Map<String, String>();
+        for (Order newOrd : newList){
+            Order oldOrd = oldMap == null ? new Order() : oldMap.get(newOrd.Id);
+            if (newOrd.ProductConfig_D__c != oldOrd.ProductConfig_D__c && oldOrd.ProductConfig_D__c != null) {
+                Order ord1 = new Order();
+                ord1.Id = newOrd.Id;
+                ord1.ProductConfig_IsChanged__c = true;
+                updList.add(ord1);
+            }
+        }
+        if (updList.size() > 0) update updList;
+    }*/
+
+
+    public static void setRecordTypeHidden(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        system.debug('set hidden type');
+        List<String> odrIds = new List<String>();
+        for (Order odr : newList) {
+            Order oldOrd = oldMap == null ? new Order() : oldMap.get(odr.Id);
+            if (odr.RecordTypeId != oldOrd.RecordTypeId &&
+                    (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_Approval ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_Approval ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_kua ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_Approval_kua ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_kua ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_Approval_kua )) {
+                odrIds.add(odr.Id);
+            }
+        }
+        system.debug('111111+' + odrIds.size());
+        if (odrIds.size() == 0) return;
+
+        Map<String, boolean> hiddenFlagMap = new Map<String, boolean>();
+        List<OrderItem> oiList = [select id, OrderId, PricebookEntry.Hidden_flag__c from OrderItem where OrderId = :odrIds order by OrderId];
+        for (OrderItem oi : oiList) {
+            if (hiddenFlagMap.containsKey(oi.OrderId) == false) {
+                hiddenFlagMap.put(oi.OrderId, false);
+            }
+            if (oi.PricebookEntry.Hidden_flag__c == true) {
+                hiddenFlagMap.put(oi.OrderId, true);
+            }
+        }
+        for(Order o : newList){
+            if(StaticParameter.specialDealerMap.containsKey(o.DealerId__c.subString(0,15))){
+                hiddenFlagMap.put(o.Id, true);
+            }
+        }
+        
+        system.debug('hiddenFlagMap'+hiddenFlagMap);
+        for (Order odr : newList) {
+            Order oldOrd = oldMap == null ? new Order() : oldMap.get(odr.Id);
+            system.debug(odr.RecordTypeId + '@@@' + oldOrd.RecordTypeId);
+            system.debug(odr.CrossCooperativeProject__c + '!!!!!' + hiddenFlagMap.get(odr.Id));
+            //濡傛灉鍚堝悓鐨勮褰曠被鍨嬫槸LS鐩稿叧鐨勮褰曠被鍨嬶紝闇�瑕佹牴鎹殣钘忔爣璁扮‘璁ゆ槸鍚︿慨鏀逛负瀵瑰簲鐨勮褰曠被鍨�
+            if (odr.RecordTypeId != oldOrd.RecordTypeId &&
+                    (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_Approval ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax ||
+                     odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_Approval)) {
+                if (hiddenFlagMap.get(odr.Id) == true) {
+                    if (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax) {
+                        if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_hidden_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_hidden;
+                        }
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_Approval) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_Approval_hidden_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_Approval_hidden;
+                        }
+                       
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_hidden_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_hidden;
+                        }
+                        
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_Approval) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_hidden_Approval_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_hidden_Approval;
+                        }
+                        
+                    }
+                } else if (hiddenFlagMap.get(odr.Id) == false) {
+                    if (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_hidden) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax;
+                        }
+                        
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_Approval_hidden) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_Approval_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_Approval;
+                        }
+                        
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_hidden) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax;
+                        }
+                        
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_hidden_Approval) {
+                        if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_Approval_kua;
+                        }else{
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_hidden;
+                        }   
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax) {
+                        if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_kua;
+                        }
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_Tax_Approval) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_Approval_kua;
+                        }
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_kua;
+                        }
+                    } else if (odr.RecordTypeId == System.Label.RT_Contract_BS_WithoutTax_Approval) {
+                         if(odr.CrossCooperativeProject__c == true){
+                            odr.RecordTypeId = System.Label.RT_Contract_BS_WithoutTax_Approval_kua;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    public static void setfile(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap) {
+        if (newList[0].ProductSegment__c == 'BS') {
+
+            String targetlist4 = newList[0].QuoteId;
+            String ordId = newList[0].Id;
+
+            Map<String, List<DecideQuoteProductSet__c>> dqpMap = new Map<String, List<DecideQuoteProductSet__c>>();
+            List<DecideQuoteProductSet__c> dqpList = new List<DecideQuoteProductSet__c>();
+            dqpList = [select id, DecideOpportunity__c, DecideQuote__c from DecideQuoteProductSet__c  where DecideQuote__c = :targetlist4];
+            system.debug('090909' + dqpList);
+            for (DecideQuoteProductSet__c dqp : dqpList) {
+                if (dqpMap.containsKey(dqp.DecideQuote__c)) {
+                    dqpMap.get(dqp.DecideQuote__c).add(dqp);
+                } else {
+                    dqpMap.put(dqp.DecideQuote__c, new List<DecideQuoteProductSet__c>());
+                    dqpMap.get(dqp.DecideQuote__c).add(dqp);
+                }
+            }
+            system.debug('123123000' + dqpMap);
+            List<DecideQuoteProductSet__c> updateList = new List<DecideQuoteProductSet__c>();
+            if (dqpMap.size() > 0 && dqpMap.containsKey(targetlist4)) {
+                // DecideQuoteProductSet__c temp = dqpMap.get(o.OpportunityId);
+                for (DecideQuoteProductSet__c temp : dqpMap.get(targetlist4)) {
+                    temp.DecideOrder__c = ordId;
+                }
+                updateList.addAll(dqpMap.get(targetlist4));
+            }
+            if (updateList.size() > 0) update updateList;
+
+            List<order_Single_product__c> ospList = [select id from order_Single_product__c where Order__c = :ordId and OrderProduct__c = null];
+            if (ospList.size() > 0 ) {
+                delete ospList;
+            }
+        }
+
+
+    }
+    /**
+     * [radiation description]浜у搧杈愬皠
+     * @param newList    [description]
+     * @param newMap     [description]
+     * @param oldList    [description]
+     * @param oldMap     [description]
+     * @param updateFlag [description]
+     */
+    public static void radiation(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap, Boolean updateFlag) {
+        for (Order newOrd : newList) {
+
+            if ( newOrd.ProductSegment__c == 'ANI' && newOrd.TradeType__c == '鍐呰锤' && newOrd.BusMagDepRev_F__c) { 
+
+                String orderFounder = newOrd.CreatedById;
+                if ( updateFlag) {
+                    // 鍚堝悓鍙樻洿
+                    Order oldOrd = oldMap.get(newOrd.Id);
+                    // 瀹℃壒鐘舵��
+                    Boolean approveStatus = newOrd.ApproveStatus__c != oldOrd.ApproveStatus__c;
+                    if (newOrd.ApproveStatus__c == 'OrderPass') {
+
+                        // 鐘舵��
+                        Boolean status = newOrd.Status__c != oldOrd.Status__c && newOrd.Status__c == 'Inactive';
+
+                        // 鍚堝悓-鍙樻洿鐢宠-鍘熷悎鍚屾棤鏁堟垨鑰呮墜鍔ㄤ慨鏀瑰鑷村悎鍚屾棤鏁�
+                        if (!approveStatus && status) {
+                            RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, true,'鏃犳晥鎴栧彉鏇存棤鏁�',newOrd.LastModifiedById );
+                        }
+
+                        if (oldOrd.ApproveStatus__c == 'OrderDraft') {
+                            // WLIG-C3LA29 XHL Start
+                           //鍚堝悓-鍙樻洿鐢宠-鏂板鍚堝悓淇敼鍐呭鈫掕鍗曡崏妗堚啋璁㈠崟鎵瑰噯
+                           RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, false,'鍚堝悓鑽夋涓彉鎵瑰噯',newOrd.LastModifiedById );
+                           // WLIG-C3LA29 XHL End
+                        }
+
+                    } else if ( oldOrd.ApproveStatus__c == 'OrderPass') {
+                        // 鍚堝悓-鍙樻洿鐢宠-鏂板鍚堝悓淇敼鍐呭鈫掕鍗曟壒鍑嗏啋璁㈠崟鑽夋
+                        if (newOrd.ApproveStatus__c == 'OrderDraft' &&  newOrd.Status__c == 'Active') {
+
+                            if (RadiationUtil.EscapeOrderTriggerHandler) {
+                                RadiationUtil.EscapeOrderTriggerHandler = false;
+                                RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, true,'鍚堝悓鍙樻洿鑽夋涓�',newOrd.LastModifiedById );
+
+                            }
+                        }
+                    } else if (newOrd.ApproveStatus__c == 'OrderSubmit' && newOrd.Status__c == 'Active') {
+                        // 鍚堝悓鎻愪氦
+                        if ( approveStatus ) {
+                            RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, false,'鍚堝悓鎻愪氦',newOrd.LastModifiedById );
+                        }
+                    } else if (newOrd.ApproveStatus__c == 'OrderSubmit' ) {
+                        Boolean status = newOrd.Status__c != oldOrd.Status__c && newOrd.Status__c == 'Inactive';
+                        // 鍚堝悓鎻愪氦鐘舵�佸彉鎴愭棤鏁�
+                        if ( status ) {
+                            RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, true,'鍚堝悓鎻愪氦鍙樻棤鏁�',newOrd.LastModifiedById );
+                        }
+                    } else if (newOrd.ApproveStatus__c == 'CancelPass' && newOrd.Status__c == 'Active') {
+                        // 鍚堝悓-鍚堝悓鎵瑰噯鈫掆啋鈫掑悎鍚屽彇娑�
+                        if ( approveStatus && newOrd.BeforeSubmitStatus__c == 'OrderPass') {
+
+                            RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, true,'鍚堝悓鍙栨秷',newOrd.LastModifiedById );
+                        }
+
+                    } else if (oldOrd.ApproveStatus__c == 'OrderSubmit' && newOrd.ApproveStatus__c == 'OrderReject' && newOrd.Status__c == 'Active') {
+                        // 鍚堝悓鎻愪氦鈫掆啋鈫掑悎鍚岄┏鍥�
+                        RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, true,'鍚堝悓椹冲洖',newOrd.LastModifiedById );
+                    } else if (oldOrd.ApproveStatus__c == 'OrderSubmit' && newOrd.ApproveStatus__c == 'OrderDraft' && newOrd.Status__c == 'Active') {
+                        // 鍚堝悓鎻愪氦鈫掆啋鈫掑悎鍚岃皟鍥�
+                        RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, true,'鍚堝悓璋冨洖',newOrd.LastModifiedById );
+                    }
+                   
+                } else {
+                    //  鍚堝悓鏂板-鍘熷悎鍚屽彉鏇寸敵璇峰鎵瑰悗鍏嬮殕鍑烘潵鐨勫悎鍚�
+                    if (newOrd.ApproveStatus__c == 'OrderPass' &&
+                            newOrd.Status__c == 'Active' &&
+                            !newOrd.Is_Already_Splited__c) {
+                        RadiationUtil.updateRadiationTypeQuantity(newOrd.Id,orderFounder , newOrd.DealerId__c, false,'鍚堝悓鍙樻洿鏂板',newOrd.LastModifiedById );
+                    }
+                }
+
+            }
+
+        }
+    }
+
+    //鐜嬮箯浼熸柊寤烘柟娉� 鍚堝悓鏄疘E锛�3.COMPO鍕鹃�夛紝鏇存柊瀵瑰簲璇环condition__c瀛楁 containsKey
+    public static void setOpportunityCOMPO(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap , Boolean temp){
+        // ProductSegment__c
+           /* List<String> oppId = new List<String>();
+            for(Order o:newList){
+                oppId.add(o.OpportunityId);
+            }*/
+            System.debug('鏂板缓鍚堝悓鏇存柊璇环 COMPO');
+            List<Opportunity> oppList = new List<Opportunity>();
+            //List<Opportunity> oppNewList = new List<Opportunity>();
+            //oppList = [select Id,condition__c from Opportunity where Id=:oppId];
+            for(Order o:newList){
+                Order old = new Order();
+                if(!temp){
+                    old = oldMap.get(o.Id);
+                }
+                if (o.ProductSegment__c == 'BS' && temp) {
+                    Opportunity opp1 = new Opportunity();
+                    opp1.Id = o.OpportunityId;
+                    opp1.SubDealer__c = o.SubDealer__c;
+                    oppList.add(opp1);
+                }
+                if(o.ProductSegment__c=='IE' && o.Status__c == 'Active' && ( temp || ( !temp && o.IE_SP8_D__c != old.IE_SP8_D__c ))){
+                    Opportunity opp = new Opportunity();
+                    opp.Id = o.OpportunityId;
+                    if(o.IE_SP8_D__c){
+                        opp.condition__c = 'Y';
+                    }else{
+                        opp.condition__c = '';
+                    }
+                    oppList.add(opp);
+                    /*for(Opportunity opp : oppList){
+                        if (o.OpportunityId == opp.Id) {
+                            opp.condition__c = '3.COMPO';
+                            oppNewList.add(opp);
+                            break;
+                        }
+                    }*/
+                }
+            }
+            StaticParameter.OpportunityTriggerIsUpdate = true;
+            if(oppList.size()>0) update oppList;
+    }
+    
+    public static void updateOpportunity(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap, Boolean updateFlag){
+        Map<String,Opportunity> updateOpportunityMap = new  Map<String,Opportunity>();
+        for (Order newOrd : newList) {
+
+            String opportunityId = newOrd.OpportunityId;
+            Opportunity updateOpportunity = new Opportunity();
+            updateOpportunity.Id = opportunityId;
+            if (updateOpportunityMap.containsKey(opportunityId)) {
+                updateOpportunity = updateOpportunityMap.get(opportunityId);
+            }
+
+            if (updateFlag) {// 鍚堝悓鏇存柊
+                // 鑾峰彇鍘熷悎鍚�
+                Order oldOrd = oldMap.get(newOrd.Id);
+                // 鍚堝悓 鏃犳晥--->鏈夋晥
+                if (oldOrd.Status__c != newOrd.Status__c && 'Active'.equals(newOrd.Status__c)) {
+                    // 鏇存柊鏈夋晥鍚堝悓
+                    updateOpportunity.ActiveOrder__c =  newOrd.Id; 
+                    updateOpportunityMap.put(opportunityId,updateOpportunity);      
+                }  
+                // 鍚堝悓 鏈夋晥--->鏃犳晥
+                if (String.isNotBlank(oldOrd.Status__c) && oldOrd.Status__c != newOrd.Status__c && 'Inactive'.equals(newOrd.Status__c)) {
+                    // 鍒ゆ柇 鏈夋晥鍚堝悓瀛楁 鏄惁鏈夊�� 鏈夊�间笉鏇存柊 
+                    if (updateOpportunity.ActiveOrder__c == null) {
+                        updateOpportunity.ActiveOrder__c = null;
+                        updateOpportunityMap.put(opportunityId,updateOpportunity);
+                    }
+                      
+                }  
+                 
+            } else {//鍚堝悓鏂板
+
+                if ('Active'.equals(newOrd.Status__c)) {// 鍚堝悓鏈夋晥
+                    updateOpportunity.ActiveOrder__c =  newOrd.Id;
+                    updateOpportunityMap.put(opportunityId,updateOpportunity);
+                }
+            }
+        }
+        // test(null,null,newList,oldMap);
+        if (updateOpportunityMap != null && updateOpportunityMap.size() > 0) {
+            StaticParameter.OpportunityTriggerIsUpdate = true;
+            StaticParameter.StageProgressBarUpdate = true;
+            update updateOpportunityMap.values();
+        }
+
+    }
+    
+    
+    public static void CustomerConsistency(List<String> oppidList,Map<String,String> oppAccountMap,List<Order> newList){
+        // 鑾峰彇璇环鐨勬渶缁堢敤鎴�
+        List<OpportunityContactRole> role_list = new List<OpportunityContactRole>();
+        role_list = [select Id,Role,IsPrimary,OpportunityId,ContactId from OpportunityContactRole where OpportunityId = :oppidList and Role  = 'End user' and IsPrimary = true];
+        Map<String,String> roleMap = new Map<String,String>();
+        for(OpportunityContactRole oppor:role_list){
+            roleMap.put(oppor.OpportunityId,oppor.ContactId);
+        }
+        // 鑾峰彇绯荤粺绠$悊鍛業d
+        String getUserId = System.label.SystemAdmin1_2_GPI;
+        String errMessage = '瀹㈡埛鍚嶆垨鏈�缁堢敤鎴蜂笌璇环涓嶄竴鑷达紒';
+        for(Order orOne:newList){
+            if (oppAccountMap.containsKey(orOne.OpportunityId)) {
+                if(oppAccountMap.get(orOne.OpportunityId) != orOne.AccountId || !roleMap.containsKey(orOne.OpportunityId) || orOne.EndUserD__c != roleMap.get(orOne.OpportunityId)){
+                    // 鑾峰彇鐢ㄦ埛Id
+                    String userId = UserInfo.getUserId().subString(0,15);
+                    if (String.isNotBlank(getUserId)) {
+                        if (getUserId.contains(userId)) {
+                            if (String.isNotBlank(orOne.Id)) {
+                                throw new ControllerUtil.myException('鍚堝悓Id:'+orOne.Id+'_'+errMessage);    
+                            } else {
+                                //璁㈠崟ID娌℃湁鍙栧埌
+                                orOne.addError(errMessage);
+                            }
+                        } else {
+                            //鑷畾涔夋爣绛鹃噷闈㈡病鏈夊綋鍓嶇敤鎴风殑ID
+                            orOne.addError(errMessage);
+                        }
+
+                    } else {
+                        //鑷畾涔夋爣绛炬病鏈夊唴瀹�
+                        orOne.addError(errMessage);
+                    }
+                    
+                    
+                }
+            }
+        }
+
+    }
+
+    //妫�鏌ュ悎鍚屼笂鐨勭瓑绾х被鍒槸浜岀被锛屼竴绫伙紝闈炵洃绠�(绛夌骇鐢遍珮鍒板簳)锛屽崟鐙竴鏉¤褰曢噷闈㈢殑鎵�鏈変骇鍝侊紝鏀惧埌涓�涓猯ist閲岄潰銆�
+    //鏍规嵁璁㈠崟涓婄殑琛屼骇鍝佺殑瀵瑰簲鐨勪骇鍝佽〃閲岀殑绛夌骇绫诲埆瀛楁锛岀粰璁㈠崟涓婄殑绛夌骇绫诲埆瀛楁璧嬪��,newList涓洪渶瑕佸垽鏂殑浼犳潵鐨勫悎鍚岀殑Id銆�
+    //浜у搧閲岀殑绛夌骇绫诲埆瀛楁锛岃祴鍊肩粰璁㈠崟琛岄」鐩殑 浜у搧鐨勭瓑绾х被鍒瓧娈点��
+    public static Map<Id,String> levelCheck(List<String> newList){
+        //瀹氫箟涓狶ist锛屽瓨鏀緎oql鏂�
+        List<OrderItem> orditemList = new List<OrderItem>();
+        orditemList = [select OrderId,Pro_Level__c from OrderItem where Pro_Level__c <> null and OrderId in : newList];
+
+        //瀹氫箟map锛屽瓨鏀捐鍗旾D,鍜屼笂闈㈢殑鎻愬埌鐨凩ist
+        Map<Id,List<String>> orditemMap = new Map<id,List<String>>();
+
+        //杩欎釜Map瀛樻斁(Id,绛夌骇绫诲埆鐨勫��)
+        Map<Id,String> orderXMap = new  Map<Id,String>();
+
+        //缁橫ap閲岄潰鏀惧叆璁㈠崟ID,浠ヨ鍗旾D锛屽瓨鏀捐鍗曚笅闈㈢殑鎵�鏈変骇鍝佺殑绛夌骇绫诲埆鐨勫瓧娈电殑鍊�
+        if (orditemList.size()>0) {
+            for (OrderItem orditem: orditemList) {
+                if (orditemMap.containsKey(orditem.OrderId)) {
+                    orditemMap.get(orditem.OrderId).add(orditem.Pro_Level__c);
+                }else{
+                    orditemMap.put(orditem.OrderId, new List<String>());
+                    orditemMap.get(orditem.OrderId).add(orditem.Pro_Level__c);
+                }
+            }
+        }
+
+        //寮�濮嬮�昏緫鍒ゆ柇锛岃鍗曚骇鍝佸搴旂殑浜у搧鐨勭瓑绾х被鍒彧瑕佹湁涓�绫伙紝璁㈠崟涓婄殑绛夌骇绫诲埆璧嬪�间竴绫�(涓�绫�>浜岀被>闈炵洃绠★紝渚濇绫绘帹)
+        for (String oe : newList) {
+            if (orditemMap.containsKey(oe)) {
+                if (orditemMap.get(oe).contains('浜岀被')) {
+                    orderXMap.put(oe, '浜岀被');
+                }else if (orditemMap.get(oe).contains('涓�绫�')) {
+                    orderXMap.put(oe, '涓�绫�');
+                }else{
+                    orderXMap.put(oe, '闈炵洃绠�');
+                }
+            }else{
+                orderXMap.put(oe, '闈炵洃绠�');
+            }
+        }
+        //鏈�鍚庤繑鍥炰竴涓狹ap鏂逛究鍒殑鏂规硶璋冪敤
+        return orderXMap;
+    }
+
+
+     /**
+     * [鍒ゆ柇鍚堝悓鏄竴绫汇�佷簩绫昏繕鏄潪鐩戠]
+     * @param  idList [闇�瑕佸垽鏂殑鍚堝悓鐨処D]
+     * @return        [鍚堝悓ID鍜屽搴旂殑鍒嗙被]
+     */
+
+    /*
+    public static Map<String,String> CheckProductType (List<String> idList){
+        //杩斿洖鍙傛暟浣跨敤鐨勬暟鎹�
+        Map<String,String> returnMap = new Map<String,String>();
+        //鍙傛暟闈炵┖鍒ゆ柇
+        if(idList != null && idList.size() > 0){
+            //妫�绱㈠悎鍚屽搴旂殑浜у搧
+            List<OrderItem> oiList = new List<OrderItem>();
+            oiList = [SELECT id,OrderId,PricebookEntry.Product2.Product_ECCode__c FROM OrderItem WHERE OrderId in: idList];
+            //鍚堝悓ID鍜屽搴斿悎鍚屼骇鍝佺殑Map
+            Map<String,List<String>> orderMap = new Map<String,List<String>>();
+            for (OrderItem oi : oiList) {
+                //灏嗗悎鍚屼骇鍝佷簬瀵圭敤鐨勫悎鍚孖D鍏宠仈
+                if (orderMap.containsKey(oi.OrderId)) {
+                    orderMap.get(oi.OrderId).add(oi.PricebookEntry.Product2.Product_ECCode__c);
+                } else {
+                    orderMap.put(oi.OrderId, new List<String>());
+                    orderMap.get(oi.OrderId).add(oi.PricebookEntry.Product2.Product_ECCode__c);
+                }
+            }
+
+            //鍒ゆ柇鍚堝悓鏄竴绫汇�佷簩绫昏繕鏄潪鐩戠
+            //瀵瑰涓悎鍚屽垎鍒繘琛屽鐞�
+            for (String id : orderMap.keySet()) {
+                List<String> tempList = orderMap.get(id);
+
+                if(tempList.contains('浜岀被')){
+                    //濡傛灉鍖呭惈浜岀被锛岀洿鎺ユ爣璁颁负浜岀被骞惰繑鍥烇紱
+                    returnMap.put(id, '浜岀被');
+                }else if(tempList.contains('涓�绫�')){
+                    //濡傛灉鍖呭惈涓�绫伙紝灏嗘爣璁拌缃负涓�绫�
+                    returnMap.put(id, '涓�绫�');
+                }else{
+                    returnMap.put(id, '闈炵洃绠�');
+                }
+            }
+        }
+        return returnMap;
+    }
+    */
+   
+
+    
+    /**
+     * 妫�鏌ュ悎鍚屽鎵逛汉鏄惁濉啓瀹屾暣   
+     * @author Dai Y
+     * @date   2022-01-12
+     * @param  ordList    寰呮鏌ュ悎鍚孡ist
+     * @return            濉啓瀹屾暣杩斿洖true锛屼笉瀹屾暣杩斿洖false
+     */
+    private static Boolean CheckSalesOwner(List<Order> ordList){
+        Boolean flag = true;
+        for (Order order : ordList) {
+            //鍒ゆ柇鍚堝悓瀹℃壒浜烘槸鍚︿负绌猴紝
+            if(String.isBlank(order.SalesOwner_BS__c)){
+                //order.SalesOwner_BS__c.addError('璇峰~鍐欏鎵逛汉');
+                flag = false;
+            }
+        }
+        return flag;
+    }
+    /**
+     * 妫�鏌ヨ法鍖洪攢鍞浉鍏虫暟鎹槸鍚﹀~鍐欏畬鏁�
+     * @author Dai Y
+     * @date   2022-01-12
+     * @param  ordList    寰呮鏌ュ悎鍚孡ist
+     * @return            濉啓瀹屾暣杩斿洖true锛屼笉瀹屾暣杩斿洖false
+     */
+    
+    private static Boolean CheckCrossComperativeData(List<Order> ordList){
+        Boolean flag = true;
+        for (Order order : ordList) {
+            //鍒ゆ柇鍚堜綔鍖哄煙浠g悊鍟嗭紝涓讳唬鐞嗗晢鍜屽悎浣滃尯鍩熻礋璐d汉
+            if(String.isBlank(order.CrossCooperativeDealerText__c) || String.isBlank(order.HeadOfCooperationArea__c)  || false){
+                flag = false;
+            }
+        }
+        return flag;
+    }
+    /**
+     * 鍒ゆ柇AB浠g悊鍟嗘槸鍚︿慨鏀�
+     * @author Dai Y
+     * @date   2022-01-20
+     * @param  newOrd    淇敼鍚庡悎鍚�
+     * @param  oldOrd     淇敼鍓嶅悎鍚�
+     * @return            濡傛灉杩涜淇敼杩斿洖true锛屾病淇繃楗悗false
+     */
+    public static Boolean CherkCrossComperativeChanged(Order newOrd ,Order oldOrd){
+        Boolean flag = false;
+        if(newOrd.Dealer_A__c != oldOrd.Dealer_A__c || newOrd.Dealer_B__c != oldOrd.Dealer_B__c ){
+            flag = true;
+        }
+        return flag;
+    }
+
+    /**
+     * 蹇呭~閫夐」妫�鏌�
+     * @author Dai Y
+     * @date   2022-01-13
+     * @param  ordList    寰呮鏌ュ悎鍚孡ist
+     * @return            妫�鏌ラ�氳繃杩斿洖true锛屼笉閫氳繃杩斿洖false
+     */
+    private static Boolean Check(List<Order> ordList){
+        Boolean flag = true;
+
+
+        return flag;
+    }
+
+    public static void asd() {
+        Integer i = 1;
+        i++;
+        i++;
+        i++;    
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/OrderTriggerHandler.cls-meta.xml b/scr/classes/OrderTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/OrderTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderTriggerTest.cls b/scr/classes/OrderTriggerTest.cls
new file mode 100644
index 0000000..13c821d
--- /dev/null
+++ b/scr/classes/OrderTriggerTest.cls
@@ -0,0 +1,807 @@
+@isTest
+private class OrderTriggerTest {
+
+    // 鏃犵壒娈婃潯浠跺悎鍚�
+    static testMethod void myTest1() {
+        OrderTriggerHandler.asd();
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp;
+        
+        User user = new User();
+        user.LastName = 'test1';
+        user.FirstName = 'test2';
+        user.Alias = 'test3';
+        user.Email = 'test4@test.com';
+        user.Username = 'test11122@test222.com';
+        user.CommunityNickname = 'test22';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+
+        OpportunityTeamMember otm1 = new OpportunityTeamMember();
+        otm1.opportunityId = opp.Id;
+        otm1.userId = user.Id;
+        otm1.teamMemberRole = 'Sales Manager';
+        insert otm1;
+
+        //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        OrderItemTriggerHandler.tess();
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'IESalesContract'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = rectOdr[0].Id,
+            SpecialDeliveryAccount__c = accIE.Id,
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        // User user = new User();
+        // user.LastName = 'test1';
+        // user.FirstName = 'test2';
+        // user.Alias = 'test3';
+        // user.Email = 'test4@test.com';
+        // user.Username = 'test11122@test222.com';
+        // user.CommunityNickname = 'test22';
+        // user.IsActive = true;
+        // user.EmailEncodingKey = 'ISO-2022-JP';
+        // user.TimeZoneSidKey = 'Asia/Tokyo';
+        // user.LocaleSidKey = 'ja_JP';
+        // user.LanguageLocaleKey = 'ja';
+        // user.ProfileId = System.Label.SystemAdmin;
+        // insert user;
+
+        /*List<User> userList = [select id,SalesAsistManager__c from user where id =:UserInfo.getUserId()];
+        if (userList.size() > 0) {
+            userList[0].SalesAsistManager__c = user.Id;
+            update userList;
+        }*/
+
+        List<Order> orderList = [select id, ApproveStatus__c from Order where Id = :odr.Id];
+        //System.assertEquals('OrderDraft', orderList[0].ApproveStatus__c);
+
+        odr.ApproveStatus__c = 'Completed';
+        update odr;
+        odr.ApproveStatus__c = 'Submit';
+        update odr;
+        odr.ApproveStatus__c = 'OrderReject';
+        update odr;
+
+        List<Order> orderList2 = [select id, ApproveStatus__c from Order where Id = :odr.Id];
+        System.assertEquals('OrderReject', orderList2[0].ApproveStatus__c);
+
+        odr.ApproveStatus__c = 'Completed';
+        update odr;
+        odr.ApproveStatus__c = 'Submit';
+        update odr;
+        odr.ApproveStatus__c = 'OrderPass';
+        update odr;
+
+        List<Order> orderList3 = [select id, ApproveStatus__c from Order where Id = :odr.Id];
+        System.assertEquals('OrderPass', orderList3[0].ApproveStatus__c);
+    }
+
+    // 鏈夌壒娈婃潯浠跺悎鍚�
+    static testMethod void myTest2() {
+        OrderTriggerHandler.asd();
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp;
+
+        //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            IE_SP8__c = true,
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+        List<Order> orderList = [select id, ApproveStatus__c,ProductSegment__c,Status__c,IE_SP5_D__c,IE_SP6_D__c,IE_SP7_D__c,IE_SP8_D__c from Order where Id = :odr.Id];
+        System.debug('orderList--->'+orderList);
+        // System.assertEquals('Draft', orderList[0].ApproveStatus__c);
+
+        odr.ApproveStatus__c = 'Completed';
+        update odr;
+        odr.ApproveStatus__c = 'Submit';
+        update odr;
+        odr.ApproveStatus__c = 'Pass';
+        update odr;
+
+        List<Order> orderList2 = [select id, ApproveStatus__c from Order where Id = :odr.Id];
+        System.assertEquals('Pass', orderList2[0].ApproveStatus__c);
+
+        odr.ApproveStatus__c = 'Completed2';
+        update odr;
+        odr.ApproveStatus__c = 'OrderSubmit';
+        update odr;
+        odr.ApproveStatus__c = 'OrderPass';
+        update odr;
+
+        List<Order> orderList3 = [select id, ApproveStatus__c from Order where Id = :odr.Id];
+        System.assertEquals('OrderPass', orderList3[0].ApproveStatus__c);
+
+        odr.ApproveStatus__c = 'Completed2';
+        update odr;
+        odr.ApproveStatus__c = 'OrderSubmit';
+        update odr;
+        odr.ApproveStatus__c = 'OrderReject';
+        update odr;
+
+        List<Order> orderList4 = [select id, ApproveStatus__c from Order where Id = :odr.Id];
+        System.assertEquals('OrderReject', orderList4[0].ApproveStatus__c);
+    }
+
+    //
+    static testMethod void myTest3() {
+        OrderTriggerHandler.asd();
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            compo_opp__c = false
+        );
+        insert opp;
+        //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        odr.SP_11__c = true;
+        odr.SP_102__c = true;
+        odr.SP_103__c = true;
+        odr.SP_106__c = true;
+        odr.SP_111__c = true;
+        odr.SP_121__c = true;
+        odr.SP_131__c = true;
+        odr.SP_141__c = true;
+        odr.SP_151__c = true;
+        odr.SP_161__c = true;
+        odr.SP_171__c = true;
+        odr.SP_181__c = true;
+        odr.SP_191__c = true;
+        odr.SP_202__c = true;
+        odr.SP_21__c = true;
+        odr.SP_22__c = false;
+        odr.SP_31__c = true;
+        odr.SP_32__c = false;
+        odr.SP_33__c = false;
+        odr.SP_41__c = true;
+        odr.SP_51__c = true;
+        odr.SP_52__c = true;
+        odr.SP_62__c = true;
+        odr.SP_71__c = true;
+        odr.SP_81__c = true;
+        odr.SP_91__c = true;
+
+        odr.IE_SP1__c = true;
+        odr.IE_SP2__c = true;
+        odr.IE_SP3__c = true;
+        odr.IE_SP4__c = false;
+        odr.IE_SP5__c = true;
+        odr.IE_SP6__c = true;
+        odr.IE_SP7__c = true;
+
+        odr.RVI_SP1__c = true;
+        odr.RVI_SP2__c = false;
+        odr.RVI_SP3__c = true;
+        odr.RVI_SP4__c = true;
+        odr.RVI_SP5__c = true;
+        odr.RVI_SP6__c = true;
+
+        odr.NDT_SP1__c = true;
+        odr.NDT_SP2__c = true;
+        odr.NDT_SP3__c = true;
+        odr.NDT_SP4__c = true;
+        odr.NDT_SP5__c = true;
+        odr.NDT_SP6__c = true;
+        odr.NDT_SP7__c = true;
+        odr.NDT_SP8__c = true;
+        odr.NDT_SP9__c = true;
+        odr.NDT_SP10__c = true;
+        odr.NDT_SP11__c = true;
+
+        odr.ANI_SP1__c = true;
+        odr.ANI_SP2__c = true;
+        odr.ANI_SP3__c = true;
+        odr.ANI_SP4__c = true;
+        odr.ANI_SP5__c = true;
+        odr.ANI_SP6__c = true;
+
+        odr.NormalDis_SerContractCondition__c = true;
+        odr.HighDis_SerContractCondition__c = false;
+        odr.SpecialDis_SerContractCondition__c = false;
+        odr.Warranty_SerContractCondition__c = true;
+
+        odr.Discount__c = 0.5;
+        odr.Olympus_Price_BeforeDiscount__c = 2000;
+        odr.PaymentCondition__c = 'PaymentCondition__c';
+        odr.SpecialDelivery__c = 'SpecialDelivery__c';
+        odr.SpecialDeliveryContact__c = 'SpecialDeliveryContact__c';
+        odr.SpecialDeliveryPhone__c = '11223344';
+        odr.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress__c';
+        odr.SpecialParkage__c = 'SpecialParkage__c';
+        odr.SpecialWarranty__c = 'SpecialWarranty__c';
+        odr.DealerProfit__c = 0.4;
+        odr.SpecialDelDate__c = Date.today().addDays(1);
+        odr.OtherApply__c = 'OtherApply__c';
+
+        odr.CustomerContractPrice__c = 2000;
+        odr.OlympusContractPrices__c = 1000;
+        odr.EndUser__c = con.Id;
+
+        odr.Andor__c = true;
+        odr.Bitplane__c = true;
+        odr.CoolLED__c = true;
+        odr.Lumen__c = true;
+        odr.Lumenera__c = true;
+        odr.Media_Cybernetics__c = true;
+        odr.Narishige__c = true;
+        odr.Newport__c = true;
+        odr.OSIS_Germany__c = true;
+        odr.OSIS_Singapore__c = true;
+        odr.Photometrics__c = true;
+        odr.Prior_Scientific__c = true;
+        odr.Q_Imaging__c = true;
+        odr.Tokai_Hit__c = true;
+        odr.Other_Third__c = true;
+        odr.ServiceFee__c = 500;
+        odr.AlongProduct__c = '鏄�';
+        odr.Cost__c = 500;
+        odr.Sub_DealerC__c = '9878971';
+        odr.Shipment_Term__c = 'CIP';
+
+        odr.Contract_Status__c = 'Active';
+
+        update odr;
+    }
+
+    static testMethod void myTest4() {
+        OrderTriggerHandler.asd();
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        //List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        //List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+
+        //Account buyer = new Account(
+        //    Name = '*',
+        //    FacilityName__c = 'buyer',
+        //    PostCode__c = '123456',
+        //    DivisionName__c='Dealer',
+        //    OwnerId = UserInfo.getUserId(),
+        //    RecordTypeId = rectDealer[0].Id,
+        //    ProductSegment__c = 'BS',
+        //    ManagementCode_Ext__c = 'P11111'
+        //    //ProductSegment__c = 'BS'
+        //);
+        //Account delivery = new Account(
+        //    Name = '*',
+        //    FacilityName__c = 'delivery',
+        //    PostCode__c = '123456'
+        //);
+        //Account user = new Account(
+        //    Name = '*',
+        //    FacilityName__c = 'user',
+        //    PostCode__c = '123456',
+        //    RecordTypeId = rectIE[0].Id
+        //);
+        //insert new List<Account> {buyer, delivery, user};
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account dealerParent = new Account();
+        dealerParent.Name = 'test dealer';
+        dealerParent.RecordTypeId = rectDealer[0].Id;
+        dealerParent.ProductSegment__c = 'BS';
+        dealerParent.PostCode__c='000000';
+        dealerParent.ManagementCode_Ext__c = 'P11111';
+        insert dealerParent;
+
+        Account dealer1 = new Account();
+        dealer1.Name = 'test dealer';
+        dealer1.RecordTypeId = rectDealer[0].Id;
+        dealer1.ProductSegment__c = 'BS';
+        dealer1.PostCode__c='000000';
+        dealer1.ManagementCode_Ext__c = 'C22222';
+        dealer1.ParentId = dealerParent.Id;
+        insert dealer1;
+
+        Account dealer2 = new Account();
+        dealer2.Name = 'test dealer';
+        dealer2.RecordTypeId = rectDealer[0].Id;
+        dealer2.ProductSegment__c = 'BS';
+        dealer2.PostCode__c='000000';
+        dealer2.ManagementCode_Ext__c = 'C33333';
+        dealer2.ParentId = dealerParent.Id;
+        insert dealer2;
+
+        Account accBS = new Account(
+            Name = '*',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accBS;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accBS.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accBS.Id,
+            useing__c = 'OEM',
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Dealer__c = dealer1.Id,
+            Machine_Parts__c = 'Machine',
+            InquiryResult__c = '112233'
+        );
+        insert opp;
+
+        //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accBS.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            SP_61D__c = true,
+            SpecialDeliveryAccount_D__c = accBS.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        OrderItem oi1 = new OrderItem(
+            OrderId = odr.Id,
+            PriceBookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oi1;
+
+        /*Opportunity opp1 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        System.assertEquals(null, opp1.Order_Date__c);
+        System.assertEquals(null, opp1.DeliveryDate__c);
+
+        odr.OrderDate__c = Date.today();
+        update odr;*/
+
+        Delivery__c delivery1 = new Delivery__c(
+            SSBD_Contract__c = odr.Id,
+            Delivery_Date__c = Date.today().addDays(-1),
+            Delivery_Status__c = '鏈彂璐�'
+        );
+        insert delivery1;
+
+        Opportunity opp2 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        //System.assertEquals(Date.today(), opp2.Order_Date__c);
+        System.assertEquals(null, opp2.DeliveryDate__c);
+
+        Delivery__c delivery2 = new Delivery__c(
+            SSBD_Contract__c = odr.Id,
+            Delivery_Date__c = Date.today(),
+            Delivery_Status__c = '閮ㄥ垎鍙戣揣'
+        );
+        insert delivery2;
+
+        Opportunity opp3 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        System.assertEquals(null, opp3.DeliveryDate__c);
+
+        Delivery__c delivery3 = new Delivery__c(
+            SSBD_Contract__c = odr.Id,
+            Delivery_Date__c = Date.today().addDays(1),
+            Delivery_Status__c = '鍏ㄩ儴鍙戣揣'
+        );
+        insert delivery3;
+
+        /*Opportunity opp4 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        //System.assertEquals(Date.today().addDays(1), opp4.DeliveryDate__c);
+
+        odr.RecordTypeId = System.Label.RT_Contract_BS_Tax_Approval;
+        update odr;*/
+    }
+    static testMethod void myTest5(){
+        OrderTriggerHandler.asd();
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'ANI',
+            ProductSegment__c = 'ANI',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectANI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectANI[0].Id
+        );
+        insert user;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert contact;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'ANI',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+         //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = contact.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10
+        );
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20
+        );
+        insert new OpportunityLineItem[] {oli1, oli2};
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli1 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10,
+            Custom_Price__c = 15,
+            Set__c = 'set01'
+        );
+        QuoteLineItem qli2 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20,
+            Custom_Price__c = 25,
+            Set__c = 'set01'
+        );
+        insert new QuoteLineItem[] {qli1, qli2};
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            QuoteId = quo.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            EndUser__c = contact.Id
+        );
+        insert order;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderTriggerTest.cls-meta.xml b/scr/classes/OrderTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..b12420e
--- /dev/null
+++ b/scr/classes/OrderTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>31.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderWebService.cls b/scr/classes/OrderWebService.cls
new file mode 100644
index 0000000..be3d31b
--- /dev/null
+++ b/scr/classes/OrderWebService.cls
@@ -0,0 +1,3224 @@
+global class OrderWebService {
+
+    WebService static String checkproduct(String oppid){
+        List<OpportunityLineItem> qliList= [select id,Product2.NMPAStatus__c,Product2.ProductCode,OppliOrderIsChange__c,oppLiVerifyProductValid__c from OpportunityLineItem where opportunityId = :oppId];
+        String str = '';
+        Boolean isok = true;
+        for(OpportunityLineItem qli : qliList){
+            // WLIG-BTA8C2 XHL 20200925 -Start
+            // 鍚堝悓鍙樻洿 骞朵笖 璇环浜у搧鐨� 楠岃瘉浜у搧鏈夋晥鎬� 涓� false 鏃惰烦杩囬獙璇�
+            if (qli.OppliOrderIsChange__c && qli.oppLiVerifyProductValid__c == false){
+            // WLIG-BTA8C2 XHL 20200925 -End
+            } else {
+                if(qli.Product2.NMPAStatus__c == '棣栬惀鐘舵�佸彉鏇�' ||qli.Product2.NMPAStatus__c == '棣栬惀涓嶉�氳繃'){
+                    str += (' '+qli.Product2.ProductCode);
+                    isok = false;
+                }
+            }
+            
+        }
+        System.debug(str);
+        if(isok == true){
+            return '1';
+        }else{
+            return str;
+        }
+    }
+
+    WebService static String checkLicense(String oppid,String ordId){
+        String str = '1';
+        Date endDate = Date.valueOf('2019-12-28');
+        Order ord = [select id,date_P__c from Order where id =:ordId];
+         System.debug('endDate:'+endDate+'       date_P__c:'+ord.date_P__c);
+        Opportunity oppor = [select id,AccountId,Dealer__r.DummyDealer__c,Dealer__r.ParentID,Account.MarketVerticals__c,Trade_Type_D__c from Opportunity where id = :oppid];
+        if(oppor.Account.MarketVerticals__c == 'Clinical'&&oppor.Trade_Type_D__c == 'Taxation' && (ord.date_P__c > endDate || ord.date_P__c == null) ){
+            if(oppor.Dealer__r.DummyDealer__c == true){
+                str = LicenseCheckUtil.LicenseCheck(oppor.AccountId); 
+            }else{
+                str = LicenseCheckUtil.LicenseCheck(oppor.Dealer__r.ParentID); 
+            }
+        }else{
+            System.debug('endDate:'+endDate+'       date_P__c:'+ord.date_P__c);
+        }
+        return str;
+
+    }
+
+    WebService static String checkaddress(String oppid,String address,String ordId){
+        String str = '1';
+        Date endDate = Date.valueOf('2019-12-28');
+        Opportunity oppor = [select id,AccountId,Dealer__r.DummyDealer__c,Dealer__r.ParentID,Account.MarketVerticals__c,Trade_Type_D__c from Opportunity where id = :oppId];
+        Order ord = [select id,date_P__c,Level_Category__c from Order where id =:ordId];
+        List<String> LcList = new List<String>();
+        LcList.add(ordId);
+        String LevelCategory = OrderTriggerHandler.levelCheck(LcList).get(ordId);
+        if(oppor.Account.MarketVerticals__c == 'Clinical'&&oppor.Trade_Type_D__c == 'Taxation' && (ord.date_P__c > endDate || ord.date_P__c == null) && LevelCategory =='浜岀被'){
+            if(oppor.Dealer__r.DummyDealer__c == true){
+                str = LicenseCheckUtil.AddressCheck(oppor.AccountId,address) == true ? '1' : '0';    
+            }else{
+                str = LicenseCheckUtil.AddressCheck(oppor.Dealer__r.ParentID,address) == true ? '1' : '0';
+
+            }
+        }else{
+            System.debug('endDate:'+endDate+'       date_P__c:'+ord.date_P__c);
+        }
+        return str;
+    }
+
+    WebService static String checkLicense1(String oppid){
+        String str = '1';
+        List<OpportunityLineItem> oliList = [select id,Product2.If_Exempt_Product__c,Product2.If_Radiation_Product__c,Opportunity.DealerId__c from OpportunityLineItem where opportunityId = :oppId];
+            Boolean hasA = false;
+            for(OpportunityLineItem oli : oliList){
+                if(oli.Product2.If_Exempt_Product__c == false && oli.Product2.If_Radiation_Product__c == true){
+                    hasA = true;
+                }
+            }
+            if(hasA == true){
+                str =  LicenseCheckUtil.LicenseCheck1(oliList[0].Opportunity.DealerId__c);
+            }
+        return str;
+    }
+    /**
+     * 妫�鏌ュ悎鍚屾彁浜ゅ鎵规椂锛屾墍璐拱鐨勮緪灏勪骇鍝佹暟閲忥紝鏄惁瓒呰繃"濂ユ灄宸存柉浠g悊鍟嗕笌鍚堝悓浠g悊鍟�"鐨勫彲鍞檺鍒�
+     * 鐩墠鐢ㄥ湪-鍚堝悓锛氭彁浜ゅ鎵规寜閽�
+     * @Author   XHL
+     * @DateTime 2020-02-11
+     * @param    orderId    [鍚堝悓Id]
+     * @param    dealerId   [鍚堝悓瀵瑰簲鐨勪唬鐞嗗晢Id]
+     * @return              [寮傚父淇℃伅]
+     */
+     WebService static String checkUpperLimitOfSales(String orderId,String dealerId){
+        String result = '';
+        String olympusAccountId = System.label.Olympus_Id;
+        Map<String, Integer> getModelQuantityMap = RadiationUtil.GetModelQuantityMap(orderId);
+        String errorStr = RadiationUtil.GetCertificationDetail(dealerId,getModelQuantityMap);
+        if(errorStr != ''){
+           return '-1';
+        }
+        String accountDealerErrorMessage = RadiationUtil.updateCertificationDetails(dealerId, null, getModelQuantityMap, false);
+        //String olympusDealerErrorMessage = RadiationUtil.updateCertificationDetails(olympusAccountId, null, getModelQuantityMap, false);
+        result = accountDealerErrorMessage;
+        Boolean temp = result.startsWith('浣犱笉鑳�');
+        if(temp){
+            return '-1';
+        }else{
+            return result;
+        }
+        return result;
+    }
+
+    WebService static String checkUpperLimitOfSalesOly(String orderId,String dealerId){
+        String result = '';
+        String olympusAccountId = System.label.Olympus_Id;
+        Map<String, Integer> getModelQuantityMap = RadiationUtil.GetModelQuantityMap(orderId);
+        /*String errorStr = RadiationUtil.GetCertificationDetail(dealerId,getModelQuantityMap);
+        if(errorStr != ''){
+           return '-1';
+        }
+        String accountDealerErrorMessage = RadiationUtil.updateCertificationDetails(dealerId, null, getModelQuantityMap, false);*/
+        String olympusDealerErrorMessage = RadiationUtil.updateCertificationDetails(olympusAccountId, null, getModelQuantityMap, false);
+        result = olympusDealerErrorMessage == '' ? '' : '浠櫙閫氬彲閿�鍞暟閲忎笉瓒�' ;
+        Boolean temp = result.startsWith('浣犱笉鑳�');
+        if(temp){
+            return '-1';
+        }else{
+            return result;
+        }
+        return result;
+    }
+
+
+    WebService static String updItems(String oppId, String orderId) {
+        String rs = '';
+
+        List<Order> odrList = [select Id, OpportunityId, Opportunity.Model_product_cnt__c, QuoteId from Order where Id = :orderId];
+        Order odr = odrList.size() > 0 ? odrList[0] : null;
+        /*if (odr.Opportunity.Model_product_cnt__c > 0) {
+            return '璇环浜у搧涓湁浜у搧鍨嬪彿锛屼笉鑳藉悓姝ャ��';
+        }*/
+        List<OrderItem> oiList = [select Id from OrderItem where OrderId = :orderId];
+
+        List<Opportunity> oppList = [select Id, SyncedQuoteId, Quote_Discount__c, Quote_Subtotal__c, Quote_TotalPrice__c,
+                                            Quote_Warranty__c, Quote_PaymentTerms_Text__c, Quote_ShipmentTerm__c, Quote_ShipmentTerm2__c,
+                                            Quote_CustomPrice__c
+                                       from Opportunity where Id = :oppId];
+        Opportunity opp = oppList.size() > 0 ? oppList[0] : null;
+        List<OpportunityLineItem> oliList = [select Id, OpportunityId, Description, Quantity, PricebookEntryId, UnitPrice from OpportunityLineItem where OpportunityId = :oppId order by id];
+
+        Quote quo = null;
+        List<QuoteLineItem> qliList = null;
+         List<DecideQuoteProductSet__c> dqpsList = new  List<DecideQuoteProductSet__c>();
+        if (opp != null && opp.SyncedQuoteId != null) {
+            List<Quote> quoList = [select Id from Quote where Id = :opp.SyncedQuoteId];
+            quo = quoList.size() > 0 ? quoList[0] : null;
+
+            qliList = [select Id, QuoteId, Description, Quantity, PricebookEntryId, UnitPrice from QuoteLineItem where QuoteId = :opp.SyncedQuoteId];
+            dqpsList = [select id from DecideQuoteProductSet__c where DecideQuote__c =: opp.SyncedQuoteId];
+            System.debug(dqpsList);
+            for(DecideQuoteProductSet__c dqps : dqpsList){
+                dqps.DecideOrder__c = orderId;
+            }
+        }
+
+        boolean needupd = false;
+//        if (odr.QuoteId != opp.SyncedQuoteId) {
+            
+            odr.QuoteId = opp.SyncedQuoteId;
+            Decimal quoteDiscount = opp.Quote_Discount__c;
+            //odr.Discount__c = opp.Quote_Discount__c;
+            odr.Discount_D__c = quoteDiscount.setScale(4, System.RoundingMode.HALF_UP);
+            Decimal quoteSubtotal = opp.Quote_Subtotal__c;
+            //odr.Olympus_Price_BeforeDiscount__c = opp.Quote_Subtotal__c;
+            odr.Olympus_Price_BeforeDiscount_D__c = quoteSubtotal.setScale(2, System.RoundingMode.HALF_UP);
+            Decimal quoteTotalPrice = opp.Quote_TotalPrice__c;
+            //odr.OlympusContractPrices__c = opp.Quote_TotalPrice__c;
+            odr.OlympusContractPricesD__c = quoteTotalPrice.setScale(0, System.RoundingMode.HALF_UP);
+            //odr.SpecialWarranty__c = opp.Quote_Warranty__c;
+            odr.SpecialWarranty_D__c = String.valueOf(opp.Quote_Warranty__c);
+            //odr.PaymentCondition__c = opp.Quote_PaymentTerms_Text__c;
+            odr.PaymentCondition_D__c = opp.Quote_PaymentTerms_Text__c;
+            //odr.Shipment_Term__c = opp.Quote_ShipmentTerm__c;
+            odr.Shipment_Term_D__c = opp.Quote_ShipmentTerm__c;
+            //odr.Shipment_Term2__c = opp.Quote_ShipmentTerm2__c;
+            odr.Shipment_Term2_D__c = opp.Quote_ShipmentTerm2__c;
+            Decimal quoteCustomPrice = opp.Quote_CustomPrice__c;
+            //odr.CustomerContractPrice__c = opp.Quote_CustomPrice__c;
+            odr.CustomerContractPriceD__c = quoteCustomPrice.setScale(2, System.RoundingMode.HALF_UP);
+
+            odr.product_approval__c = false;
+            needupd = true;
+//        }
+
+        List<OrderItem> insList = new List<OrderItem>();
+        if (opp.SyncedQuoteId != null) {
+            for (QuoteLineItem qli : qliList) {
+                OrderItem oi = new OrderItem();
+                oi.Description = qli.Description;
+                oi.Quantity = qli.Quantity;
+                oi.PricebookEntryId = qli.PricebookEntryId;
+                oi.UnitPrice = qli.UnitPrice;
+                oi.OrderId = orderId;
+                oi.QuoteLineItemId = qli.Id;
+                insList.add(oi);
+            }
+        } else {
+            for (OpportunityLineItem oli : oliList) {
+                OrderItem oi = new OrderItem();
+                oi.Description = oli.Description;
+                oi.Quantity = oli.Quantity;
+                oi.PricebookEntryId = oli.PricebookEntryId;
+                oi.UnitPrice = oli.UnitPrice;
+                oi.OrderId = orderId;
+                insList.add(oi);
+            }
+        }
+
+        try {
+            if (needupd == true){ 
+                update odr;
+                update dqpsList;
+            }
+            if (oiList.size() > 0) delete oiList;
+            if (insList.size() > 0) insert insList;
+            rs = '1';
+        } catch (Exception e) {
+            rs = e.getMessage();
+        }
+
+        return rs;
+    }
+
+    WebService static String copyOrder(String orderId) {
+        String rs = '';
+
+        // 鍙栧緱鍚堝悓銆佸悎鍚屼骇鍝�
+        Order old_odr = null;
+        List<OrderItem> old_oi = new List<OrderItem>();
+
+        Schema.DescribeSobjectResult d_odr = Order.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_odr_map = d_odr.fields.getMap();
+        String soql_odr = 'select ';
+        String fields_odr = '';
+        for (String field : d_odr_map.keySet()) {
+            if (fields_odr.length() > 0) {
+                fields_odr += ', ';
+            }
+            fields_odr += field;
+        }
+        soql_odr += fields_odr;
+        soql_odr += ' from Order where Id = \'' + orderId + '\'';
+        //List<Order> odrList = [select Id, OpportunityId, QuoteId from Order where Id = :orderId];
+        List<Order> odrList = Database.query(soql_odr);
+
+        if (odrList.size() > 0) {
+            old_odr = odrList[0];
+        }
+
+        // 鍚堝悓瀛樺湪check
+        if (old_odr == null) {
+            rs = 'SSBD鍚堝悓涓嶅瓨鍦ㄣ��';
+            return rs;
+        }
+
+        Schema.DescribeSobjectResult d_oi = OrderItem.sObjectType.getDescribe();
+        Map<String, Schema.SObjectField> d_oi_map = d_oi.fields.getMap();
+        String soql_oi = 'select ';
+        String fields_oi = '';
+        for (String field : d_oi_map.keySet()) {
+            if (fields_oi.length() > 0) {
+                fields_oi += ', ';
+            }
+            fields_oi += field;
+        }
+        soql_oi += fields_oi;
+        soql_oi += ' from OrderItem where OrderId = \'' + orderId + '\'';
+        //List<OrderItem> old_oi = [select Id from OrderItem where OrderId = :orderId];
+        old_oi = Database.query(soql_oi);
+
+        // 璇环瀛樺湪check
+        if (old_odr.OpportunityId == null) {
+            rs = 'SSBD鍚堝悓鏁版嵁涓嶆纭紝璇环涓虹┖銆�';
+            return rs;
+        }
+
+        // 鍙栧緱璇环銆佽浠蜂骇鍝�
+        Opportunity old_opp = null;
+        List<Opportunity> oppList = [select Id, SyncedQuoteId from Opportunity where Id = :old_odr.OpportunityId];
+        //List<OpportunityLineItem> old_oli = [select Id from OpportunityLineItem where OpportunityId = :old_odr.OpportunityId];
+        if (oppList.size() > 0) {
+            old_opp = oppList[0];
+        }
+
+        // 鍚屾涓姤浠蜂竴鑷碿heck
+        if (old_opp.SyncedQuoteId != old_odr.QuoteId) {
+            rs = 'SSBD鍚堝悓鏁版嵁涓嶆纭紝鍚屾涓姤浠烽敊璇��';
+            return rs;
+        }
+
+        // 鍚屾涓姤浠枫�佸彇寰楀悓姝ヤ腑鎶ヤ环銆佹姤浠蜂骇鍝�
+        Quote old_quo = null;
+        List<QuoteLineItem> old_qli = new List<QuoteLineItem>();
+        List<DecideQuoteProductSet__c> oldDqps = new List<DecideQuoteProductSet__c>();
+        if (old_odr.QuoteId == null) {
+
+        } else {
+            Schema.DescribeSobjectResult d_quo = Quote.sObjectType.getDescribe();
+            Map<String, Schema.SObjectField> d_quo_map = d_quo.fields.getMap();
+            String soql_quo = 'select ';
+            String fields_quo = '';
+            for (String field : d_quo_map.keySet()) {
+                if (fields_quo.length() > 0) {
+                    fields_quo += ', ';
+                }
+                fields_quo += field;
+            }
+            soql_quo += fields_quo;
+            soql_quo += ' from Quote where Id = \'' + old_odr.QuoteId + '\'';
+            //List<Quote> quoList = [select Id from Quote where Id = :old_odr.QuoteId];
+            List<Quote> quoList = Database.query(soql_quo);
+
+            if (quoList.size() > 0) {
+                old_quo = quoList[0];
+
+                oldDqps = [select id,DecideProductSet__c,DecideProductSetCount__c,DecideProductSetCode__c,DecideProductSetName__c from DecideQuoteProductSet__c where DecideQuote__c =:old_quo.id];
+                
+                //delete oldDqps;
+            }
+
+
+
+            Schema.DescribeSobjectResult d_qli = QuoteLineItem.sObjectType.getDescribe();
+            Map<String, Schema.SObjectField> d_qli_map = d_qli.fields.getMap();
+            String soql_qli = 'select ';
+            String fields_qli = '';
+            for (String field : d_qli_map.keySet()) {
+                if (fields_qli.length() > 0) {
+                    fields_qli += ', ';
+                }
+                fields_qli += field;
+            }
+            soql_qli += fields_qli;
+            soql_qli += ' from QuoteLineItem where QuoteId = \'' + old_odr.QuoteId + '\'';
+            //old_qli = [select Id from QuoteLineItem where QuoteId = :old_odr.QuoteId];
+            old_qli = Database.query(soql_qli);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            Quote new_quo = null;
+            if (old_quo != null) {
+                new_quo = old_quo.clone();
+                new_quo.Id = null;
+                new_quo.Is_Decided__c = false;
+                new_quo.Is_upload__c = false;
+                new_quo.OrderIsChange__c = true;
+                insert new_quo;
+
+                List<QuoteLineItem> new_qli = new List<QuoteLineItem>();
+                for (QuoteLineItem qli : old_qli) {
+                    QuoteLineItem new_i = qli.clone();
+                    new_i.Id = null;
+                    new_i.QuoteId = new_quo.Id;
+                    new_qli.add(new_i);
+                }
+
+                insert new_qli;
+
+                old_quo.Is_Decided__c = false;
+                //old_quo.Is_upload__c = fasle;
+                update old_quo;
+
+                //old_opp.SyncedQuoteId = new_quo.Id;
+                old_opp.Is_Decided__c = false;
+                //old_opp.SAP_Upload__c = false;
+                //old_opp.The_Upload_of_quotation_number__c = null;
+                // WLIG-BTA8C2 XHL 20200925 -Start
+                old_opp.OrderIsChange__c = true;
+                // WLIG-BTA8C2 XHL 20200925 -End
+                update old_opp;
+            } else {
+                // WLIG-BTA8C2 XHL 20200925 -Start
+                old_opp.OrderIsChange__c = true;
+                update old_opp;
+                // WLIG-BTA8C2 XHL 20200925 -End
+            }
+
+            Order new_odr = old_odr.clone();
+            new_odr.Id = null;
+            new_odr.Status__c = 'Active';
+            new_odr.ContractCode__c = null;
+            new_odr.IsNew__c = true;
+            new_odr.IsSpPassed__c = false;
+            //new_odr.product_approval__c = false;
+            new_odr.IsOrderPassed__c = false;
+            new_odr.IsCopy__c = true;
+            new_odr.IsUpload__c = false;
+            new_odr.Is_Already_Splited__c = false;
+            new_odr.CopyStatus__c = new_odr.ApproveStatus__c;
+            new_odr.original_order__c = old_odr.Id;
+//            if (new_quo != null) {
+//                new_odr.QuoteId = new_quo.Id;
+//            }
+            // WLIG-BTA8C2 XHL 20200925 -Start
+            new_odr.OrderIsChange__c = true;
+            // WLIG-BTA8C2 XHL 20200925 -End
+            old_odr.Status__c = 'Inactive';
+            List<Order> updateList = new List<Order>();
+            updateList.add(old_odr);
+            update old_odr;
+
+            insert new_odr;
+            if(old_odr.Association_Order__c != null){
+                Order o = new Order();
+                o.Id = old_odr.Association_Order__c;
+                o.Association_Order__c = new_odr.Id;
+                update o;
+            }
+
+//            List<OrderItem> new_oi = new List<OrderItem>();
+//            for (OrderItem oi : old_oi) {
+//                OrderItem new_i = oi.clone();
+//                new_i.Id = null;
+//                new_i.OrderId = new_odr.Id;
+//                new_oi.add(new_i);
+//            }
+
+//            insert new_oi;
+            if(oldDqps.size() > 0){
+                for(DecideQuoteProductSet__c dqps : oldDqps){
+                    dqps.DecideQuote__c = new_quo.Id;
+                    dqps.DecideOrder__c = new_odr.Id;
+                }
+
+                update oldDqps;
+            }
+
+
+            //鐜嬮箯浼� 寮�濮� 鍚堝悓鍙樻洿锛堝鍒舵簮鍚堝悓(鍙樻洿)锛夊悓姝ュ鍒惰锤鏄撶鐞嗗鎴风敵璇疯〃
+            if(new_odr!=null && new_odr.Id !=null){
+                Schema.DescribeSobjectResult tradeFields = TradeCustomerManager__c.sObjectType.getDescribe();
+                Map<String, Schema.SObjectField> tradeFields_map = tradeFields.fields.getMap();
+                String tradeList_sql = 'select ';
+                String fields_trade = '';
+                for (String field : tradeFields_map.keySet()) {
+                    if (fields_trade.length() > 0) {
+                        fields_trade += ', ';
+                    }
+                    fields_trade += field;
+                }
+                tradeList_sql += fields_trade;
+                tradeList_sql += ' from TradeCustomerManager__c where order__c = \'' + old_odr.Id + '\'';
+                List<TradeCustomerManager__c> tradeList = Database.query(tradeList_sql);
+                if(tradeList!=null && tradeList.size()!=0){
+                    TradeCustomerManager__c newTrade = tradeList[0].clone();
+                    newTrade.Id = null;
+                    newTrade.OrderIdSave__c = new_odr.Id;
+                    newTrade.order__c = new_odr.Id;
+                    insert newTrade;
+                }
+            }
+            //鐜嬮箯浼� 缁撴潫
+            
+            rs = new_odr.Id;
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            rs = ex.getMessage() + '=====' + ex.getStackTraceString();
+        }
+
+        return rs;
+    }
+
+    WebService static String selectOrder(String orderId) {
+        String rs = '';
+
+        // 鍙栧緱鐩爣鍚堝悓銆佸悎鍚屼骇鍝�
+        List<Order> odrList = [select Id, OpportunityId, QuoteId, Quote.Is_Decided__c, Quote.Is_upload__c, Quote.QuoteNumber from Order where Id = :orderId];
+        Order odr = null;
+        if (odrList.size() > 0) {
+            odr = odrList[0];
+        }
+
+        // 鍚堝悓瀛樺湪check
+        if (odr == null) {
+            rs = 'SSBD鍚堝悓涓嶅瓨鍦ㄣ��';
+            return rs;
+        }
+
+        List<OrderItem> odr_oi = new List<OrderItem>();
+        if (odr.QuoteId == null) {
+            odr_oi = [select Id, Description, Quantity, UnitPrice, PricebookEntryId, PricebookEntry.Product2Id from OrderItem where OrderId = :orderId];
+        }
+
+        // 鍙栧緱璇环
+        List<Opportunity> oppList = [select Id from Opportunity where Id = :odr.OpportunityId];
+        Opportunity opp = null;
+        if (oppList.size() > 0) {
+            opp = oppList[0];
+        }
+        List<OpportunityLineItem> oliList = [select Id from OpportunityLineItem where OpportunityId = :odr.OpportunityId];
+
+        // 鍙栧緱鍏朵粬鏈夋晥鍚堝悓
+        List<Order> odrList2 = [select Id from Order where OpportunityId = :opp.Id and Status__c = 'Active' and Id <> :orderId];
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            if (odr.QuoteId != null) {
+                opp.SyncedQuoteId = odr.QuoteId;
+                opp.Is_Decided__c = odr.Quote.Is_Decided__c;
+                opp.SAP_Upload__c = odr.Quote.Is_upload__c;
+                opp.The_Upload_of_quotation_number__c = odr.Quote.Is_upload__c == true ? odr.Quote.QuoteNumber : null;
+            } else {
+                opp.SyncedQuoteId = null;
+                opp.Is_Decided__c = false;
+                opp.SAP_Upload__c = false;
+                opp.The_Upload_of_quotation_number__c = null;
+
+                List<String> prdList = new List<String>();
+                for (OrderItem oi : odr_oi) {
+                    prdList.add(oi.PricebookEntry.Product2Id);
+                }
+                Map<String, String> prdMap = new Map<String, String>();
+                if (prdList.size() > 0) {
+                    List<Product_Search__c> psList = [select Id,Product__c from Product_Search__c where Product__c = :prdList];
+                    for (Product_Search__c ps : psList) {
+                        prdMap.put(ps.Product__c, ps.Id);
+                    }
+                }
+
+                List<OpportunityLineItem> ins_oli = new List<OpportunityLineItem>();
+                for (OrderItem oi : odr_oi) {
+                    OpportunityLineItem oli = new OpportunityLineItem();
+                    oli.OpportunityId = opp.Id;
+                    oli.Description = oi.Description;
+                    oli.DescriptionD__c = oi.Description;
+                    oli.Quantity = oi.Quantity;
+                    oli.QuantityD__c = oi.Quantity;
+                    oli.UnitPrice = oi.UnitPrice;
+                    oli.UnitPriceD__c = oi.UnitPrice;
+                    oli.PricebookEntryId = oi.PricebookEntryId;
+                    oli.Product_Search__c = prdMap.get(oi.PricebookEntry.Product2Id);
+                    ins_oli.add(oli);
+                }
+
+                if (oliList.size() > 0) {
+                    delete oliList;
+                }
+
+                insert ins_oli;
+            }
+
+            update opp;
+
+            odr.Status__c = 'Active';
+            update odr;
+
+            if (odrList2.size() > 0) {
+                for (Order o : odrList2) {
+                    o.Status__c = 'Inactive';
+                }
+                update odrList2;
+            }
+
+            rs = '1';
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            rs = ex.getMessage() + '=====' + ex.getStackTraceString();
+        }
+
+        return rs;
+    }
+
+    WebService static String checkOly() { 
+         return LicenseCheckUtil.LicenseCheckOly();
+    }
+
+    WebService static Boolean IfspecialDealer(String oppDealerId) {
+        if (String.isBlank(oppDealerId)) {
+            return false;
+        }
+        return StaticParameter.specialDealerMap1.containsKey(oppDealerId.substring(0, 15));
+    }
+
+    WebService static Boolean checkSpecialDeliveryContact(String contactId) {
+        if (String.isBlank(contactId)){
+            return false;
+        }
+        List<Contact> contactList = [select Id from Contact 
+                                    where Id = :contactId 
+                                    AND ContactStatus__c = 'Cancel'];
+        if (contactList.size() > 0){
+            return true;
+        } else {
+            return false;
+        }
+    }
+    //鐜嬮箯浼熸柊寤烘柟娉� 銆愬鎵樸�戜笂浼犲悎鍚屾椂澧炲姞瀵瑰鎴�/鑱旂郴浜哄鎵圭姸鎬佺殑妫�鏌� WLIG-BVE68E
+    WebService static String checkAccountContact(String orderId){
+        String str = '';
+
+        List<Order> orderList = [select Id,AccountId,SpecialDeliveryAccount_D__c,ForeignTradeCompany_D__c,EndUserD__c,SpecialDeliveryContact2_D__c,SpecialDeliveryContact2__c from Order where Id=:orderId];
+        if(orderList!=null && orderList.size()!=0){
+            List<String> accountId = new List<String>();
+            accountId.add(orderList[0].AccountId);
+            accountId.add(orderList[0].SpecialDeliveryAccount_D__c);
+            accountId.add(orderList[0].ForeignTradeCompany_D__c);
+            List<Account> accountList = [select Id,Name,stautesD__c from Account where id=:accountId];
+            if(accountList!=null && accountList.size()!=0){
+                for(Account acc:accountList){
+                    if(String.isNotBlank(orderList[0].AccountId) && acc.Id == orderList[0].AccountId && acc.stautesD__c != 'Pass'){
+                        str += '瀹㈡埛瀹℃壒鏈�氳繃锛沑r';
+                    }
+                    if(String.isNotBlank(orderList[0].SpecialDeliveryAccount_D__c) && acc.Id == orderList[0].SpecialDeliveryAccount_D__c && acc.stautesD__c != 'Pass'){
+                        str += '閫佽揪鏂瑰鎵规湭閫氳繃锛沑r';
+                    }
+                    if(String.isNotBlank(orderList[0].ForeignTradeCompany_D__c) && acc.Id == orderList[0].ForeignTradeCompany_D__c && acc.stautesD__c != 'Pass'){
+                        str += '澶栬锤鍏徃瀹℃壒鏈�氳繃锛沑r';
+                    }
+                }
+            }
+            List<String> contactId = new List<String>();
+            contactId.add(orderList[0].EndUserD__c);
+            contactId.add(orderList[0].SpecialDeliveryContact2__c);
+            contactId.add(orderList[0].SpecialDeliveryContact2_D__c);
+            if(contactId.size()!=0){
+                List<Contact> contactList = [select Id,StatusD__c from Contact where Id=:contactId];
+                if(contactList!=null && contactList.size()!=0){
+                    for(Contact con:contactList){
+                        if(String.isNotBlank(orderList[0].EndUserD__c) && con.Id == orderList[0].EndUserD__c && con.StatusD__c != 'Pass'){
+                            str += '鏈�缁堢敤鎴峰鎵规湭閫氳繃锛沑r';
+                        }
+                        if(String.isNotBlank(orderList[0].SpecialDeliveryContact2_D__c) && con.Id == orderList[0].SpecialDeliveryContact2_D__c && con.StatusD__c != 'Pass'){
+                            str += '閫佽揪鏂硅仈绯讳汉瀹℃壒鏈�氳繃锛沑r';
+                        }
+                        if((orderList[0].SpecialDeliveryContact2__c!=orderList[0].SpecialDeliveryContact2_D__c)&&(String.isNotBlank(orderList[0].SpecialDeliveryContact2__c) && con.Id == orderList[0].SpecialDeliveryContact2__c && con.StatusD__c != 'Pass')){
+                            str += '閫佽揪鏂癸紙澶栬锤鍏徃锛夎仈绯讳汉瀹℃壒鏈�氳繃锛沑r';
+                        }
+                    }
+                }
+            }
+        }
+        if(str == ''){
+            return '1';
+        }
+        return str;
+    }
+//浜у搧棣栬惀鐘舵�乑5 XHL 2021/02/07 Start
+    // 鎶ヤ环搴撳瓨妫�鏌�
+    WebService static String OrderInventoryCheck(String orderId) {
+        String result = '1';
+        if (String.isNotBlank(orderId)) {
+            String FGSPStr = '';
+            // 鑾峰彇鍚堝悓鐨� 鏁存満/闆朵欢(璇环涓婄殑)
+            List<Order> orderList = [SELECT Id, Name, Opportunity.Machine_Parts__c FROM Order WHERE Id = :orderId limit 1];
+            if(orderList.size() > 0) {
+                String machine_Parts = orderList[0].Opportunity.Machine_Parts__c;
+                if (String.isNotBlank(machine_Parts) && 'Machine'.equals(machine_Parts)) {
+                    FGSPStr = 'FG';    
+                } else if (String.isNotBlank(machine_Parts) && 'Parts'.equals(machine_Parts)){
+                    FGSPStr = 'SP';
+                }
+            }
+
+            // 鑾峰彇浜у搧鐨勯钀ョ姸鎬佷笌鏁伴噺
+            List<OrderItem> ordLiList = [SELECT Id, Quantity, PricebookEntry.ProductCode, Order.ProductSegment__c, PricebookEntry.Product2.NMPAStatus__c
+            FROM OrderItem WHERE OrderId = :orderId ];
+            Map<String,Decimal> productQuantityMap = new  Map<String,Decimal>();
+            for (OrderItem orderItem : ordLiList) {
+                if ('鍋滀骇'.equals(orderItem.PricebookEntry.Product2.NMPAStatus__c)) {
+                    String productSegment = orderItem.Order.ProductSegment__c == 'BS' ? 'LS':orderItem.Order.ProductSegment__c;
+                    String managementCode = orderItem.PricebookEntry.ProductCode + '_' + productSegment  + '_' + FGSPStr;
+
+                    Decimal quantity = orderItem.Quantity;
+                    if (productQuantityMap.containsKey(managementCode)) {
+                       quantity +=  productQuantityMap.get(managementCode);
+                    }
+                    productQuantityMap.put(managementCode,quantity);
+
+                }
+            }
+
+            if (productQuantityMap != null && productQuantityMap.size() > 0) {
+                result = ProductInventoryCheck(productQuantityMap);
+            }
+        } else {
+            return '0';
+        }
+
+        return result;
+    }
+    // 璇环搴撳瓨妫�鏌�
+    WebService static String  OpportunityInventoryCheck(String opportunityId) {
+        String result = '1';
+        if (String.isNotBlank(opportunityId)) {
+            String FGSPStr = '';
+            
+            List<Opportunity> opportunityList = [SELECT Id, Name,Machine_Parts__c,ProductSegment__c FROM Opportunity WHERE Id = :opportunityId limit 1];
+            if(opportunityList.size() > 0) {
+                String machine_Parts = opportunityList[0].Machine_Parts__c;
+                if (String.isNotBlank(machine_Parts) && 'Machine'.equals(machine_Parts)) {
+                    FGSPStr = 'FG';    
+                } else if (String.isNotBlank(machine_Parts) && 'Parts'.equals(machine_Parts)){
+                    FGSPStr = 'SP';
+                }
+            }
+
+            // 鑾峰彇浜у搧鐨勯钀ョ姸鎬佷笌鏁伴噺
+            List<OpportunityLineItem> oppLiList = [SELECT Id, Quantity, PricebookEntry.ProductCode, ProductSegment__c, PricebookEntry.Product2.NMPAStatus__c
+            FROM OpportunityLineItem WHERE OpportunityId = :opportunityId ];
+            Map<String,Decimal> productQuantityMap = new  Map<String,Decimal>();
+            for (OpportunityLineItem oppItem : oppLiList) {
+                if ('鍋滀骇'.equals(oppItem.PricebookEntry.Product2.NMPAStatus__c)) {
+                    String productSegment = oppItem.ProductSegment__c == 'BS' ? 'LS':oppItem.ProductSegment__c;
+                    String managementCode = oppItem.PricebookEntry.ProductCode + '_' + productSegment  + '_' + FGSPStr;
+
+                    Decimal quantity = oppItem.Quantity;
+                    if (productQuantityMap.containsKey(managementCode)) {
+                        quantity += productQuantityMap.get(managementCode);
+                    }
+                    productQuantityMap.put(managementCode,quantity);
+
+                }
+            }
+
+            if (productQuantityMap != null && productQuantityMap.size() > 0) {
+                result = ProductInventoryCheck(productQuantityMap);
+            }
+        } else {
+            return '0';
+        }
+
+        return result;
+    }
+    // 鎶ヤ环搴撳瓨妫�鏌�
+    WebService static String  QuoteInventoryCheck(String quoteId) {
+        String result = '1';
+        if (String.isNotBlank(quoteId)) {
+            String FGSPStr = '';
+            String productSegment = '';
+            
+            List<Quote> quoteList = [SELECT Id, Name, Opportunity.Machine_Parts__c,ProductSegment__c FROM Quote WHERE Id = :quoteId limit 1];
+            if(quoteList.size() > 0) {
+                String machine_Parts = quoteList[0].Opportunity.Machine_Parts__c;
+                productSegment = quoteList[0].ProductSegment__c == 'BS' ? 'LS':quoteList[0].ProductSegment__c;
+                if (String.isNotBlank(machine_Parts) && 'Machine'.equals(machine_Parts)) {
+                    FGSPStr = 'FG';    
+                } else if (String.isNotBlank(machine_Parts) && 'Parts'.equals(machine_Parts)){
+                    FGSPStr = 'SP';
+                }
+            }
+
+            // 鑾峰彇浜у搧鐨勯钀ョ姸鎬佷笌鏁伴噺
+            List<QuoteLineItem> quoLiList = [SELECT Id, Quantity, PricebookEntry.ProductCode,PricebookEntry.Product2.NMPAStatus__c
+            FROM QuoteLineItem  WHERE QuoteId = :quoteId ];
+            Map<String,Decimal> productQuantityMap = new  Map<String,Decimal>();
+            for (QuoteLineItem  quoItem : quoLiList) {
+                if ('鍋滀骇'.equals(quoItem.PricebookEntry.Product2.NMPAStatus__c)) {
+                    
+                    String managementCode = quoItem.PricebookEntry.ProductCode + '_' + productSegment  + '_' + FGSPStr;
+                    Decimal quantity = quoItem.Quantity;
+                    if (productQuantityMap.containsKey(managementCode)) {
+                        quantity += productQuantityMap.get(managementCode);
+                    }
+                    productQuantityMap.put(managementCode,quantity);
+
+                }
+            }
+
+            if (productQuantityMap != null && productQuantityMap.size() > 0) {
+                result = ProductInventoryCheck(productQuantityMap);
+            }
+        } else {
+            return '0';
+        }
+
+        return result;
+    }
+    // 浜у搧搴撳瓨妫�鏌�
+    public static String ProductInventoryCheck(Map<String,Decimal> productQuantityMap) {
+        String result = '1';
+        System.debug('productQuantityMap--->'+productQuantityMap);
+        Date today = Date.today();
+       // 涓轰簡閬垮厤鍑虹幇闂搴撳瓨鏁伴噺锛岄獙璇佸彧鍙栧綋澶╃殑搴撳瓨
+        List<ProductInventory__c> getProductInventoryList = [SELECT Id, Name,TransforDate__c, ProductCode__c, Plant__c, ProductSegment__c, ProductType__c, InventoryQuantity__c, ManagementCode__c,TradeType__c FROM ProductInventory__c WHERE ManagementCode__c IN :productQuantityMap.keySet() AND TransforDate__c =today AND TradeType__c = 'Taxation'];
+        System.debug('getProductInventoryList--->'+getProductInventoryList);
+        List<String> errorList = new List<String>();
+        if (getProductInventoryList.size() > 0) {
+            // 
+            Map<String,Decimal> existingStockMap = new  Map<String,Decimal>();
+            for (ProductInventory__c inventory :getProductInventoryList) {
+                String managementCode = inventory.ManagementCode__c;
+                Decimal inventoryQuantity = inventory.InventoryQuantity__c;
+
+                if (existingStockMap.containsKey(managementCode)) {
+                    inventoryQuantity += existingStockMap.get(managementCode);
+                } 
+                existingStockMap.put(managementCode, inventoryQuantity);
+            }
+            // 
+            
+            System.debug('existingStockMap--->'+existingStockMap);
+            for (String managementCode:productQuantityMap.keySet()) {
+
+                Decimal salesQuantity =  productQuantityMap.get(managementCode);
+                String productCode = managementCode.split('_')[0];
+                String error = '';
+
+                if(existingStockMap.containsKey(managementCode)) {
+
+                    Decimal inventoryQuantity = existingStockMap.get(managementCode);
+
+                    if (salesQuantity > inventoryQuantity) {
+                        productCode = productCodeFormat(productCode);
+                        error = '浜у搧 [ ' +productCode+' ] 搴撳瓨涓嶈冻';
+                        errorList.add(error);   
+                    } 
+                } else {
+                    // 鎻愮ず浜у搧鏃犲簱瀛�
+                    productCode = productCodeFormat(productCode);
+                    error = '浜у搧 [ ' +productCode+' ] 搴撳瓨涓嶈冻';
+                    errorList.add(error);
+                }
+            }
+        } else {
+            // 鎻愮ず浜у搧鏃犲簱瀛�
+            for (String managementCode:productQuantityMap.keySet()) {
+
+                String productCode = managementCode.split('_')[0];
+                productCode = productCodeFormat(productCode);
+                String error = '浜у搧 [ ' +productCode+' ] 搴撳瓨涓嶈冻';
+                errorList.add(error);
+            }
+        }
+        
+
+        if (errorList.size() > 0) {
+            result = '';
+            for (String error:errorList){
+                result += error + ';';
+            }
+        }
+        System.debug('result--->'+result);
+        return result;
+    }
+    // 浜у搧搴撳瓨鍙樻洿
+    WebService static String OrderUpdateInventory(String orderId) {
+        String result = '1';
+        if (String.isNotBlank(orderId)) {
+            String FGSPStr = '';
+            // 鑾峰彇鍚堝悓鐨� 鏁存満/闆朵欢(璇环涓婄殑)
+            List<Order> orderList = [SELECT Id, Name, Opportunity.Machine_Parts__c FROM Order WHERE Id = :orderId limit 1];
+            if (orderList.size() > 0) {
+                String machine_Parts = orderList[0].Opportunity.Machine_Parts__c;
+                if (String.isNotBlank(machine_Parts) && 'Machine'.equals(machine_Parts)) {
+                    FGSPStr = 'FG';
+                } else if (String.isNotBlank(machine_Parts) && 'Parts'.equals(machine_Parts)) {
+                    FGSPStr = 'SP';
+                }
+            }
+
+            // 鑾峰彇浜у搧鐨勯钀ョ姸鎬佷笌鏁伴噺
+            List<OrderItem> ordLiList = [SELECT Id, Quantity, PricebookEntry.ProductCode, Order.ProductSegment__c, PricebookEntry.Product2.NMPAStatus__c
+                                         FROM OrderItem WHERE OrderId = :orderId ];
+            Map<String, Decimal> productQuantityMap = new  Map<String, Decimal>();
+            for (OrderItem orderItem : ordLiList) {
+                if ('鍋滀骇'.equals(orderItem.PricebookEntry.Product2.NMPAStatus__c)) {
+                    String productSegment = orderItem.Order.ProductSegment__c == 'BS' ? 'LS' : orderItem.Order.ProductSegment__c;
+                    String managementCode = orderItem.PricebookEntry.ProductCode + '_' + productSegment  + '_' + FGSPStr;
+                    Decimal quantity = orderItem.Quantity;
+                    if (productQuantityMap.containsKey(managementCode)) {
+                        quantity += productQuantityMap.get(managementCode);
+                    }
+
+                    productQuantityMap.put(managementCode, quantity);
+
+                }
+            }
+            List<String> errorList = new List<String>();
+            if (productQuantityMap != null && productQuantityMap.size() > 0) {
+                System.debug('productQuantityMap--->'+productQuantityMap);
+                Date today = Date.today();
+                // 涓轰簡閬垮厤鍑虹幇闂搴撳瓨鏁伴噺锛岄獙璇佸彧鍙栧綋澶╃殑搴撳瓨
+                List<ProductInventory__c> getProductInventoryList = [SELECT Id, Name,TransforDate__c, ProductCode__c, Plant__c, ProductSegment__c, ProductType__c, InventoryQuantity__c, ManagementCode__c FROM ProductInventory__c WHERE ManagementCode__c IN :productQuantityMap.keySet() AND TransforDate__c = today AND TradeType__c = 'Taxation'];
+
+                if (getProductInventoryList.size() > 0) {
+                    String managementCode = '';
+                    Decimal inventoryQuantity = 0;
+                    Decimal salesQuantity = 0;
+                    for (ProductInventory__c inventory : getProductInventoryList) {
+                        managementCode = inventory.ManagementCode__c;
+                        inventoryQuantity = inventory.InventoryQuantity__c;
+                        salesQuantity = productQuantityMap.get(managementCode);
+                        if (inventoryQuantity >= salesQuantity) {
+                            inventory.InventoryQuantity__c = inventoryQuantity - salesQuantity;
+                            productQuantityMap.put(managementCode, 0);
+                        } else {
+                            inventory.InventoryQuantity__c = 0;
+                            productQuantityMap.put(managementCode,salesQuantity-inventoryQuantity);
+                        }
+
+                        
+                    }
+                    
+                    for (String managementCodeStr:productQuantityMap.keySet()) {
+                        
+                        salesQuantity = productQuantityMap.get(managementCodeStr);
+                        if (salesQuantity > 0) {
+                            String productCode = productCodeFormat(managementCodeStr.split('_')[0]);
+                            String error = '浜у搧 [ '+ productCode +' ] 搴撳瓨涓嶈冻锛屾棤娉曚笂浼犲悎鍚�';
+                            errorList.add(error);
+                        }
+                    }
+
+                    if (errorList.size() > 0) {
+                        result = '';
+                        for (String error : errorList) {
+                            result += error + ';';
+                        }
+                    } else {
+                        update getProductInventoryList;
+                    }
+
+                }
+            } 
+
+            
+
+        }
+
+        return result;
+    }
+
+    //浜у搧缂栫爜绾暟瀛楄ˉ闆�
+    public static String productCodeFormat(String productCode){
+        if (productCode.startsWith('00000000000')) {
+            productCode = productCode.substring(10);
+        }
+        return productCode;
+    }
+//浜у搧棣栬惀鐘舵�乑5 XHL 2021/02/07 End
+    @TestVisible 
+    public static void testI() {
+        integer i = 0;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderWebService.cls-meta.xml b/scr/classes/OrderWebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrderWebServiceTest.cls b/scr/classes/OrderWebServiceTest.cls
new file mode 100644
index 0000000..5fc8f84
--- /dev/null
+++ b/scr/classes/OrderWebServiceTest.cls
@@ -0,0 +1,1209 @@
+@isTest
+private class OrderWebServiceTest {
+
+	@isTest static void test_updItems1() {
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = user.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Set__c = 'set01'
+        );
+        insert qli;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+        Test.startTest();
+        OrderWebService.updItems(opp.Id, order.Id);
+         Test.stopTest();
+	}
+
+    @isTest static void test_updItems2() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = user.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+         OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+        test.startTest();
+        OrderWebService.updItems(opp.Id, order.Id);
+        test.stopTest();
+    }
+
+    @isTest static void test_copyOrder() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = user.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert contact;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        // OpportunityContactRole ocr = new OpportunityContactRole(
+        //     OpportunityId = opp.Id,
+        //     ContactId = contact.Id,
+        //     IsPrimary = true
+        // );
+        // insert ocr;
+       
+        OpportunityLineItem oli = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Set__c = 'set01'
+        );
+        insert qli;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+        test.startTest();
+        OrderWebService.copyOrder(order.Id);
+        test.stopTest();
+    }
+
+    @isTest static void test_selectOrder1() {
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = user.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        test.startTest();
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Set__c = 'set01'
+        );
+        insert qli;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            QuoteId = quo.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        Order order2 = new Order(
+            Name = 'order2',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order2;
+
+        OrderWebService.selectOrder(order.Id);
+        test.stopTest();
+    }
+
+    @isTest static void test_selectOrder2() {
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = user.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+        insert con;
+
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        test.startTest();
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+
+        List<OrderItem> oiList = new List<OrderItem>();
+        for (Integer i = 0; i < 1; i++) {
+            OrderItem oi = new OrderItem(
+                OrderId = order.Id,
+                PriceBookEntryId = entry1.Id,
+                Quantity = 1,
+                UnitPrice = 10
+            );
+            oiList.add(oi);
+        }
+
+        insert oiList;
+
+        Order order2 = new Order(
+            Name = 'order2',
+            CurrencyIsoCode = 'CNY',
+            AccountId = user.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = user.Id,
+            SpecialDeliveryAccount_D__c = user.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order2;
+
+        OrderWebService.selectOrder(order.Id);
+        test.stopTest();
+    }
+
+     @isTest static void test_order1() {
+        Id pricebookId = Test.getStandardPricebookId();
+        ////璁板綍绫诲瀷-濂ユ灄宸存柉鍒嗗叕鍙�
+        //List<RecordType> olympusRectdealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        ////璁板綍绫诲瀷-浠g悊鍟�
+        //List<RecordType> rectdealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+       
+         List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (rectDealer.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        Account dealer1 = new Account();
+        dealer1.Name = 'test dealer';
+        dealer1.RecordTypeId = rectDealer[0].Id;
+        dealer1.ProductSegment__c = 'ANI';
+        dealer1.PostCode__c='000000';
+        dealer1.ManagementCode_Ext__c = 'C22222';
+        //dealer1.ParentId = dealerParent.Id;
+        insert dealer1;
+
+       //Account user = new Account(
+       //     Name = '*',
+       //     FacilityName__c = 'user',
+       //     PostCode__c = '123456',
+       //     RecordTypeId = rectDealer[0].Id
+       // );
+       // insert user;
+        //1.鍒涘缓涓や釜瀹㈡埛鈶�.ANI浠g悊鍟嗏憽濂ユ灄宸存柉浠g悊鍟�
+        //
+        test.startTest();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.NMPAStatus_one__c = 'Z2';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = dealer1.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        //Account user = new Account(
+        //    Name = '*',
+        //    FacilityName__c = 'user',
+        //    PostCode__c = '123456'
+        //);
+        //insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = dealer1.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+             OpportunityId = opp.Id,
+             PricebookEntryId = entry1.Id,
+             Quantity = 1,
+             UnitPrice = 10
+         );
+         insert new OpportunityLineItem[] {oli1};
+
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = dealer1.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = dealer1.Id,
+            SpecialDeliveryAccount_D__c = dealer1.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+
+        //List<OrderItem> oiList = new List<OrderItem>();
+        //for (Integer i = 0; i < 1; i++) {
+        //    OrderItem oi = new OrderItem(
+        //        OrderId = order.Id,
+        //        PriceBookEntryId = entry1.Id,
+        //        Quantity = 1,
+        //        UnitPrice = 10
+        //    );
+        //    oiList.add(oi);
+        //}
+
+        //insert oiList;
+
+        //Order order2 = new Order(
+        //    Name = 'order2',
+        //    CurrencyIsoCode = 'CNY',
+        //    AccountId = user.Id,
+        //    OpportunityId = opp.Id,
+        //    EffectiveDate = Date.today(),
+        //    Status = 'Draft',
+        //    Pricebook2Id = pricebook.Id
+        //);
+        //insert order2;
+
+        OrderWebService.checkUpperLimitOfSales(order.Id,dealer1.Id);
+        OrderWebService.checkUpperLimitOfSalesOly(order.Id,dealer1.Id);
+        OrderWebService.checkLicense1(opp.Id);
+        OrderWebService.checkLicense(opp.Id,order.Id);
+        OrderWebService.checkproduct(opp.Id);
+        OrderWebService.checkaddress(opp.Id,'Test0522',order.Id);
+        test.stopTest();
+    }
+
+    @isTest static void test_checkAccountContact() {
+
+         Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Account acc = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            stautesD__c = 'Submit'
+        );
+        insert acc;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Submit';
+        insert con;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = acc.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+        
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = acc.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = acc.Id,
+            SpecialDeliveryAccount_D__c = acc.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+        test.startTest();
+        OrderWebService.checkAccountContact(order.Id);
+        test.stopTest();
+    }
+
+    @isTest static void test_Inventory() {
+
+         Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Account acc = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            stautesD__c = 'Submit'
+        );
+        insert acc;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Submit';
+        insert con;
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        // Pricebook2 pricebook = new Pricebook2(
+        //     Name = 'IE',
+        //     ProductSegment__c = 'IE',
+        //     TradeType__c = 'Tax Exemption',
+        //     SalesChannel__c = 'direct',
+        //     MachineParts__c = 'Machine',
+        //     isActive = true,
+        //     CurrencyIsoCode = 'USD'
+        // );
+        // insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.NMPAStatus_one__c = 'Z5';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product1.IsActive = true;
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductCode = 'product2';
+        product2.Product_ECCode__c = 'product2';
+        product2.NMPAStatus_one__c = 'Z5';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product2.IsActive = true;
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product3';
+        product3.NMPAStatus_one__c = 'Z5';
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product3.IsActive = true;
+        insert product3;
+
+        ProductInventory__c productInventory = new ProductInventory__c();
+        productInventory.TransforDate__c = Date.today() ;
+        productInventory.ProductCode__c = product1.Id;
+        productInventory.Plant__c = 'CT22';
+        productInventory.ProductSegment__c = 'LS' ;
+        productInventory.ProductType__c = 'FG' ;
+        productInventory.InventoryQuantity__c = 2;
+        productInventory.ManagementCode__c = product1.ProductCode +'_LS'+'_FG';
+        productInventory.TradeType__c = 'Taxation';
+        insert productInventory;
+
+        ProductInventory__c productInventory2 = new ProductInventory__c();
+        productInventory2.TransforDate__c = Date.today() ;
+        productInventory2.ProductCode__c = product3.Id;
+        productInventory2.Plant__c = 'CT22';
+        productInventory2.ProductSegment__c = 'LS' ;
+        productInventory2.ProductType__c = 'FG' ;
+        productInventory2.InventoryQuantity__c = 2;
+        productInventory2.ManagementCode__c = product1.ProductCode +'_LS'+'_FG';
+        productInventory2.TradeType__c = 'Taxation';
+        insert productInventory2;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert standardPrice1;
+
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert standardPrice2;
+
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert standardPrice3;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        insert entry1;
+
+        PricebookEntry entry2 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        insert entry2;
+
+        PricebookEntry entry3 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert entry3;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = acc.Id,
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli;
+
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry2.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli2;
+
+        OpportunityLineItem oli3 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry3.Id,
+            Quantity = 10,
+            UnitPrice = 10
+        );
+        insert oli3;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli1 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10,
+            Custom_Price__c = 15,
+            Set__c = 'set01'
+        );
+        insert qli1;
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+        
+        Order order = new Order(
+            Name = 'order',
+            CurrencyIsoCode = 'CNY',
+            AccountId = acc.Id,
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            Status = 'Draft',
+            Pricebook2Id = pricebook.Id,
+            SpecialDeliveryAccount__c = acc.Id,
+            SpecialDeliveryAccount_D__c = acc.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert order;
+        test.startTest();
+        OrderWebService.testI();
+        OrderWebService.OrderInventoryCheck(order.Id);
+        OrderWebService.OpportunityInventoryCheck(opp.Id);
+        OrderWebService.OrderUpdateInventory(order.Id);
+        OrderWebService.QuoteInventoryCheck(quo.Id);
+        test.stopTest();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrderWebServiceTest.cls-meta.xml b/scr/classes/OrderWebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/OrderWebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrdertoZhaoEmailBatch.cls b/scr/classes/OrdertoZhaoEmailBatch.cls
new file mode 100644
index 0000000..fea8886
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailBatch.cls
@@ -0,0 +1,50 @@
+global class OrdertoZhaoEmailBatch implements Database.Batchable<sObject> {
+    //缁欒档鏂板畨鎬荤洃鍙戦偖浠讹紝鏇存敼浠栫殑IS_8_Sendemail__c瀛楁鐨勭湡鎴栧亣锛岃仈鍚�'鍙戦�侀偖浠剁粰璧垫柊瀹夋�荤洃'鐨勫伐浣滄祦銆�
+    private List<String> idList = null;
+
+    global OrdertoZhaoEmailBatch() {
+    }
+
+    global OrdertoZhaoEmailBatch(List<String> temp) {
+       idList = temp;
+    }
+
+    global Database.QueryLocator start(Database.BatchableContext bc) {
+        if(idList != null && idList.size()!=0){
+            // return Database.getQueryLocator([select CreatedDate,Low_profit__c,LS_Big_amount__c,IENDTANI_Big_amount__c,RVI_Big_amount__c,
+            //     Whether_the_mhbs__c,IS_8_Sendemail__c,Is_TAX__c
+            //     from Order 
+            //     where (Low_profit__c = true or  LS_Big_amount__c = true or IENDTANI_Big_amount__c = true or RVI_Big_amount__c = true) 
+            //     and Whether_the_mhbs__c = false and ApproveStatus__c = 'OrderPass' 
+            //     and CreatedDate >= 2021-04-01T00:00:00.000+0000
+            //     and Id in :idList]);
+             return Database.getQueryLocator([select CreatedDate,Low_profit__c,LS_Big_amount__c,IENDTANI_Big_amount__c,RVI_Big_amount__c,
+                Whether_the_mhbs__c,IS_8_Sendemail__c,Is_TAX__c
+                from Order 
+                where Id in :idList]);
+        }else{
+            return Database.getQueryLocator([select CreatedDate,Low_profit__c,LS_Big_amount__c,IENDTANI_Big_amount__c,RVI_Big_amount__c,
+                Whether_the_mhbs__c,IS_8_Sendemail__c,Is_TAX__c 
+                from Order 
+                where (Low_profit__c = true or  LS_Big_amount__c = true or IENDTANI_Big_amount__c = true or RVI_Big_amount__c = true) 
+                and Whether_the_mhbs__c = false and ApproveStatus__c = 'OrderPass' 
+                and CreatedDate >= 2021-04-01T00:00:00.000+0000]);    
+                }
+        }
+
+    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
+        List<Order> updatetfList = new List<Order>();
+        for(Sobject obj : scope){
+            Order oer = (Order)obj;
+            if(oer.IS_8_Sendemail__c == false){
+                oer.IS_8_Sendemail__c = true;
+            updatetfList.add(oer);
+            }
+        }
+        if (updatetfList.size() > 0) update updatetfList;
+    }
+
+    global void finish(Database.BatchableContext BC) {
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrdertoZhaoEmailBatch.cls-meta.xml b/scr/classes/OrdertoZhaoEmailBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrdertoZhaoEmailBatchTest.cls b/scr/classes/OrdertoZhaoEmailBatchTest.cls
new file mode 100644
index 0000000..e09d0db
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailBatchTest.cls
@@ -0,0 +1,390 @@
+@isTest
+private class OrdertoZhaoEmailBatchTest {
+    static testMethod void testMethod1() {
+    	List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today().addDays(3),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(6),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp;
+        //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'OrderPass',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        odr.SP_11__c = true;
+        odr.SP_102__c = true;
+        odr.SP_103__c = true;
+        odr.SP_106__c = true;
+        odr.SP_111__c = true;
+        odr.SP_121__c = true;
+        odr.SP_131__c = true;
+        odr.SP_141__c = true;
+        odr.SP_151__c = true;
+        odr.SP_161__c = true;
+        odr.SP_171__c = true;
+        odr.SP_181__c = true;
+        odr.SP_191__c = true;
+        odr.SP_201__c = true;
+        odr.SP_202__c = true;
+        odr.SP_21__c = true;
+        odr.SP_22__c = false;
+        odr.SP_31__c = true;
+        odr.SP_32__c = false;
+        odr.SP_33__c = false;
+        odr.SP_41__c = true;
+        odr.SP_51__c = true;
+        odr.SP_52__c = true;
+        odr.SP_61__c = true;
+        odr.SP_62__c = true;
+        odr.SP_71__c = true;
+        odr.SP_81__c = true;
+        odr.SP_91__c = true;
+
+        odr.IE_SP1__c = true;
+        odr.IE_SP2__c = true;
+        odr.IE_SP3__c = true;
+        odr.IE_SP4__c = false;
+        odr.IE_SP5__c = true;
+        odr.IE_SP6__c = true;
+        odr.IE_SP7__c = true;
+
+        odr.RVI_SP1__c = true;
+        odr.RVI_SP2__c = false;
+        odr.RVI_SP3__c = true;
+        odr.RVI_SP4__c = true;
+        odr.RVI_SP5__c = true;
+        odr.RVI_SP6__c = true;
+
+        odr.NDT_SP1__c = true;
+        odr.NDT_SP2__c = true;
+        odr.NDT_SP3__c = true;
+        odr.NDT_SP4__c = true;
+        odr.NDT_SP5__c = true;
+        odr.NDT_SP6__c = true;
+        odr.NDT_SP7__c = true;
+        odr.NDT_SP8__c = true;
+        odr.NDT_SP9__c = true;
+        odr.NDT_SP10__c = true;
+        odr.NDT_SP11__c = true;
+
+        odr.ANI_SP1__c = true;
+        odr.ANI_SP2__c = true;
+        odr.ANI_SP3__c = true;
+        odr.ANI_SP4__c = true;
+        odr.ANI_SP5__c = true;
+        odr.ANI_SP6__c = true;
+
+        odr.NormalDis_SerContractCondition__c = true;
+        odr.HighDis_SerContractCondition__c = false;
+        odr.SpecialDis_SerContractCondition__c = false;
+        odr.Warranty_SerContractCondition__c = true;
+
+        odr.Discount__c = 50;
+        odr.Olympus_Price_BeforeDiscount__c = 2000000;
+        odr.PaymentCondition__c = 'PaymentCondition__c';
+        odr.SpecialDelivery__c = 'SpecialDelivery__c';
+        odr.SpecialDeliveryContact__c = 'SpecialDeliveryContact__c';
+        odr.SpecialDeliveryPhone__c = '11223344';
+        odr.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress__c';
+        odr.SpecialParkage__c = 'SpecialParkage__c';
+        odr.SpecialWarranty__c = 'SpecialWarranty__c';
+        odr.DealerProfit__c = 0.4;
+        odr.SpecialDelDate__c = Date.today().addDays(1);
+        odr.OtherApply__c = 'OtherApply__c';
+
+        odr.OlympusContractPrices__c = 1000000;
+        odr.OlympusContractPricesD__c = 1000000;
+        odr.EndUser__c = con.Id;
+        odr.Whether_the_mhbs__c = false;
+        odr.IS_8_Sendemail__c = false;
+
+        odr.Andor__c = true;
+        odr.Bitplane__c = true;
+        odr.CoolLED__c = true;
+        odr.Lumen__c = true;
+        odr.Lumenera__c = true;
+        odr.Media_Cybernetics__c = true;
+        odr.Narishige__c = true;
+        odr.Newport__c = true;
+        odr.OSIS_Germany__c = true;
+        odr.OSIS_Singapore__c = true;
+        odr.Photometrics__c = true;
+        odr.Prior_Scientific__c = true;
+        odr.Q_Imaging__c = true;
+        odr.Tokai_Hit__c = true;
+        odr.Other_Third__c = true;
+        odr.ServiceFee__c = 500;
+        odr.AlongProduct__c = '鏄�';
+
+        odr.Contract_Status__c = 'Active';
+
+        update odr;
+
+        System.assertEquals(1000000, odr.OlympusContractPrices__c);
+		System.assertEquals(1000000, odr.OlympusContractPricesD__c);
+		// System.assertEquals('0060T000003GNS3QAO', opp.Id);
+		//System.debug(rectIE);
+        //System.assertEquals(true, odr.IENDTANI_Big_amount__c);
+        //System.assertEquals(true, odr.Is_TAX__c);
+		// System.assertEquals('IE', odr.ProductSegment__c);
+		//System.assertEquals('Taxation', opp.TradeType__c);
+
+        System.Test.StartTest();
+        Id execBTId = Database.executeBatch(new OrdertoZhaoEmailBatch(), 200);
+        System.Test.StopTest();
+    }
+
+    static testMethod void testMethod2() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE; 
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today().addDays(3),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(6),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp;
+        //鐜嬮箯浼� 鏂板姞 瀹㈡埛鍚嶅拰鏈�缁堢敤鎴蜂笌璇环瀵规瘮
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'OrderPass',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        odr.SP_11__c = true;
+        odr.SP_102__c = true;
+        odr.SP_103__c = true;
+        odr.SP_106__c = true;
+        odr.SP_111__c = true;
+        odr.SP_121__c = true;
+        odr.SP_131__c = true;
+        odr.SP_141__c = true;
+        odr.SP_151__c = true;
+        odr.SP_161__c = true;
+        odr.SP_171__c = true;
+        odr.SP_181__c = true;
+        odr.SP_191__c = true;
+        odr.SP_201__c = true;
+        odr.SP_202__c = true;
+        odr.SP_21__c = true;
+        odr.SP_22__c = false;
+        odr.SP_31__c = true;
+        odr.SP_32__c = false;
+        odr.SP_33__c = false;
+        odr.SP_41__c = true;
+        odr.SP_51__c = true;
+        odr.SP_52__c = true;
+        odr.SP_61__c = true;
+        odr.SP_62__c = true;
+        odr.SP_71__c = true;
+        odr.SP_81__c = true;
+        odr.SP_91__c = true;
+
+        odr.IE_SP1__c = true;
+        odr.IE_SP2__c = true;
+        odr.IE_SP3__c = true;
+        odr.IE_SP4__c = false;
+        odr.IE_SP5__c = true;
+        odr.IE_SP6__c = true;
+        odr.IE_SP7__c = true;
+
+        odr.RVI_SP1__c = true;
+        odr.RVI_SP2__c = false;
+        odr.RVI_SP3__c = true;
+        odr.RVI_SP4__c = true;
+        odr.RVI_SP5__c = true;
+        odr.RVI_SP6__c = true;
+
+        odr.NDT_SP1__c = true;
+        odr.NDT_SP2__c = true;
+        odr.NDT_SP3__c = true;
+        odr.NDT_SP4__c = true;
+        odr.NDT_SP5__c = true;
+        odr.NDT_SP6__c = true;
+        odr.NDT_SP7__c = true;
+        odr.NDT_SP8__c = true;
+        odr.NDT_SP9__c = true;
+        odr.NDT_SP10__c = true;
+        odr.NDT_SP11__c = true;
+
+        odr.ANI_SP1__c = true;
+        odr.ANI_SP2__c = true;
+        odr.ANI_SP3__c = true;
+        odr.ANI_SP4__c = true;
+        odr.ANI_SP5__c = true;
+        odr.ANI_SP6__c = true;
+
+        odr.NormalDis_SerContractCondition__c = true;
+        odr.HighDis_SerContractCondition__c = false;
+        odr.SpecialDis_SerContractCondition__c = false;
+        odr.Warranty_SerContractCondition__c = true;
+
+        odr.Discount__c = 50;
+        odr.Olympus_Price_BeforeDiscount__c = 2000000;
+        odr.PaymentCondition__c = 'PaymentCondition__c';
+        odr.SpecialDelivery__c = 'SpecialDelivery__c';
+        odr.SpecialDeliveryContact__c = 'SpecialDeliveryContact__c';
+        odr.SpecialDeliveryPhone__c = '11223344';
+        odr.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress__c';
+        odr.SpecialParkage__c = 'SpecialParkage__c';
+        odr.SpecialWarranty__c = 'SpecialWarranty__c';
+        odr.DealerProfit__c = 0.4;
+        odr.SpecialDelDate__c = Date.today().addDays(1);
+        odr.OtherApply__c = 'OtherApply__c';
+
+        odr.OlympusContractPrices__c = 1000000;
+        odr.OlympusContractPricesD__c = 1000000;
+        odr.EndUser__c = con.Id;
+        odr.Whether_the_mhbs__c = false;
+        odr.IS_8_Sendemail__c = false;
+
+        odr.Andor__c = true;
+        odr.Bitplane__c = true;
+        odr.CoolLED__c = true;
+        odr.Lumen__c = true;
+        odr.Lumenera__c = true;
+        odr.Media_Cybernetics__c = true;
+        odr.Narishige__c = true;
+        odr.Newport__c = true;
+        odr.OSIS_Germany__c = true;
+        odr.OSIS_Singapore__c = true;
+        odr.Photometrics__c = true;
+        odr.Prior_Scientific__c = true;
+        odr.Q_Imaging__c = true;
+        odr.Tokai_Hit__c = true;
+        odr.Other_Third__c = true;
+        odr.ServiceFee__c = 500;
+        odr.AlongProduct__c = '鏄�';
+
+        odr.Contract_Status__c = 'Active';
+
+        update odr;
+
+        System.assertEquals(1000000, odr.OlympusContractPrices__c);
+        System.assertEquals(1000000, odr.OlympusContractPricesD__c);
+        // System.assertEquals('0060T000003GNS3QAO', opp.Id);
+        //System.debug(rectIE);
+        //System.assertEquals(true, odr.IENDTANI_Big_amount__c);
+        //System.assertEquals(true, odr.Is_TAX__c);
+        // System.assertEquals('IE', odr.ProductSegment__c);
+        //System.assertEquals('Taxation', opp.TradeType__c);
+
+        System.Test.StartTest();
+        List<String> orderIdList = new List<String>();
+        orderIdList.add(odr.Id);
+        Id execBTId = Database.executeBatch(new OrdertoZhaoEmailBatch(orderIdList), 200);
+        System.Test.StopTest();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrdertoZhaoEmailBatchTest.cls-meta.xml b/scr/classes/OrdertoZhaoEmailBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrdertoZhaoEmailSchedulable.cls b/scr/classes/OrdertoZhaoEmailSchedulable.cls
new file mode 100644
index 0000000..baa19d4
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailSchedulable.cls
@@ -0,0 +1,5 @@
+global class OrdertoZhaoEmailSchedulable implements Schedulable {
+    global void execute(SchedulableContext sc) {
+        Id execBTId = Database.executeBatch(new OrdertoZhaoEmailBatch(), 100);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrdertoZhaoEmailSchedulable.cls-meta.xml b/scr/classes/OrdertoZhaoEmailSchedulable.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailSchedulable.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/OrdertoZhaoEmailSchedulableTest.cls b/scr/classes/OrdertoZhaoEmailSchedulableTest.cls
new file mode 100644
index 0000000..0f31e1f
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailSchedulableTest.cls
@@ -0,0 +1,19 @@
+@isTest
+private class OrdertoZhaoEmailSchedulableTest {
+    static  testMethod void testExecute() {
+		 // This test runs a scheduled job at midnight Sept. 3rd. 2022
+        String CRON_EXP = '0 0 0 3 9 ? 2032';
+
+        System.Test.startTest();
+        // Schedule the test job
+        String jobId = system.schedule('OrdertoZhaoEmailSchedulable', CRON_EXP, new OrdertoZhaoEmailSchedulable());
+        // Get the information from the CronTrigger API object
+        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
+        // Verify the expressions are the same
+        System.assertEquals(CRON_EXP, ct.CronExpression);
+        // Verify the job has not run
+        System.assertEquals(0, ct.TimesTriggered);
+        // Verify the next time the job will run
+        System.assertEquals('2032-09-03 00:00:00', String.valueOf(ct.NextFireTime));
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/OrdertoZhaoEmailSchedulableTest.cls-meta.xml b/scr/classes/OrdertoZhaoEmailSchedulableTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/OrdertoZhaoEmailSchedulableTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/PDFWbrController.cls b/scr/classes/PDFWbrController.cls
new file mode 100644
index 0000000..07e7fd1
--- /dev/null
+++ b/scr/classes/PDFWbrController.cls
@@ -0,0 +1,27 @@
+public with sharing class PDFWbrController {
+    public String tstr { get; set; }
+    
+    public List<String> getWbrStr() {
+        List<String> rtn = new List<String>();
+        if (String.isBlank(tstr) == false) {
+            if (tstr.contains('LS鍐呰锤')) {
+                for (Integer i = 0; i < tstr.removeEndIgnoreCase('LS鍐呰锤').length(); i++) {
+                    rtn.add(tstr.substring(i, i +1));
+                }
+            }else{
+               for (Integer i = 0; i < tstr.length(); i++) {
+                    rtn.add(tstr.substring(i, i + 1));
+                } 
+            }
+        }
+        return rtn;
+    }
+
+    public Boolean getwbrFlag() {
+        Boolean pdf2Flag = false;
+        if (String.isBlank(tstr) == false && tstr.contains('LS鍐呰锤')) {
+            pdf2Flag = true;
+        }
+        return pdf2Flag;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/PDFWbrController.cls-meta.xml b/scr/classes/PDFWbrController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/PDFWbrController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/PDFWbrControllerTest.cls b/scr/classes/PDFWbrControllerTest.cls
new file mode 100644
index 0000000..142e110
--- /dev/null
+++ b/scr/classes/PDFWbrControllerTest.cls
@@ -0,0 +1,20 @@
+@isTest
+private class PDFWbrControllerTest {
+	
+	@isTest static void test_method_one() {
+		// Implement test code
+		PDFWbrController pd = new PDFWbrController();
+		pd.tstr = '11';
+		List<String> strList = pd.getWbrStr();
+	}
+	@isTest static void test_method_two() {
+		// Implement test code
+		PDFWbrController pd = new PDFWbrController();
+		pd.tstr = '001LS鍐呰锤';
+		List<String> strList = pd.getWbrStr();
+		Boolean pdf2Flag = pd.getwbrFlag();
+	}
+	
+
+	
+}
\ No newline at end of file
diff --git a/scr/classes/PDFWbrControllerTest.cls-meta.xml b/scr/classes/PDFWbrControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/PDFWbrControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/PartnerSoapSforceCom.cls b/scr/classes/PartnerSoapSforceCom.cls
new file mode 100644
index 0000000..93b1dc8
--- /dev/null
+++ b/scr/classes/PartnerSoapSforceCom.cls
@@ -0,0 +1,380 @@
+// Generated by wsdl2apex
+// 蹇呰銇鑳姐倰鏈�灏忓寲銇椼仧
+public class PartnerSoapSforceCom {
+    // request鐢�
+    public class describeLayout_element {
+        public String sObjectType;
+        public String layoutName;
+        public String[] recordTypeIds;
+        private String[] sObjectType_type_info = new String[]{'sObjectType','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] layoutName_type_info = new String[]{'layoutName','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] recordTypeIds_type_info = new String[]{'recordTypeIds','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'sObjectType','layoutName','recordTypeIds'};
+    }
+    // response鐢�
+    public class describeLayoutResponse_element {
+        public PartnerSoapSforceCom.DescribeLayoutResult result;
+        private String[] result_type_info = new String[]{'result','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'result'};
+    }
+    public class DescribeLayoutResult {
+        public PartnerSoapSforceCom.DescribeLayout[] layouts;
+        public PartnerSoapSforceCom.RecordTypeMapping[] recordTypeMappings;
+        public Boolean recordTypeSelectorRequired;
+        private String[] layouts_type_info = new String[]{'layouts','urn:partner.soap.sforce.com',null,'1','-1','false'};
+        private String[] recordTypeMappings_type_info = new String[]{'recordTypeMappings','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] recordTypeSelectorRequired_type_info = new String[]{'recordTypeSelectorRequired','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'layouts','recordTypeMappings','recordTypeSelectorRequired'};
+    }
+    public class DescribeLayout {
+        public PartnerSoapSforceCom.DescribeLayoutButtonSection buttonLayoutSection;
+        public PartnerSoapSforceCom.DescribeLayoutSection[] detailLayoutSections;
+        public PartnerSoapSforceCom.DescribeLayoutSection[] editLayoutSections;
+        public PartnerSoapSforceCom.DescribeLayoutSection highlightsPanelLayoutSection;
+        public String id;
+        public PartnerSoapSforceCom.DescribeQuickActionListResult quickActionList;
+        public PartnerSoapSforceCom.RelatedContent relatedContent;
+        public PartnerSoapSforceCom.RelatedList[] relatedLists;
+        private String[] buttonLayoutSection_type_info = new String[]{'buttonLayoutSection','urn:partner.soap.sforce.com',null,'0','1','false'};
+        private String[] detailLayoutSections_type_info = new String[]{'detailLayoutSections','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] editLayoutSections_type_info = new String[]{'editLayoutSections','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] highlightsPanelLayoutSection_type_info = new String[]{'highlightsPanelLayoutSection','urn:partner.soap.sforce.com',null,'0','1','false'};
+        private String[] id_type_info = new String[]{'id','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] quickActionList_type_info = new String[]{'quickActionList','urn:partner.soap.sforce.com',null,'0','1','false'};
+        private String[] relatedContent_type_info = new String[]{'relatedContent','urn:partner.soap.sforce.com',null,'0','1','false'};
+        private String[] relatedLists_type_info = new String[]{'relatedLists','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'buttonLayoutSection','detailLayoutSections','editLayoutSections','highlightsPanelLayoutSection','id','quickActionList','relatedContent','relatedLists'};
+    }
+    public class DescribeLayoutButtonSection {
+        public PartnerSoapSforceCom.DescribeLayoutButton[] detailButtons;
+        private String[] detailButtons_type_info = new String[]{'detailButtons','urn:partner.soap.sforce.com',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'detailButtons'};
+    }
+    public class DescribeLayoutButton {
+        public String behavior;
+        public PartnerSoapSforceCom.DescribeColor[] colors;
+        public String content;
+        public String contentSource;
+        public Boolean custom;
+        public String encoding;
+        public Integer height;
+        public PartnerSoapSforceCom.DescribeIcon[] icons;
+        public String label;
+        public Boolean menubar;
+        public String name;
+        public Boolean overridden;
+        public Boolean resizeable;
+        public Boolean scrollbars;
+        public Boolean showsLocation;
+        public Boolean showsStatus;
+        public Boolean toolbar;
+        public String url;
+        public Integer width;
+        public String windowPosition;
+        private String[] behavior_type_info = new String[]{'behavior','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] colors_type_info = new String[]{'colors','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] content_type_info = new String[]{'content','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] contentSource_type_info = new String[]{'contentSource','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] custom_type_info = new String[]{'custom','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] encoding_type_info = new String[]{'encoding','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] height_type_info = new String[]{'height','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] icons_type_info = new String[]{'icons','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] label_type_info = new String[]{'label','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] menubar_type_info = new String[]{'menubar','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] name_type_info = new String[]{'name','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] overridden_type_info = new String[]{'overridden','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] resizeable_type_info = new String[]{'resizeable','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] scrollbars_type_info = new String[]{'scrollbars','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] showsLocation_type_info = new String[]{'showsLocation','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] showsStatus_type_info = new String[]{'showsStatus','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] toolbar_type_info = new String[]{'toolbar','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] url_type_info = new String[]{'url','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] width_type_info = new String[]{'width','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] windowPosition_type_info = new String[]{'windowPosition','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'behavior','colors','content','contentSource','custom','encoding','height','icons','label','menubar','name','overridden','resizeable','scrollbars','showsLocation','showsStatus','toolbar','url','width','windowPosition'};
+    }
+    public class DescribeColor {
+        public String color;
+        public String context;
+        public String theme;
+        private String[] color_type_info = new String[]{'color','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] context_type_info = new String[]{'context','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] theme_type_info = new String[]{'theme','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'color','context','theme'};
+    }
+    public class DescribeIcon {
+        public String contentType;
+        public Integer height;
+        public String theme;
+        public String url;
+        public Integer width;
+        private String[] contentType_type_info = new String[]{'contentType','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] height_type_info = new String[]{'height','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] theme_type_info = new String[]{'theme','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] url_type_info = new String[]{'url','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] width_type_info = new String[]{'width','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'contentType','height','theme','url','width'};
+    }
+    public class DescribeLayoutSection {
+        public Integer columns;
+        public String heading;
+        public PartnerSoapSforceCom.DescribeLayoutRow[] layoutRows;
+        public Integer rows;
+        public String tabOrder;
+        public Boolean useCollapsibleSection;
+        public Boolean useHeading;
+        private String[] columns_type_info = new String[]{'columns','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] heading_type_info = new String[]{'heading','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] layoutRows_type_info = new String[]{'layoutRows','urn:partner.soap.sforce.com',null,'1','-1','false'};
+        private String[] rows_type_info = new String[]{'rows','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] tabOrder_type_info = new String[]{'tabOrder','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] useCollapsibleSection_type_info = new String[]{'useCollapsibleSection','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] useHeading_type_info = new String[]{'useHeading','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'columns','heading','layoutRows','rows','tabOrder','useCollapsibleSection','useHeading'};
+    }
+    public class DescribeLayoutRow {
+        public PartnerSoapSforceCom.DescribeLayoutItem[] layoutItems;
+        public Integer numItems;
+        private String[] layoutItems_type_info = new String[]{'layoutItems','urn:partner.soap.sforce.com',null,'1','-1','false'};
+        private String[] numItems_type_info = new String[]{'numItems','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'layoutItems','numItems'};
+    }
+    public class DescribeLayoutItem {
+        public Boolean editableForNew;
+        public Boolean editableForUpdate;
+        public String label;
+        public PartnerSoapSforceCom.DescribeLayoutComponent[] layoutComponents;
+        public Boolean placeholder;
+        public Boolean required;
+        private String[] editableForNew_type_info = new String[]{'editableForNew','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] editableForUpdate_type_info = new String[]{'editableForUpdate','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] label_type_info = new String[]{'label','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] layoutComponents_type_info = new String[]{'layoutComponents','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] placeholder_type_info = new String[]{'placeholder','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] required_type_info = new String[]{'required','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'editableForNew','editableForUpdate','label','layoutComponents','placeholder','required'};
+    }
+    public class DescribeLayoutComponent {
+        public Integer displayLines;
+        public Integer tabOrder;
+        public String type_x;
+        public String value;
+        // ReportChartComponent
+        public Boolean cacheData;
+        public String contextFilterableField;
+        public String error;
+        public Boolean hideOnError;
+        public Boolean includeContext;
+        public Boolean showTitle;
+        public String size;
+        // CustomLinkComponent
+        public partnerSoapSforceCom.DescribeLayoutButton customLink;
+        private String[] displayLines_type_info = new String[]{'displayLines','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] tabOrder_type_info = new String[]{'tabOrder','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] type_x_type_info = new String[]{'type','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] value_type_info = new String[]{'value','urn:partner.soap.sforce.com',null,'1','1','true'};
+        // ReportChartComponent
+        private String[] cacheData_type_info = new String[]{'cacheData','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] contextFilterableField_type_info = new String[]{'contextFilterableField','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] error_type_info = new String[]{'error','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] hideOnError_type_info = new String[]{'hideOnError','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] includeContext_type_info = new String[]{'includeContext','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] showTitle_type_info = new String[]{'showTitle','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] size_type_info = new String[]{'size','urn:partner.soap.sforce.com',null,'1','1','false'};
+        // CustomLinkComponent
+        private String[] customLink_type_info = new String[]{'customLink','urn:partner.soap.sforce.com',null,'1','1','false'};
+
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'displayLines','tabOrder','type_x','value',
+                // ReportChartComponent
+                'cacheData','contextFilterableField','error','hideOnError','includeContext','showTitle','size',
+                // CustomLinkComponent
+                'customLink'
+        };
+    }
+    public class FieldLayoutComponent {
+        public partnerSoapSforceCom.DescribeLayoutComponent[] components;
+        public String fieldType;
+        private String[] components_type_info = new String[]{'components','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] fieldType_type_info = new String[]{'fieldType','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'components','fieldType'};
+    }
+    public class DescribeQuickActionListResult {
+        public PartnerSoapSforceCom.DescribeQuickActionListItemResult[] quickActionListItems;
+        private String[] quickActionListItems_type_info = new String[]{'quickActionListItems','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'quickActionListItems'};
+    }
+    public class DescribeQuickActionListItemResult {
+        public String accessLevelRequired;
+        public PartnerSoapSforceCom.DescribeColor[] colors;
+        public String iconUrl;
+        public PartnerSoapSforceCom.DescribeIcon[] icons;
+        public String label;
+        public String miniIconUrl;
+        public String quickActionName;
+        public String targetSobjectType;
+        public String type_x;
+        private String[] accessLevelRequired_type_info = new String[]{'accessLevelRequired','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] colors_type_info = new String[]{'colors','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] iconUrl_type_info = new String[]{'iconUrl','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] icons_type_info = new String[]{'icons','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] label_type_info = new String[]{'label','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] miniIconUrl_type_info = new String[]{'miniIconUrl','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] quickActionName_type_info = new String[]{'quickActionName','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] targetSobjectType_type_info = new String[]{'targetSobjectType','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] type_x_type_info = new String[]{'type','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'accessLevelRequired','colors','iconUrl','icons','label','miniIconUrl','quickActionName','targetSobjectType','type_x'};
+    }
+    public class RelatedContent {
+        public PartnerSoapSforceCom.DescribeRelatedContentItem[] relatedContentItems;
+        private String[] relatedContentItems_type_info = new String[]{'relatedContentItems','urn:partner.soap.sforce.com',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'relatedContentItems'};
+    }
+    public class DescribeRelatedContentItem {
+        public PartnerSoapSforceCom.DescribeLayoutItem describeLayoutItem;
+        private String[] describeLayoutItem_type_info = new String[]{'describeLayoutItem','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'describeLayoutItem'};
+    }
+    public class RelatedList {
+        public String accessLevelRequiredForCreate;
+        public PartnerSoapSforceCom.DescribeLayoutButton[] buttons;
+        public PartnerSoapSforceCom.RelatedListColumn[] columns;
+        public Boolean custom;
+        public String field;
+        public String label;
+        public Integer limitRows;
+        public String name;
+        public String sobject_x;
+        public PartnerSoapSforceCom.RelatedListSort[] sort_x;
+        private String[] accessLevelRequiredForCreate_type_info = new String[]{'accessLevelRequiredForCreate','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] buttons_type_info = new String[]{'buttons','urn:partner.soap.sforce.com',null,'0','-1','true'};
+        private String[] columns_type_info = new String[]{'columns','urn:partner.soap.sforce.com',null,'1','-1','false'};
+        private String[] custom_type_info = new String[]{'custom','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] field_type_info = new String[]{'field','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] label_type_info = new String[]{'label','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] limitRows_type_info = new String[]{'limitRows','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] name_type_info = new String[]{'name','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] sobject_x_type_info = new String[]{'sobject','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] sort_x_type_info = new String[]{'sort','urn:partner.soap.sforce.com',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'accessLevelRequiredForCreate','buttons','columns','custom','field','label','limitRows','name','sobject_x','sort_x'};
+    }
+    public class RelatedListSort {
+        public Boolean ascending;
+        public String column;
+        private String[] ascending_type_info = new String[]{'ascending','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] column_type_info = new String[]{'column','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'ascending','column'};
+    }
+    public class RelatedListColumn {
+        public String field;
+        public String format;
+        public String label;
+        public String lookupId;
+        public String name;
+        private String[] field_type_info = new String[]{'field','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] format_type_info = new String[]{'format','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] label_type_info = new String[]{'label','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] lookupId_type_info = new String[]{'lookupId','urn:partner.soap.sforce.com',null,'0','1','true'};
+        private String[] name_type_info = new String[]{'name','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'field','format','label','lookupId','name'};
+    }
+    public class RecordTypeMapping {
+        public Boolean available;
+        public Boolean defaultRecordTypeMapping;
+        public String layoutId;
+        public String name;
+        public PartnerSoapSforceCom.PicklistForRecordType[] picklistsForRecordType;
+        public String recordTypeId;
+        private String[] available_type_info = new String[]{'available','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] defaultRecordTypeMapping_type_info = new String[]{'defaultRecordTypeMapping','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] layoutId_type_info = new String[]{'layoutId','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] name_type_info = new String[]{'name','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] picklistsForRecordType_type_info = new String[]{'picklistsForRecordType','urn:partner.soap.sforce.com',null,'0','-1','true'};
+        private String[] recordTypeId_type_info = new String[]{'recordTypeId','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'available','defaultRecordTypeMapping','layoutId','name','picklistsForRecordType','recordTypeId'};
+    }
+    public class PicklistForRecordType {
+        public String picklistName;
+        public PartnerSoapSforceCom.PicklistEntry[] picklistValues;
+        private String[] picklistName_type_info = new String[]{'picklistName','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] picklistValues_type_info = new String[]{'picklistValues','urn:partner.soap.sforce.com',null,'0','-1','true'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'picklistName','picklistValues'};
+    }
+    public class PicklistEntry {
+        public Boolean active;
+        public Boolean defaultValue;
+        public String label;
+        public String validFor;
+        public String value;
+        private String[] active_type_info = new String[]{'active','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] defaultValue_type_info = new String[]{'defaultValue','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] label_type_info = new String[]{'label','urn:partner.soap.sforce.com',null,'1','1','true'};
+        private String[] validFor_type_info = new String[]{'validFor','urn:partner.soap.sforce.com',null,'0','1','false'};
+        private String[] value_type_info = new String[]{'value','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'active','defaultValue','label','validFor','value'};
+    }
+
+    public class Soap {
+        public String endpoint_x = 'https://test.salesforce.com/services/Soap/u/33.0';
+        public Map<String,String> inputHttpHeaders_x;
+        public Map<String,String> outputHttpHeaders_x;
+        public String clientCertName_x;
+        public String clientCert_x;
+        public String clientCertPasswd_x;
+        public Integer timeout_x;
+        public PartnerSoapSforceCom.SessionHeader_element SessionHeader;
+        private String SessionHeader_hns = 'SessionHeader=urn:partner.soap.sforce.com';
+        private String[] ns_map_type_info = new String[]{'urn:sobject.partner.soap.sforce.com', 'SobjectPartnerSoapSforceCom', 'urn:fault.partner.soap.sforce.com', 'FaultPartnerSoapSforceCom', 'urn:partner.soap.sforce.com', 'PartnerSoapSforceCom'};
+        public PartnerSoapSforceCom.DescribeLayoutResult describeLayout(String sObjectType,String layoutName,String[] recordTypeIds) {
+            PartnerSoapSforceCom.describeLayout_element request_x = new PartnerSoapSforceCom.describeLayout_element();
+            request_x.sObjectType = sObjectType;
+            request_x.layoutName = layoutName;
+            request_x.recordTypeIds = recordTypeIds;
+            PartnerSoapSforceCom.describeLayoutResponse_element response_x;
+            Map<String, PartnerSoapSforceCom.describeLayoutResponse_element> response_map_x = new Map<String, PartnerSoapSforceCom.describeLayoutResponse_element>();
+            response_map_x.put('response_x', response_x);
+            WebServiceCallout.invoke(
+              this,
+              request_x,
+              response_map_x,
+              new String[]{endpoint_x,
+              '',
+              'urn:partner.soap.sforce.com',
+              'describeLayout',
+              'urn:partner.soap.sforce.com',
+              'describeLayoutResponse',
+              'PartnerSoapSforceCom.describeLayoutResponse_element'}
+            );
+            response_x = response_map_x.get('response_x');
+            return response_x.result;
+        }
+    }
+    public class SessionHeader_element {
+        public String sessionId;
+        private String[] sessionId_type_info = new String[]{'sessionId','urn:partner.soap.sforce.com',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'urn:partner.soap.sforce.com','true','false'};
+        private String[] field_order_type_info = new String[]{'sessionId'};
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/PartnerSoapSforceCom.cls-meta.xml b/scr/classes/PartnerSoapSforceCom.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/PartnerSoapSforceCom.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/PersonalProcessInstanceController.cls b/scr/classes/PersonalProcessInstanceController.cls
new file mode 100644
index 0000000..7d4d8e3
--- /dev/null
+++ b/scr/classes/PersonalProcessInstanceController.cls
@@ -0,0 +1,96 @@
+public with sharing class PersonalProcessInstanceController {
+    public List<ProcessInfo> accPIList { get; private set; }
+    public List<ProcessInfo> conPIList { get; private set; }
+    public List<ProcessInfo> oppPIList { get; private set; }
+    public List<ProcessInfo> odrPIList { get; private set; }
+    public List<ProcessInfo> othPIList { get; private set; }
+
+    private String userId;
+
+    public Integer getAccPIListSize() {
+        return accPIList.size();
+    }
+
+    public Integer getConPIListSize() {
+        return conPIList.size();
+    }
+
+    public Integer getOppPIListSize() {
+        return oppPIList.size();
+    }
+
+    public Integer getOdrPiListSize() {
+        return odrPIList.size();
+    }
+
+    public Integer getOthPIListSize() {
+        return othPIList.size();
+    }
+
+    public PersonalProcessInstanceController() {
+        userId = ApexPages.currentPage().getParameters().get('uid');
+        if (userId == null || userId == '') {
+            userId = UserInfo.getUserId();
+        }
+    }
+
+    public PageReference init() {
+        List<ProcessInstanceWorkitem> piwList = [select id, ActorId, CreatedDate, ElapsedTimeInDays, OriginalActorId,
+                                                        ProcessInstance.TargetObjectId, ProcessInstance.Targetobject.Name, ProcessInstance.Status, ProcessInstance.SubmittedbyId, ProcessInstance.Submittedby.Name
+                                                   from ProcessInstanceWorkitem
+                                                  where ActorId = :userId
+                                                  order by ProcessInstance.TargetobjectId, CreatedDate asc];
+
+        Integer lineNo = 0;
+        accPIList = new List<ProcessInfo>();
+        conPIList = new List<ProcessInfo>();
+        oppPIList = new List<ProcessInfo>();
+        odrPIList = new List<ProcessInfo>();
+        othPIList = new List<ProcessInfo>();
+        if (piwList.size() > 0) {
+            for (ProcessInstanceWorkitem piw : piwList) {
+                lineNo += 1;
+                String targetObjectId = piw.ProcessInstance.TargetObjectId;
+                if (targetObjectId.startsWith('001') == true) {
+                    // account
+                    ProcessInfo newpi = new ProcessInfo(lineNo, piw, 'account');
+                    accPIList.add(newpi);
+                } else if (targetObjectId.startsWith('003') == true) {
+                    // contact
+                    ProcessInfo newpi = new ProcessInfo(lineNo, piw, 'contact');
+                    conPIList.add(newpi);
+                } else if (targetObjectId.startsWith('006') == true) {
+                    // opportunity
+                    ProcessInfo newpi = new ProcessInfo(lineNo, piw, 'opportunity');
+                    oppPIList.add(newpi);
+                } else if (targetObjectId.startsWith('801') == true) {
+                    // order
+                    ProcessInfo newpi = new ProcessInfo(lineNo, piw, 'order');
+                    odrPIList.add(newpi);
+                } else {
+                    // others
+                    ProcessInfo newpi = new ProcessInfo(lineNo, piw, 'other');
+                    othPIList.add(newpi);
+                }
+            }
+        }
+
+        return null;
+    }
+
+    class ProcessInfo {
+        public Integer lineNo { get; private set; }
+        public ProcessInstanceWorkitem piw { get; private set; }
+        public Decimal elapsedTimeInDays { get; private set; }
+        // accpunt,contact,opportunity,order,other
+        public String pType { get; private set; }
+
+        public ProcessInfo(Integer in_no, ProcessInstanceWorkitem in_piw, String in_pType) {
+            lineNo = in_no;
+            piw = in_piw;
+            pType = in_pType;
+            elapsedTimeInDays = in_piw.ElapsedTimeInDays;
+            elapsedTimeInDays = elapsedTimeInDays.setScale(1);
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/PersonalProcessInstanceController.cls-meta.xml b/scr/classes/PersonalProcessInstanceController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/PersonalProcessInstanceController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/PersonalProcessInstanceControllerTest.cls b/scr/classes/PersonalProcessInstanceControllerTest.cls
new file mode 100644
index 0000000..d2b7a66
--- /dev/null
+++ b/scr/classes/PersonalProcessInstanceControllerTest.cls
@@ -0,0 +1,161 @@
+@isTest
+private class PersonalProcessInstanceControllerTest {
+
+	@isTest static void test_method_one() {
+        Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
+        Approval.ProcessResult submitResult = null;
+
+        List<RecordType> rectRVI = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer RVI'];
+        Account accRVI = new Account(
+            Name = '*',
+            RecordTypeId = rectRVI[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer RVI',
+            FacilityName__c='abc',
+            PostCode__c='000000',
+            stautesD__c = 'Completed',
+            IsNew__c = true
+        );
+        insert accRVI;
+
+        psr = new Approval.ProcessSubmitRequest();
+        psr.setObjectId(accRVI.Id);
+        submitResult = Approval.process(psr);
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accRVI.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Completed';
+        con.IsNew__c = true;
+        con.DealerSelectOwner__c = UserInfo.getUserId();
+
+        insert con;
+
+        psr = new Approval.ProcessSubmitRequest();
+        psr.setObjectId(con.Id);
+        submitResult = Approval.process(psr);
+
+        Id pricebookId = Test.getStandardPricebookId();
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'RVI',
+            ProductSegment__c = 'RVI',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert entry1;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accRVI.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'RVI',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Machine_Parts_D__c = 'Machine',
+            ApprovalStatus_D__c = 'Completed',
+            IsNew__c = true
+        );
+        insert opp;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oli1;
+
+        opp.ApprovalStatus_D__c = 'Completed';
+        update opp;
+
+        psr = new Approval.ProcessSubmitRequest();
+        psr.setObjectId(opp.Id);
+        submitResult = Approval.process(psr);
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'RVISalesContract'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accRVI.Id,
+            ApproveStatus__c = 'Completed2',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = rectOdr[0].Id,
+            SpecialDeliveryAccount__c = accRVI.Id,
+            SpecialDeliveryAccount_D__c = accRVI.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            IsCopy__c = true
+        );
+        insert odr;
+
+        psr = new Approval.ProcessSubmitRequest();
+        psr.setObjectId(odr.Id);
+        submitResult = Approval.process(psr);
+
+        ProcessInstanceWorkitem piw = [select id, ActorId, ProcessInstance.TargetobjectId from ProcessInstanceWorkitem where ProcessInstance.TargetobjectId = :odr.Id];
+        piw.ActorId = UserInfo.getUserId();
+        update piw;
+
+        PageReference page = new PageReference('/apex/PersonalProcessInstance');
+        System.Test.setCurrentPage(page);
+
+        PersonalProcessInstanceController controller = new PersonalProcessInstanceController();
+
+        //鍒濆鍖�
+        controller.init();
+
+        controller.getAccPIListSize();
+        controller.getConPIListSize();
+        controller.getOppPIListSize();
+        controller.getOdrPiListSize();
+        controller.getOthPIListSize();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/PersonalProcessInstanceControllerTest.cls-meta.xml b/scr/classes/PersonalProcessInstanceControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/PersonalProcessInstanceControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterBatch.cls b/scr/classes/ProRegisterBatch.cls
new file mode 100644
index 0000000..4b3e1fe
--- /dev/null
+++ b/scr/classes/ProRegisterBatch.cls
@@ -0,0 +1,45 @@
+global class ProRegisterBatch implements Database.Batchable<sObject> {
+    String regId;
+    
+    global ProRegisterBatch(String regId) {
+        this.regId = regId;
+    }
+
+    global ProRegisterBatch() {
+        
+    }
+    
+    global Database.QueryLocator start(Database.BatchableContext BC) {
+        Date yesterday = Date.Today() - 1;
+        
+        if (String.isBlank(this.regId)) {
+            return Database.getQueryLocator([select id, ValidProductRegister__c
+                                               from Product_Register__c 
+                                              where ValidProductRegister__c = false
+                                                and ValidTo__c = yesterday ]);
+
+        } else {
+            if (this.regId == 'updateAllInvalidData') {
+                return Database.getQueryLocator([select id, ValidProductRegister__c
+                                               from Product_Register__c 
+                                              where ValidProductRegister__c = false ]);
+                                                
+            } else {
+                return Database.getQueryLocator([select id, ValidProductRegister__c 
+                                               from Product_Register__c 
+                                              where id = :this.regId
+                                                and ValidTo__c <= :Date.Today()]);    
+            }
+            
+        }
+    }
+
+    global void execute(Database.BatchableContext BC, List<Product_Register__c> dcList) {
+        
+        if (dcList.size() > 0) update dcList;
+    }
+
+    global void finish(Database.BatchableContext BC) {
+        
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterBatch.cls-meta.xml b/scr/classes/ProRegisterBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterBatchSchedulable.cls b/scr/classes/ProRegisterBatchSchedulable.cls
new file mode 100644
index 0000000..18ef3c4
--- /dev/null
+++ b/scr/classes/ProRegisterBatchSchedulable.cls
@@ -0,0 +1,5 @@
+global class ProRegisterBatchSchedulable implements Schedulable {
+    global void execute(SchedulableContext sc) {
+        Id execBTId = database.executebatch(new ProRegisterBatch(),100);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterBatchSchedulable.cls-meta.xml b/scr/classes/ProRegisterBatchSchedulable.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterBatchSchedulable.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterBatchSchedulableTest.cls b/scr/classes/ProRegisterBatchSchedulableTest.cls
new file mode 100644
index 0000000..988b42b
--- /dev/null
+++ b/scr/classes/ProRegisterBatchSchedulableTest.cls
@@ -0,0 +1,17 @@
+@isTest
+private class ProRegisterBatchSchedulableTest {
+
+    @isTest static void test_method_one() {
+		String CRON_EXP = '0 0 0 3 9 ? 2022';
+        System.Test.startTest();
+        String jobId = system.schedule('ProRegisterBatchSchedulableTest', CRON_EXP, new ProRegisterBatchSchedulable());       
+        System.Test.StopTest();
+	}
+
+	//@isTest static void test_method_two() {
+	//	String CRON_EXP = '0 0 0 3 9 ? 2022';
+ //       System.Test.startTest();
+ //       String jobId = system.schedule('ProRegisterBatchSchedulableTest', CRON_EXP, new ProRegisterBatchSchedulable());       
+ //       System.Test.StopTest();
+	//}
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterBatchSchedulableTest.cls-meta.xml b/scr/classes/ProRegisterBatchSchedulableTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterBatchSchedulableTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterBatchTest.cls b/scr/classes/ProRegisterBatchTest.cls
new file mode 100644
index 0000000..ba40bc1
--- /dev/null
+++ b/scr/classes/ProRegisterBatchTest.cls
@@ -0,0 +1,54 @@
+@isTest
+private class ProRegisterBatchTest {
+	static testMethod void testMethod1() {
+
+		Product_Register__c prorec = new Product_Register__c();
+		prorec.Name = 'SFDCTEST2018001';
+		prorec.MedPrdClass__c = '3';
+		prorec.RegisterNoClass_New__c = '';
+		prorec.RegisterNoClass_Old__c = '6822';
+		prorec.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		prorec.ValidTo__c = Date.today().addDays(-1);
+		prorec.ValidFrom__c = Date.today().addDays(-22);
+		insert prorec;
+		Product_Register__c prorec1 = new Product_Register__c();
+		prorec1.Name = 'SFDCTEST2018002';
+		prorec1.MedPrdClass__c = '3';
+		prorec1.RegisterNoClass_New__c = '';
+		prorec1.RegisterNoClass_Old__c = '6822';
+		prorec1.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		prorec1.ValidTo__c = Date.today().addDays(1);
+		prorec1.ValidFrom__c = Date.today().addDays(-22);
+		insert prorec1;
+		List<Product_Register__c> prorecList = [select Id, Name, ValidProductRegister__c from Product_Register__c ];
+		System.assertEquals(false, prorecList[0].ValidProductRegister__c);
+
+		Product2 pro = new Product2();
+		pro.Name = 'A00507A:瀵嗗皝鍦�,  閫忔槑, 榛戣壊';
+		pro.registrationCode__c  = 'SFDCTEST2018001 SFDCTEST2018002';
+		insert pro;
+
+		Product_Register_Link__c prl = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl.Product2__c = pro.ID;
+		insert prl;
+
+		Product_Register_Link__c prl2 = new Product_Register_Link__c(Product_Register__c = prorec1.ID);
+		prl2.Product2__c = pro.ID;
+		insert prl2;
+
+		Id execBTId = null;
+		System.Test.StartTest();
+		execBTId = Database.executeBatch(new ProRegisterBatch());
+		List<Product2> productList = [select Id, registrationCode__c from Product2];
+		System.assertEquals('SFDCTEST2018002', productList[0].registrationCode__c);
+		execBTId = Database.executeBatch(new ProRegisterBatch('updateAllInvalidData'));
+		productList = [select Id, registrationCode__c from Product2];
+		System.assertEquals('SFDCTEST2018002', productList[0].registrationCode__c);
+		String prorecId = prorec.ID;
+		execBTId = Database.executeBatch(new ProRegisterBatch(prorecId));
+		productList = [select Id, registrationCode__c from Product2];
+		System.assertEquals('SFDCTEST2018002', productList[0].registrationCode__c);
+		System.Test.StopTest();
+
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterBatchTest.cls-meta.xml b/scr/classes/ProRegisterBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterHandler.cls b/scr/classes/ProRegisterHandler.cls
new file mode 100644
index 0000000..d3ab708
--- /dev/null
+++ b/scr/classes/ProRegisterHandler.cls
@@ -0,0 +1,192 @@
+public without sharing class ProRegisterHandler {
+
+	public static void updateProduct(List<Product_Register__c> newList, Map<Id, Product_Register__c> newMap, List<Product_Register__c> oldList, Map<Id, Product_Register__c> oldMap) {
+
+		// 浜у搧-娉ㄥ唽璇佸叧绯� 涓墍鏈� 浜у搧ID
+		List<ID> Product2_ID_list = new list<ID>();
+		// 鐜版湁浜у搧 map
+		Map<ID, Product2> Exist_ProductMap = new map<ID, Product2>();
+		// 闇�瑕佹洿鏂颁骇鍝� list
+		List<Product2> UpdateProductlist = new list<Product2>();
+		// 鏍规嵁鍙樻洿鐨勮瘉ID鎵惧埌鍏宠仈鐨勬墍鏈夌殑浜у搧
+		list<Product_Register_Link__c> ExistPRLList = [select Product2__c,
+		                               Product_Register__c
+		                               from Product_Register_Link__c
+		                               where Product_Register__c in: newList
+		                                              ];
+
+		for (Product_Register_Link__c PRL : ExistPRLList) {
+			// 浜у搧ID鐨凩IST
+			Product2_ID_list.add(PRL.Product2__c);
+		}
+
+		// 閫氳繃浜у搧ID鎵惧埌璇ヤ骇鍝佹渶鏂版敞鍐岃瘉ID
+		Exist_ProductMap = new Map<ID, Product2> ([select ID, Register_Latest__c, registrationCode__c, clinical_product_code__c
+		        from Product2
+		        where id in: Product2_ID_list
+		                                          ]);
+
+		// 閫氳繃浜у搧ID鎵惧埌鎵�鏈夋秹鍙婄殑鏈夋晥鍏崇郴
+		List<Product_Register_Link__c> allPRLList = [select Product2__c,
+		                               Product_Register__c,
+		                               Product_Register__r.PrdCompanyAddr__c,
+		                               Product_Register__r.ValidFrom__c,
+		                               Product_Register__r.ValidTo__c,
+		                               Product_Register__r.Name,
+		                               Product_Register__r.ValidProductRegister__c,
+		                               Product_Register__r.ClinicalProductCode__c
+		                               from Product_Register_Link__c
+		                               where Product2__c in : Product2_ID_list
+		                               order by Product2__c,
+		                               LastModifiedDate desc
+		                                            ];
+
+		String tmpProductID = '';
+		Product2 temProduct = new Product2();
+		Map<Id, Product2> UpdProMap = new Map<Id, Product2>();
+
+		for (Product_Register_Link__c temPRL : allPRLList) {
+
+			if (!tmpProductID.equals(temPRL.Product2__c)) {
+
+				tmpProductID = temPRL.Product2__c;
+				temProduct = Exist_ProductMap.get(tmpProductID);
+				temProduct.Register_Latest__c = temPRL.Product_Register__c;                    // 鏈�鏂版敞鍐岃瘉ID
+				temProduct.registrationCode__c = null;
+				temProduct.clinical_product_code__c = null;
+			}
+
+			// 濡傛灉娉ㄥ唽璇佺姸鎬佹湁鏁�,璁板綍鏈夋晥娉ㄥ唽璇佸彿
+			if (temPRL.Product_Register__r.ValidProductRegister__c ) {
+				if (String.isBlank(temProduct.registrationCode__c)) {
+					temProduct.registrationCode__c = temPRL.Product_Register__r.Name + '\n';
+				} else {
+					if (String.isNotBlank(temPRL.Product_Register__r.Name)) {
+						if (temProduct.registrationCode__c.indexOf(temPRL.Product_Register__r.Name) == -1) {
+							temProduct.registrationCode__c += temPRL.Product_Register__r.Name + '\n';
+						}
+					}
+				}
+
+				String clinicalCode = temPRL.Product_Register__r.ClinicalProductCode__c;
+				if (String.isBlank(temProduct.clinical_product_code__c)) {
+					temProduct.clinical_product_code__c = clinicalCode;//temPRL.Product_Register__r.ClinicalProductCode__c;
+				} else {
+
+					if (String.isNotBlank(clinicalCode)) {
+
+						Map<String, String> codeMap = new Map<String, String>();
+						for (String code : temProduct.clinical_product_code__c.split('/')) {
+							codeMap.put(code, code);
+						}
+						codeMap.put(clinicalCode, clinicalCode);
+						temProduct.clinical_product_code__c = '';
+						for (String code : codeMap.values()) {
+							if (String.isBlank(temProduct.clinical_product_code__c)) {
+								temProduct.clinical_product_code__c = code;
+							} else {
+								temProduct.clinical_product_code__c += '/' + code;
+							}
+						}
+						
+					}
+
+				}
+			}
+			UpdProMap.put(tmpProductID, temProduct);
+		}
+		if (UpdProMap.keySet().size() > 0)  update UpdProMap.values();
+	}
+
+	//浜у搧闄嶇被,鍙娉ㄥ唽璇佹洿鏂颁簡,灏辨鏌ヤ竴閬嶏紝閲嶆柊缁欎骇鍝佷笂鐨勭瓑绾х被鍒瓧娈佃祴鍊笺��
+	//鍙互鎵惧嚭闇�瑕佺殑Id,鐒跺悗璋冪敤鏂规硶銆�
+	public static void checkRegistervervaldatum(List<Product_Register__c> newList, Map<Id, Product_Register__c> newMap, List<Product_Register__c> oldList, Map<Id, Product_Register__c> oldMap) {
+		if (Trigger.isAfter && Trigger.isUpdate) {
+			List<String> prcList = new List<String>();
+			for (Product_Register__c pr : newList) {
+				Product_Register__c oldpr = oldMap.get(pr.Id);
+				//鏈夋晥鏈熺殑濮嬩笌缁堝彉浜�,灏辨妸杩欎釜浜у搧娉ㄥ唽璇佺殑id鏀惧叆涓�涓狶ist闆嗗悎閲岄潰
+				//if (pr.ValidTo__c != oldpr.ValidTo__c || pr.ValidFrom__c != oldpr.ValidFrom__c) {
+				    prcList.add(pr.id);
+				//}
+			}
+			//鏀惧埌Map閲岋紝鐢ㄤ簬鎰熻娉ㄥ唽璇佹洿鏂颁骇鍝�
+			Map<Id,Product2> prt2Map = new Map<Id,Product2>();
+			//閫氳繃涔嬪墠瀛樺偍鐨処d鐢ㄤ簬鍏崇郴琛ㄧ殑鏌ヨ銆�
+			List<Product_Register_Link__c> prlList = new List<Product_Register_Link__c>();
+			prlList = [select Product2__r.id,Product2__r.demoteer_Sap__c,Product_Register__r.MedPrdClass__c,Product_Register__r.ValidTo__c,Product_Register__r.ValidFrom__c 
+			from Product_Register_Link__c 
+	        where Product_Register__r.Id in : prcList];
+
+	        //瀛樻斁浜у搧鐨刬d鍜岀瓑绾х被鍒瓧娈电殑鍊肩殑闆嗗悎
+	        Map<Id,List<String>> pro2Map = new Map<Id,List<String>>();
+	        if (prlList.size()>0) {
+	            for (Product_Register_Link__c prl: prlList) {
+	                if (pro2Map.containsKey(prl.Product2__r.Id)) {
+	                    pro2Map.get(prl.Product2__r.Id).add(prl.Product_Register__r.MedPrdClass__c);
+	                }else {
+	                    pro2Map.put(prl.Product2__r.Id, new List<String>());
+	                    pro2Map.get(prl.Product2__r.Id).add(prl.Product_Register__r.MedPrdClass__c);
+	                }
+	            }
+	        }
+	        
+	        //瀛樻斁浜у搧id鍜屽瓧绗︿覆鍊�
+	        Map<Id,String> prlMap = new Map<Id,String>();
+	        System.debug('pro2Map='+pro2Map);
+
+	        List<Id> pidList = new List<Id>();
+	        //閫氳繃涓婇潰鐨勫惊鐜紝鎶婂叧绯昏〃杩囪幏鍙栫殑鏁版嵁璇诲嚭鏉ワ紝浼犵粰map
+	        if (pro2Map.size()>0) {
+	            for (Product_Register_Link__c pr: prlList) {
+	            	// && (oldMap.get(pr.Product_Register__r.Id).ValidTo__c != newMap.get(pr.Product_Register__r.Id).ValidTo__c || oldMap.get(pr.Product_Register__r.Id).ValidFrom__c != newMap.get(pr.Product_Register__r.Id).ValidFrom__c)
+	                if (pro2Map.containsKey(pr.Product2__r.Id)) {
+	                	pidList.add(pr.Product2__r.Id);
+	                    //鐢熶骇鏃ユ湡鍦ㄦ敞鍐岃瘉鏈夋晥鏈熷唴鐨勬槸浜岀被锛岀敓浜ф棩鏈熷湪澶囨璇佹湁鏁堟湡鐨勬槸涓�绫伙紝鍓嶆彁涓烘湁鏁堟湡
+	                    // System.debug('pr.Product_Register__r.ValidTo__c='+ pr.Product_Register__r.ValidTo__c);
+	                    // System.debug('pr.Product_Register__r.Level_Category__c='+pr.Product_Register__r.MedPrdClass__c);
+	                    // System.debug('pr.Product2__r.demoteer_Sap__c='+ pr.Product2__r.demoteer_Sap__c);
+                        if (pr.Product2__r.demoteer_Sap__c <= newMap.get(pr.Product_Register__r.Id).ValidTo__c && pr.Product2__r.demoteer_Sap__c >= newMap.get(pr.Product_Register__r.Id).ValidFrom__c
+	                        && (pr.Product_Register__r.MedPrdClass__c == '1')) {
+	                        prlMap.put(pr.Product2__r.Id, '涓�绫�');
+                    	}
+	                    else if (pr.Product2__r.demoteer_Sap__c <= newMap.get(pr.Product_Register__r.Id).ValidTo__c && pr.Product2__r.demoteer_Sap__c >= newMap.get(pr.Product_Register__r.Id).ValidFrom__c
+	                        && pr.Product_Register__r.MedPrdClass__c == '2' || pr.Product_Register__r.MedPrdClass__c == '3') {
+	                    	if (!'涓�绫�'.equals(prlMap.get(pr.Product2__r.Id))){
+	                        prlMap.put(pr.Product2__r.Id, '浜岀被');
+	                    	}
+	                    } 
+	                }
+	                //System.debug('prlMap='+prlMap);
+	            }
+	        }
+
+	        List<Product2> por2Lsit = new List<Product2>();
+	        //鏌ュ嚭浜у搧鐨刬d鍜岀瓑绾х被鍒殑瀛楁 
+	        por2Lsit = [select Id,Level_Category__c from Product2 where Id in : pidList];
+
+	        //List<Product2> ppr2List = new List<Product2>();
+	        //缁欎骇鍝佷笂鐨勭瓑绾х被鍒瓧娈佃祴鍊�
+	        for (Product2 pr2: por2Lsit) {
+	        	//Product2 ppr2;
+	            if (!pro2Map.containsKey(pr2.Id)) {
+	                pr2.Level_Category__c = '闈炵洃绠�';
+	            }else if (prlMap.containsKey(pr2.Id)) {
+	                pr2.Level_Category__c = prlMap.get(pr2.Id);
+	            }else {
+	                pr2.Level_Category__c = null;
+	            }
+	            if (pr2.Level_Category__c != null) {
+	                prt2Map.put(pr2.Id, pr2);
+	            }
+	            //prt2.Id = pr2.Id;
+	            //prt2.Level_Category__c = pr2.Level_Category__c;
+	            //ppr2List.add(ppr2);
+	            //System.debug('ppr2List='+ppr2List);
+	            //System.debug('pr2.Level_Category__c='+pr2.Level_Category__c);
+	        }
+	        update prt2Map.values(); 
+		}
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterHandler.cls-meta.xml b/scr/classes/ProRegisterHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterHandlerTest.cls b/scr/classes/ProRegisterHandlerTest.cls
new file mode 100644
index 0000000..2d2c72f
--- /dev/null
+++ b/scr/classes/ProRegisterHandlerTest.cls
@@ -0,0 +1,191 @@
+@isTest
+public with sharing class ProRegisterHandlerTest {
+
+	static testMethod void Test01() {
+		System.Test.startTest();
+		//ProRegisterHandler prh = new ProRegisterHandler();
+		Product_Register__c PRC = new Product_Register__c();
+		PRC.Name = '鍥芥娉ㄨ繘20183222249';
+		PRC.MedPrdClass__c = '3';
+		PRC.RegisterNoClass_New__c = '';
+		PRC.RegisterNoClass_Old__c = '6822';
+		PRC.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		PRC.ClinicalProductCode__c = 'YYYY';
+		PRC.ValidTo__c = Date.today().addDays(22);
+		PRC.ValidFrom__c = Date.today().addDays(-22);
+		insert PRC;
+
+		Product_Register__c PRC1 = new Product_Register__c();
+		PRC1.Name = '鍥芥娉ㄨ繘20183222249';
+		PRC1.MedPrdClass__c = '3';
+		PRC1.RegisterNoClass_New__c = '';
+		PRC1.RegisterNoClass_Old__c = '6822';
+		PRC1.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		PRC1.ClinicalProductCode__c = 'tttttt';
+		PRC1.ValidTo__c = Date.today().addDays(22);
+		PRC1.ValidFrom__c = Date.today().addDays(-22);
+		insert PRC1;
+
+
+		Product2 product2 = new Product2();
+		product2.Name = 'WD18100A';
+		product2.registrationCode__c = 'XXXX';
+		product2.clinical_product_code__c = 'zzzz';
+		insert product2;
+
+		Product2 pro = new Product2();
+		pro.Name = 'A00507A:瀵嗗皝鍦�,  閫忔槑, 榛戣壊';
+		pro.clinical_product_code__c = 'yyyyy';
+		insert pro;
+
+		Product_Register_Link__c prl = new Product_Register_Link__c();
+		prl.Product2__c = pro.ID;
+		prl.Product_Register__c = PRC.ID;
+		insert prl;
+		Product_Register_Link__c prl2 = new Product_Register_Link__c();
+		prl2.Product2__c = pro.ID;
+		prl2.Product_Register__c = PRC1.ID;
+		insert prl2;
+
+		update PRC;
+
+		System.Test.stopTest();
+	}
+
+	static testMethod void Test02() {
+		System.Test.startTest();
+		Product_Register__c PRC = new Product_Register__c();
+		PRC.Name = '鍥芥娉ㄨ繘20183222249';
+		PRC.MedPrdClass__c = '3';
+		PRC.RegisterNoClass_New__c = '';
+		PRC.RegisterNoClass_Old__c = '6822';
+		PRC.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		//PRC.ValidTo__c = Date.today();
+		PRC.ValidTo__c = Date.today().addDays(22);
+		PRC.ValidFrom__c = Date.today().addDays(-22);
+		insert PRC;
+
+
+		Product2 product2 = new Product2();
+		product2.Name = 'WD18100A';
+		product2.clinical_product_code__c = 'zzzz';
+		insert product2;
+
+		Product2 pro = new Product2();
+		pro.Name = 'A00507A:瀵嗗皝鍦�,  閫忔槑, 榛戣壊';
+		pro.clinical_product_code__c = 'zzzz';
+
+		insert pro;
+
+		Product_Register_Link__c prl = new Product_Register_Link__c();
+		prl.Product2__c = pro.ID;
+		prl.Product_Register__c = PRC.ID;
+		insert prl;
+		//ProRegisterHandler prh = new ProRegisterHandler();
+		update PRC;
+
+		System.Test.stopTest();
+	}
+
+	@isTest static void test_checkProduct2Level() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c      = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        prd.Level_Category__c      = '';
+        prd.demoteer_Sap__c        = Date.today();
+        insert prd;
+
+        Product_Register__c PRC = new Product_Register__c();
+        PRC.Name                   = '鍥芥娉ㄨ繘20183222249';
+        PRC.MedPrdClass__c         = '1';
+        PRC.RegisterNoClass_New__c = '';
+        PRC.RegisterNoClass_Old__c = '6822';
+        PRC.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+        PRC.ClinicalProductCode__c = 'YYYY';
+        PRC.ValidTo__c = Date.today().addDays(22);
+        PRC.ValidFrom__c = Date.today().addDays(-22);
+        insert PRC;
+
+        Product_Register_Link__c prl = new Product_Register_Link__c();
+        prl.Product2__c = prd.ID;
+        prl.Product_Register__c = PRC.ID;
+        insert prl;
+
+        PRC.ValidTo__c = Date.today().addDays(21);
+        PRC.ValidFrom__c = Date.today().addDays(-21);
+        update PRC;
+
+        prd.Name                   = 'hehe';
+        update prd;
+    }
+
+    @isTest static void test_checkProduct2Level1() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c      = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        prd.Level_Category__c      = '';
+        prd.demoteer_Sap__c        = Date.today();
+        insert prd;
+
+        Product_Register__c PRC = new Product_Register__c();
+        PRC.Name                   = '鍥芥娉ㄨ繘20183222249';
+        PRC.MedPrdClass__c         = '2';
+        PRC.RegisterNoClass_New__c = '';
+        PRC.RegisterNoClass_Old__c = '6822';
+        PRC.PrdCompanyAddr__c      = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+        PRC.ClinicalProductCode__c = 'YYYY';
+        PRC.ValidTo__c             = Date.today().addDays(22);
+        PRC.ValidFrom__c           = Date.today().addDays(-22);
+        insert PRC;
+
+        Product_Register_Link__c prl = new Product_Register_Link__c();
+        prl.Product2__c              = prd.ID;
+        prl.Product_Register__c      = PRC.ID;
+        insert prl;
+
+        PRC.ValidTo__c   = Date.today().addDays(21);
+        PRC.ValidFrom__c = Date.today().addDays(-21);
+        update PRC;
+
+        prd.Name                   = 'hehe1';
+        update prd;
+    }
+
+    @isTest static void test_checkProduct2Level2() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c      = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        prd.Level_Category__c      = '';
+        prd.demoteer_Sap__c        = Date.today();
+        insert prd;
+
+        Product_Register__c PRC = new Product_Register__c();
+        PRC.Name                   = '鍥芥娉ㄨ繘20183222249';
+        PRC.MedPrdClass__c         = '';
+        PRC.RegisterNoClass_New__c = '';
+        PRC.RegisterNoClass_Old__c = '6822';
+        PRC.PrdCompanyAddr__c      = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+        PRC.ClinicalProductCode__c = 'YYYY';
+        PRC.ValidTo__c             = Date.today().addDays(22);
+        PRC.ValidFrom__c           = Date.today().addDays(-22);
+        insert PRC;
+
+        Product_Register_Link__c prl = new Product_Register_Link__c();
+        prl.Product2__c              = prd.ID;
+        prl.Product_Register__c      = PRC.ID;
+        insert prl;
+
+        PRC.ValidTo__c   = Date.today().addDays(21);
+        PRC.ValidFrom__c = Date.today().addDays(-21);
+        update PRC;
+
+        prd.Name                   = 'hehe2';
+        update prd;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterHandlerTest.cls-meta.xml b/scr/classes/ProRegisterHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterLinkHandler.cls b/scr/classes/ProRegisterLinkHandler.cls
new file mode 100644
index 0000000..8e0744e
--- /dev/null
+++ b/scr/classes/ProRegisterLinkHandler.cls
@@ -0,0 +1,107 @@
+public without sharing class ProRegisterLinkHandler {
+	/* 鏇存柊浜у搧鍐呮渶鏂颁骇鍝佸湪娉ㄥ唽璇�
+	   1.鏍规嵁浜у搧-娉ㄥ唽璇佸叧绯绘壘鍑烘墍鏈夊搴旂殑浜у搧
+	   2.鏍规嵁浜у搧鎵惧嚭鍏舵墍闇�鏈�鏂颁骇鍝佹敞鍐岃瘉
+	  */
+	public static void updateProduct(List<Product_Register_Link__c> newList, Map<Id, Product_Register_Link__c> newMap, List<Product_Register_Link__c> oldList, Map<Id, Product_Register_Link__c> oldMap, string HandleType) {
+		// 浜у搧-娉ㄥ唽璇佸叧绯� 涓墍鏈� 浜у搧ID
+		list<ID> Product2_ID_list = new list<ID>();
+		// 鐜版湁浜у搧 map
+		map<ID, Product2> Exist_ProductMap = new map<ID, Product2>();
+		// 闇�瑕佹洿鏂颁骇鍝� list
+		List<Product2> UpdateProductlist = new list<Product2>();
+
+		List<Product_Register_Link__c> currentList = new List<Product_Register_Link__c>();
+
+		if ('1'.equals(HandleType)) {
+			currentList = newList;
+		} else {
+			currentList = oldList;
+		}
+
+		for (Product_Register_Link__c PRL : currentList) {
+			Product2_ID_list.add(PRL.Product2__c);
+		}
+
+		Exist_ProductMap = new map<ID, Product2>([select ID, registrationCode__c, clinical_product_code__c from Product2 where id in: Product2_ID_list]);
+		List<Product_Register_Link__c> allPRLList = new List<Product_Register_Link__c>();
+
+		allPRLList = [select  Product2__c,
+		              Product_Register__c,
+		              Product_Register__r.PrdCompanyAddr__c,
+		              Product_Register__r.ValidFrom__c,
+		              Product_Register__r.ValidTo__c,
+		              Product_Register__r.name,
+		              Product_Register__r.ValidProductRegister__c,
+		              Product_Register__r.ClinicalProductCode__c
+		              from Product_Register_Link__c
+		              where Product2__c  in : Product2_ID_list
+		              order by Product2__c,
+		              LastModifiedDate desc
+		             ];
+
+		String tmpProductID = '';
+		Map<ID, Product2> Upd_ProductMap = new Map<ID, Product2>();
+		Product2 temProduct = new Product2();
+
+		for (String ProId : Product2_ID_list) {
+			temProduct = Exist_ProductMap.get(ProId);
+			Upd_ProductMap.put(ProId, temProduct);
+		}
+
+		for (Product_Register_Link__c temPRL : allPRLList) {
+			if (!tmpProductID.equals(temPRL.Product2__c)) {
+				tmpProductID = temPRL.Product2__c;
+				temProduct = Upd_ProductMap.get(tmpProductID);
+				temProduct.Register_Latest__c = temPRL.Product_Register__c;                    // 鏈�鏂版敞鍐岃瘉ID
+				temProduct.registrationCode__c = null;
+				temProduct.clinical_product_code__c = null;
+			}
+			//// 濡傛灉娉ㄥ唽璇佺姸鎬佹湁鏁�,璁板綍鏈夋晥娉ㄥ唽璇佸彿
+			if (temPRL.Product_Register__r.ValidProductRegister__c) {
+				if (String.isBlank(temProduct.registrationCode__c)) {
+					temProduct.registrationCode__c = temPRL.Product_Register__r.Name + '\n';
+				} else {
+					if (String.isNotBlank(temPRL.Product_Register__r.Name)) {
+						if (temProduct.registrationCode__c.indexOf(temPRL.Product_Register__r.Name) == -1) {
+							temProduct.registrationCode__c += temPRL.Product_Register__r.Name + '\n';
+						}
+					}
+				}
+				String clinicalCode = temPRL.Product_Register__r.ClinicalProductCode__c;
+				if (String.isBlank(temProduct.clinical_product_code__c)) {
+					temProduct.clinical_product_code__c = clinicalCode;//temPRL.Product_Register__r.ClinicalProductCode__c;
+				} else {
+
+					if (String.isNotBlank(clinicalCode)) {
+
+						Map<String, String> codeMap = new Map<String, String>();
+						for (String code : temProduct.clinical_product_code__c.split('/')) {
+							codeMap.put(code, code);
+						}
+						codeMap.put(clinicalCode, clinicalCode);
+						temProduct.clinical_product_code__c = '';
+						for (String code : codeMap.values()) {
+							if (String.isBlank(temProduct.clinical_product_code__c)) {
+								temProduct.clinical_product_code__c = code;
+							} else {
+								temProduct.clinical_product_code__c += '/' + code;
+							}
+						}
+						
+					}
+
+				}
+			}
+
+
+			Upd_ProductMap.put(tmpProductID, temProduct);
+		}
+
+		if (Upd_ProductMap.keySet().size() > 0)  {
+			update Upd_ProductMap.values();
+		}
+
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterLinkHandler.cls-meta.xml b/scr/classes/ProRegisterLinkHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterLinkHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ProRegisterLinkHandlerTest.cls b/scr/classes/ProRegisterLinkHandlerTest.cls
new file mode 100644
index 0000000..487966f
--- /dev/null
+++ b/scr/classes/ProRegisterLinkHandlerTest.cls
@@ -0,0 +1,97 @@
+@isTest
+public with sharing class ProRegisterLinkHandlerTest {
+
+	static testMethod void AfterInsert() {
+		Product_Register__c prorec = new Product_Register__c();
+		prorec.Name = 'SFDCTEST2018001';
+		prorec.MedPrdClass__c = '3';
+		prorec.RegisterNoClass_New__c = '';
+		prorec.RegisterNoClass_Old__c = '6822';
+		prorec.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		prorec.ValidTo__c = Date.today().addDays(22);
+		prorec.ValidFrom__c = Date.today().addDays(-22);
+		insert prorec;
+
+		Product2 product2 = new Product2();
+		product2.Name = 'WD18100A';
+		insert product2;
+
+		Product2 pro = new Product2();
+		pro.Name = 'A00507A:瀵嗗皝鍦�,  閫忔槑, 榛戣壊';
+		insert pro;
+
+		Product_Register_Link__c prl = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl.Product2__c = pro.ID;
+		insert prl;
+
+		System.Test.startTest();
+		Product_Register_Link__c prl001 = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl001.Product2__c = pro.ID;
+		insert prl001;
+
+		System.Test.stopTest();
+	}
+
+	static testMethod void AfterUpdate() {
+		Product_Register__c prorec = new Product_Register__c();
+		prorec.Name = 'SFDCTEST2018001';
+		prorec.MedPrdClass__c = '3';
+		prorec.RegisterNoClass_New__c = '';
+		prorec.RegisterNoClass_Old__c = '6822';
+		prorec.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		prorec.ValidTo__c = Date.today().addDays(22);
+		prorec.ValidFrom__c = Date.today().addDays(-22);
+		insert prorec;
+
+		Product2 product2 = new Product2();
+		product2.Name = 'WD18100A';
+		insert product2;
+
+		Product2 pro = new Product2();
+		pro.Name = 'A00507A:瀵嗗皝鍦�,  閫忔槑, 榛戣壊';
+		insert pro;
+
+		Product_Register_Link__c prl = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl.Product2__c = pro.ID;
+		insert prl;
+
+		System.Test.startTest();
+		Product_Register_Link__c prl001 = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl001.Product2__c = pro.ID;
+		insert prl001;
+		update prl001;
+		System.Test.stopTest();
+	}
+
+	static testMethod void AfterDelete() {
+		Product_Register__c prorec = new Product_Register__c();
+		prorec.Name = 'SFDCTEST2018001';
+		prorec.MedPrdClass__c = '3';
+		prorec.RegisterNoClass_New__c = '';
+		prorec.RegisterNoClass_Old__c = '6822';
+		prorec.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+		prorec.ValidTo__c = Date.today().addDays(22);
+		prorec.ValidFrom__c = Date.today().addDays(-22);
+		insert prorec;
+
+
+		Product2 product2 = new Product2();
+		product2.Name = 'WD18100A';
+		insert product2;
+
+
+		Product2 pro = new Product2();
+		pro.Name = 'A00507A:瀵嗗皝鍦�,  閫忔槑, 榛戣壊';
+		insert pro;
+		Product_Register_Link__c prl = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl.Product2__c = pro.ID;
+		insert prl;
+
+		System.Test.startTest();
+		Product_Register_Link__c prl001 = new Product_Register_Link__c(Product_Register__c = prorec.ID);
+		prl001.Product2__c =  pro.ID;
+		insert prl001;
+		delete prl001;
+		System.Test.stopTest();
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/ProRegisterLinkHandlerTest.cls-meta.xml b/scr/classes/ProRegisterLinkHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ProRegisterLinkHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/Product2TriggerHandler.cls b/scr/classes/Product2TriggerHandler.cls
new file mode 100644
index 0000000..eb132ba
--- /dev/null
+++ b/scr/classes/Product2TriggerHandler.cls
@@ -0,0 +1,122 @@
+public without sharing class Product2TriggerHandler {
+
+    public static void upsertProductSearch(List<Product2> newList, Map<Id, Product2> newMap, List<Product2> oldList, Map<Id, Product2> oldMap) 
+    {
+        if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate))
+        {
+            List<String> p2ids = new List<String>();
+            for(Product2 p2 : newList)
+            {
+                p2ids.add(p2.id);
+            }
+            
+            List<Product_Search__c> ps = [select Id,Name,CurrencyIsoCode,Product__c From Product_Search__c Where Product__c in: p2ids];
+            Map <String,Product_Search__c> psmap = new Map<String,Product_Search__c>();
+            List<Product_Search__c> pss = new List<Product_Search__c>();
+            for(Product_Search__c p : ps)
+            {
+                psmap.put(p.Product__c,p);
+            }
+            
+            for(Product2 p2 : newList)
+            {
+                Product_Search__c p2s;
+                if(psmap.containsKey(p2.id))
+                {
+                    p2s = psmap.get(p2.id);
+                }
+                else
+                {
+                    p2s = new Product_Search__c();
+                }
+                
+                p2s.Name =  p2.Name;
+                p2s.Product__c = p2.id;
+                p2s.CurrencyIsoCode = p2.CurrencyIsoCode;
+                pss.add(p2s);
+            }
+            System.debug('psssize' + pss.size());
+            upsert(pss);  
+        }else if(Trigger.isDelete)
+       {
+           for(Product2 en : newList)
+           {
+                 en.addError('姝ゆ暟鎹笉鑳藉垹闄�');
+           }
+       }
+    }
+
+    public static void checkProduct2Level(List<Product2> newList, Map<Id, Product2> newMap, List<Product2> oldList, Map<Id, Product2> oldMap) {
+        if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)){
+            List<String> p2ids = new List<String>();
+            for(Product2 p2 : newList)
+            {
+                p2ids.add(p2.id);
+            }
+
+            //瀛樻斁鏌ユ壘鐨剆oql鏂�
+            List<Product_Register_Link__c> pro2List = new List<Product_Register_Link__c>();
+            pro2List = [select Product2__r.id,Product2__r.demoteer_Sap__c,Product_Register__r.MedPrdClass__c,Product_Register__r.ValidTo__c,Product_Register__r.ValidFrom__c 
+            from Product_Register_Link__c 
+            where Product2__r.Id in : p2ids];
+            System.debug('pro2List='+pro2List);
+            //瀛樻斁浜у搧鐨刬d鍜岀瓑绾х被鍒瓧娈电殑鍊肩殑闆嗗悎
+            Map<Id,List<String>> pro2Map = new Map<Id,List<String>>();
+            if (pro2List.size()>0) {
+                for (Product_Register_Link__c prl: pro2List) {
+                    if (pro2Map.containsKey(prl.Product2__r.Id)) {
+                        pro2Map.get(prl.Product2__r.Id).add(prl.Product_Register__r.MedPrdClass__c);
+                    }else {
+                        pro2Map.put(prl.Product2__r.Id, new List<String>());
+                        pro2Map.get(prl.Product2__r.Id).add(prl.Product_Register__r.MedPrdClass__c);
+                    }
+                }
+            }
+            
+            //瀛樻斁浜у搧id鍜屽瓧绗︿覆鍊�
+            Map<Id,String> prlMap = new Map<Id,String>();
+            System.debug('pro2Map='+pro2Map);
+
+            //閫氳繃涓婇潰鐨勫惊鐜紝鎶婂叧绯昏〃杩囪幏鍙栫殑鏁版嵁璇诲嚭鏉ワ紝浼犵粰map
+            if (pro2Map.size()>0) {
+                for (Product_Register_Link__c pr: pro2List) {
+                    if (pro2Map.containsKey(pr.Product2__r.Id)) {
+                        if (newMap.get(pr.Product2__r.Id).demoteer_Sap__c <> null) {
+                            //鐢熶骇鏃ユ湡鍦ㄦ敞鍐岃瘉鏈夋晥鏈熷唴鐨勬槸浜岀被锛岀敓浜ф棩鏈熷湪澶囨璇佹湁鏁堟湡鐨勬槸涓�绫伙紝鍓嶆彁涓烘湁鏁堟湡
+                            //System.debug('pr.Product_Register__r.ValidTo__c='+ pr.Product_Register__r.ValidTo__c);
+                            //System.debug('pr.Product_Register__r.MedPrdClass__c='+pr.Product_Register__r.MedPrdClass__c);
+                            if (newMap.get(pr.Product2__r.Id).demoteer_Sap__c <= pr.Product_Register__r.ValidTo__c && newMap.get(pr.Product2__r.Id).demoteer_Sap__c >= pr.Product_Register__r.ValidFrom__c
+                                && (pr.Product_Register__r.MedPrdClass__c == '1')) {
+                                prlMap.put(pr.Product2__r.Id, '涓�绫�');
+                            }
+                            else if (newMap.get(pr.Product2__r.Id).demoteer_Sap__c <= pr.Product_Register__r.ValidTo__c && newMap.get(pr.Product2__r.Id).demoteer_Sap__c >= pr.Product_Register__r.ValidFrom__c
+                                && pr.Product_Register__r.MedPrdClass__c == '2' || pr.Product_Register__r.MedPrdClass__c == '3') {
+                                if (!'涓�绫�'.equals(prlMap.get(pr.Product2__r.Id))){
+                                    prlMap.put(pr.Product2__r.Id, '浜岀被');
+                                }
+                            }
+                        }
+                    }
+                    System.debug('prlMap='+prlMap);
+                }
+            }
+
+            //缁欎骇鍝佷笂鐨勭瓑绾х被鍒瓧娈佃祴鍊�
+            for (Product2 pr2: newList) {
+                 System.debug('pr2.demoteer_Sap__c='+pr2.demoteer_Sap__c);
+                if (!pro2Map.containsKey(pr2.Id)) {
+                    //閬垮厤浠巗ap浼犳潵鐨勬椂闂村彇娑堜簡锛岀瓑绾х被鍒瓧娈典笂杩樻湁鍊艰繖涓�璇�
+                    if (pr2.demoteer_Sap__c == null) {
+                        pr2.Level_Category__c = null;
+                    }else{
+                        pr2.Level_Category__c = '闈炵洃绠�';
+                    }
+                }else{
+                //else if (prlMap.containsKey(pr2.Id)) {
+                    pr2.Level_Category__c = prlMap.get(pr2.Id);
+                }
+                System.debug('pr2.Level_Category__c='+pr2.Level_Category__c);
+            }
+        }
+    }     
+}
\ No newline at end of file
diff --git a/scr/classes/Product2TriggerHandler.cls-meta.xml b/scr/classes/Product2TriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/Product2TriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/Product2TriggerHandlerTest.cls b/scr/classes/Product2TriggerHandlerTest.cls
new file mode 100644
index 0000000..4bb1f35
--- /dev/null
+++ b/scr/classes/Product2TriggerHandlerTest.cls
@@ -0,0 +1,105 @@
+@isTest
+private class Product2TriggerHandlerTest {
+
+    @isTest static void test_Product2TriggerHandler() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        insert prd;  
+        //Pricebook2 prdbook     = new Pricebook2();
+        List<Product2> pp = [Select Id,Name From Product2];
+        System.assertEquals(pp.size(),1);
+
+        prd.Name = 'tttt';
+        update prd;
+        List<Product2> p2 = [Select Id,Name From Product2];
+        System.assertEquals(p2[0].Name,'tttt');
+
+        List<Product_Search__c> ss = [Select Id,Name From Product_Search__c];
+        System.assertEquals(ss.size(),1);
+    }
+
+    @isTest static void test_checkProduct2Level() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c      = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        prd.Level_Category__c      = '';
+        prd.demoteer_Sap__c        = Date.today();
+        insert prd;
+
+        Product_Register__c PRC = new Product_Register__c();
+        PRC.Name                   = '鍥芥娉ㄨ繘20183222249';
+        PRC.MedPrdClass__c         = '1';
+        PRC.RegisterNoClass_New__c = '';
+        PRC.RegisterNoClass_Old__c = '6822';
+        PRC.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+        PRC.ClinicalProductCode__c = 'YYYY';
+        PRC.ValidTo__c = Date.today().addDays(22);
+        PRC.ValidFrom__c = Date.today().addDays(-22);
+        insert PRC;
+
+        Product_Register_Link__c prl = new Product_Register_Link__c();
+        prl.Product2__c = prd.ID;
+        prl.Product_Register__c = PRC.ID;
+        insert prl;
+    }
+
+    @isTest static void test_checkProduct2Level1() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c      = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        prd.Level_Category__c      = '';
+        prd.demoteer_Sap__c        = Date.today();
+        insert prd;
+
+        Product_Register__c PRC = new Product_Register__c();
+        PRC.Name                   = '鍥芥娉ㄨ繘20183222249';
+        PRC.MedPrdClass__c         = '2';
+        PRC.RegisterNoClass_New__c = '';
+        PRC.RegisterNoClass_Old__c = '6822';
+        PRC.PrdCompanyAddr__c = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+        PRC.ClinicalProductCode__c = 'YYYY';
+        PRC.ValidTo__c             = Date.today().addDays(22);
+        PRC.ValidFrom__c           = Date.today().addDays(-22);
+        insert PRC;
+
+        Product_Register_Link__c prl = new Product_Register_Link__c();
+        prl.Product2__c              = prd.ID;
+        prl.Product_Register__c      = PRC.ID;
+        insert prl;
+    }
+
+    @isTest static void test_checkProduct2Level2() {
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c      = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        prd.Level_Category__c      = '';
+        prd.demoteer_Sap__c        = Date.today();
+        insert prd;
+
+        Product_Register__c PRC = new Product_Register__c();
+        PRC.Name                   = '鍥芥娉ㄨ繘20183222249';
+        PRC.MedPrdClass__c         = '';
+        PRC.RegisterNoClass_New__c = '';
+        PRC.RegisterNoClass_Old__c = '6822';
+        PRC.PrdCompanyAddr__c      = '鍚嶇О:濂ユ灄宸存柉鍖荤枟鏍紡浼氱ぞ;浣忔墍:鏃ユ湰鍥戒笢浜兘娑╄胺鍖哄埂涔嬭胺浜屼竵鐩�43鐣湴2鍙�;鑱旂郴鏂瑰紡:0081-426-42-2667';
+        PRC.ClinicalProductCode__c = 'YYYY';
+        PRC.ValidTo__c             = Date.today().addDays(22);
+        PRC.ValidFrom__c           = Date.today().addDays(-22);
+        insert PRC;
+
+        Product_Register_Link__c prl = new Product_Register_Link__c();
+        prl.Product2__c              = prd.ID;
+        prl.Product_Register__c      = PRC.ID;
+        insert prl;
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/Product2TriggerHandlerTest.cls-meta.xml b/scr/classes/Product2TriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/Product2TriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/PrototypeToThaw.cls b/scr/classes/PrototypeToThaw.cls
new file mode 100644
index 0000000..4e1e614
--- /dev/null
+++ b/scr/classes/PrototypeToThaw.cls
@@ -0,0 +1,134 @@
+global class PrototypeToThaw {
+
+	/**
+	 * 鏍锋満鐢宠鑰呰嚜鍔ㄨВ鍐�
+	 * @Author   XHL
+	 * @DateTime 2020-02-26
+	 * @param    loanerId   鏍锋満鍊熺敤鐢宠Id
+	 */
+	public static void UserUnfreeze(String loanerId) {
+
+		Map<String, String> userIdViolationIdMap = new Map<String, String>();
+		//鏌ユ壘鏍锋満鍊熺敤鐢宠鐩稿叧鐨�"鏍锋満鐢ㄦ埛杩濊淇℃伅"
+		List<User_Violations__c> ulList = [select id, Violations_User__c, Violations_reason__c
+		                                   from User_Violations__c
+		                                   where Is_effective__c = true and Violations_reason__c = '瓒呮湡鏈綊杩�'
+		                                           and Violations_Loaner__c  = :loanerId];
+		if ( ulList.size() > 0) {
+			for (User_Violations__c violation : ulList) {
+				userIdViolationIdMap.put(violation.Violations_User__c, violation.Id);
+			}
+		}
+
+		if (userIdViolationIdMap.size() > 0) {
+
+			Map<String, Map<String, Integer>> userIdReasonQuantityMap = new Map<String, Map<String, Integer>>();
+			Map<String, Integer> reasonQuantityMap = new Map<String, Integer>();
+			//鐢ㄦ埛鐨�"鏍锋満鐢ㄦ埛杩濊淇℃伅"
+			ulList = [SELECT Id, Is_effective__c, Violations_User__c, Is_locking__c, Violations_reason__c,is_Alone__c
+			          FROM User_Violations__c
+			          WHERE Violations_User__c in :userIdViolationIdMap.keySet() AND Is_effective__c = true];
+			if (ulList.size() > 0) {
+				Map<String,User_Violations__c> upsertUserViolationsMap = new Map<String,User_Violations__c>();
+				String userId = '';
+				for (User_Violations__c violation : ulList) {
+					userId = violation.Violations_User__c;
+					//鍒ゆ柇鏄惁涓庡綋鍓�"鏍锋満鍊熺敤鐢宠"鐨�"鏍锋満鐢ㄦ埛杩濊淇℃伅"鐩稿悓
+					if (userIdViolationIdMap.get(userId) != violation.Id) {
+						//涓嶅悓鈫掔粺璁℃牱鏈哄�熺敤鐨勭敤鎴峰叾浠栬繚瑙勪俊鎭殑鏁伴噺
+						String key = userId + ';' + violation.Id + ';' + violation.Violations_reason__c;
+						if (!userIdReasonQuantityMap.containsKey(userId)) {
+							reasonQuantityMap.put(key, 1);
+							userIdReasonQuantityMap.put(userId, reasonQuantityMap);
+
+						} else {
+							if (!reasonQuantityMap.containsKey(key)) {
+								reasonQuantityMap.put(key, 1);
+							} else {
+								reasonQuantityMap.put(key, reasonQuantityMap.get(key) + 1);
+							}
+							userIdReasonQuantityMap.put(userId, reasonQuantityMap);
+						}
+					} else {
+						//鐩稿悓鈫掑皢褰撳墠鐨�"鏍锋満鐢ㄦ埛杩濊淇℃伅"璁剧疆涓烘棤鏁�
+						upsertUserViolationsMap.put(violation.Id,violation);
+						violation.Is_effective__c = false;
+						if (violation.Is_locking__c == true) {
+							violation.Is_locking__c = false;
+							violation.Violations_Stop_Date__c = Date.today();
+							violation.is_Alone__c = true;
+						}
+					}
+				}
+
+				if (userIdReasonQuantityMap.size() > 0) {
+
+					List<User> userList = [SELECT Id, ViolationsID__c FROM User WHERE Id in :userIdReasonQuantityMap.keySet()];
+					if (userList.size() > 0 && userList != null) {
+						Map<String,Integer> reasonMap = new Map<String,Integer>();
+						for (User user : userList) {
+							for (String keys : userIdReasonQuantityMap.get(user.Id).keySet()) {
+								List<String> keyList =  keys.split(';');
+								//鍒ゆ柇鍓╀綑鐨�"鏍锋満鐢ㄦ埛杩濊淇℃伅"鐨勬暟閲忔槸鍚﹀ぇ浜庢垨绛変簬1
+								if (userIdReasonQuantityMap.get(user.Id).size() >= 1) {
+									//鍒ゆ柇鐢ㄦ埛鐨�"鍐荤粨淇℃伅Id"鏄惁涓�"鏍锋満鍊熺敤鐢宠"鐨�"鏍锋満鐢ㄦ埛杩濊淇℃伅"鐩稿悓
+									if (userIdViolationIdMap.get(user.Id) == user.ViolationsID__c) {
+
+										user.ViolationsID__c = keyList[1];
+										User_Violations__c uViolations = new User_Violations__c();
+										uViolations.Id = keyList[1];
+										uViolations.Is_locking__c = true;
+										uViolations.Locking_Start_Date__c = date.today();
+										upsertUserViolationsMap.put(keyList[1],uViolations);
+									}
+								} else {
+									user.ViolationsID__c = null;
+								}
+
+								//缁熻杩濊绫诲瀷鏁伴噺
+								if (!reasonMap.containsKey(keyList[2]) && '瓒呮湡鏈綊杩�'.equals(keyList[2])) {
+									reasonMap.put(keyList[2],1);
+									user.Return_Timeout_Number__c = 1;
+								} else if ('瓒呮湡鏈綊杩�'.equals(keyList[2])){
+									user.Return_Timeout_Number__c += 1;
+								} else if (!reasonMap.containsKey(keyList[2]) && '绯荤粺鑷姩鏀惰揣'.equals(keyList[2])) {
+									reasonMap.put(keyList[2],1);
+									user.Automatic_Received_Number__c = 1;
+								} else if ('绯荤粺鑷姩鏀惰揣'.equals(keyList[2])){
+									user.Automatic_Received_Number__c += 1;
+								}
+							}
+							//2020-05-08 AddStart
+							//褰撹繚瑙勭被鍨�"瓒呮湡鏈綊杩�"涓嶅瓨鍦ㄦ椂锛岀敤鎴风殑"瓒呮湡鏈綊杩樻鏁�"瀛楁缃负0
+							if ( reasonMap.size() > 0) {
+								if (!reasonMap.containsKey('瓒呮湡鏈綊杩�')) {
+									user.Return_Timeout_Number__c = 0;
+								} 
+							}
+							//2020-05-08 AddEnd
+						}
+
+
+						update userList;
+					}
+
+				} else {
+					if (String.isNotBlank(userId)) {
+						User user = new User();
+						user.Id = userId;
+						user.Return_Timeout_Number__c = 0;
+						user.ViolationsID__c = null;
+						update user;
+					}
+				}
+
+				if ( upsertUserViolationsMap.size() > 0 && upsertUserViolationsMap != null) {
+					upsert upsertUserViolationsMap.values();
+				}
+				//upsert ulList;
+			}
+
+
+		}
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/PrototypeToThaw.cls-meta.xml b/scr/classes/PrototypeToThaw.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/PrototypeToThaw.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuoteLineItemTriggerHandler.cls b/scr/classes/QuoteLineItemTriggerHandler.cls
new file mode 100644
index 0000000..9a77a12
--- /dev/null
+++ b/scr/classes/QuoteLineItemTriggerHandler.cls
@@ -0,0 +1,26 @@
+public with sharing class QuoteLineItemTriggerHandler {
+	//XHL-20190513-AddStart
+    public static void SetOpportunityLineItem(List<QuoteLineItem> newList, Map<Id, QuoteLineItem> newMap, List<QuoteLineItem> oldList, Map<Id, QuoteLineItem> oldMap){
+    	String singleProduct  = System.Label.SingleProduct;
+    	List<QuoteLineItem> quoteLineItemList = new List<QuoteLineItem>();
+        //褰撳湪璇环椤甸潰娣诲姞璇环琛岄」鐩椂锛岀敓鎴愭姤浠疯椤圭洰瀵瑰簲瀛楁鐨勮祴鍊�
+        for (QuoteLineItem qli : newList) {
+            
+            if (qli.SingleProduct__c) {
+
+            	QuoteLineItem quoteLineItem = new QuoteLineItem();
+            	quoteLineItem.Id =  qli.Id;
+            	quoteLineItem.Set__c = singleProduct;
+            	quoteLineItemList.add(quoteLineItem);	
+            }
+        }
+
+        if (quoteLineItemList.size() > 0) {
+        	update quoteLineItemList;
+        }
+    }
+    //XHL-20190513-AddEnd
+
+
+    
+}
\ No newline at end of file
diff --git a/scr/classes/QuoteLineItemTriggerHandler.cls-meta.xml b/scr/classes/QuoteLineItemTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/QuoteLineItemTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuotePDFController.cls b/scr/classes/QuotePDFController.cls
new file mode 100644
index 0000000..9651bb6
--- /dev/null
+++ b/scr/classes/QuotePDFController.cls
@@ -0,0 +1,392 @@
+public with sharing class QuotePDFController {
+    public QuoteInfo quoteInfo {get; private set;}
+    public List<SetInfo> printRecords {get; private set;}
+    public Integer pageCnt {get; private set;}
+    public String isPrintPrice {get; private set;}
+    public String currencyIsoCode {get; private set;}
+
+    public boolean is_hidden_user { get; set; }
+    public boolean is_dealer_user { get; set; }
+
+    private String targetId;
+    private Integer maxLine = 10;
+
+    private static Map<String, String> paymentTermsMap = new Map<String, String> {
+        'Z001' => '棰勬敹娆�/棰勪粯娆�',
+        'Z002' => '绔嬪嵆浠樻',
+        'Z003' => '鏈堢粨30澶╁唴浠樻',
+        'Z004' => '鏈堢粨60澶╁唴浠樻',
+        'Z005' => '鏈堢粨90澶╁唴浠樻',
+        'Z006' => '鏈堢粨120澶╁唴浠樻',
+        'Z007' => '鏈堢粨25澶╁唴浠樻',
+        'Z008' => '鏈堢粨55澶╁唴浠樻',
+        'Z009' => '鏈堢粨85澶╁唴浠樻',
+        'Z010' => '鏈堢粨115澶╁唴浠樻',
+        'Z011' => '鏈堢粨175澶╁唴浠樻',
+        'Z012' => '鏈堢粨205澶╁唴浠樻',
+        'Z013' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'Z014' => '鏈堢粨30澶╁唴浠樻',
+        'Z015' => '楠屾敹鍚�15澶╃數姹�',
+        'Z020' => '100%鍙戣揣鍚�30澶╁唴鏀粯',
+        'Z021' => '100%鍙戣揣鍚�60澶╁唴鐢垫眹鏀粯',
+        'Z030' => '鏀跺埌鍙戠エ鍚�30澶╁唴鐢垫眹',
+        'Z045' => '鏈堢粨45澶╁唴浠樻',
+        'Z060' => '鏀跺埌鍙戠エ鍚�60澶╁唴鐢垫眹',
+        'Z075' => '鏀跺埌鍙戠エ鍚�75澶╁唴鐢垫眹',
+        'Z090' => '鏀跺埌鍙戠エ鍚�90澶╁唴鐢垫眹',
+        'Z0LC' => '100% L/C (90/10)',
+        'Z120' => '鏀跺埌鍙戠エ鍚�120澶╁唴鐢垫眹',
+        'Z1LC' => '100% L/C (80/20)',
+        'Z1TT' => '90%TT ADV锛�10%TT AFTER',
+        'Z2LC' => '100% L/C (70/30)',
+        'Z2TT' => '80%TT ADV锛�20%TT AFTER',
+        'Z30E' => '涓嬫湀鏈�',
+        'Z3LC' => '100% L/C 90 days',
+        'Z3TT' => '70%TT ADV锛�30%TT AFTER',
+        'Z4LC' => '90%L/CTransfer 10%TT AFTER',
+        'Z4TT' => '100% TT AFTER',
+        'Z5LC' => '100%L/C at sight Transfer',
+        'Z5TT' => '30% TT ADV锛�50% TT AT SIGHT锛�20% TT AFTER',
+        'Z60E' => '涓�2涓湀鏈�',
+        'Z6LC' => '100%L/C (85/15)',
+        'Z6TT' => '30% TT ADV锛�60% TT AT SIGHT锛�10% TT AFTER',
+        'Z7LC' => '100% L/C (60/40)',
+        'Z7TT' => '100锛匱T AFTER(80/20)',
+        'Z8TT' => '100% TT AFTER锛�70/30锛�',
+        'Z9TT' => '100%TT鍙戣揣鍚�20澶╁唴鏀粯',
+        'ZCOD' => 'C.O.D.',
+        'ZD60' => '绔嬪嵆搴斾粯鐨� 鍒版湡鍑�鍊�',
+        'ZFR1' => '鍗婃湀缁擄紝15鏃ヤ箣鍓嶅彂璐э紝褰撴湀15鏃ュ埌鏈�',
+        'ZL6T' => '90% LC 60 days锛�10% TT AFTER',
+        'ZL95' => '95% L/C AFTER,5% L/C AFTER 6M FROM ACCEPTANCE DATE',
+        'ZLC1' => '100% L/C (90/10) Transfer',
+        'ZLC2' => '100% L/C AT SIGHT (95/5)',
+        'ZLT1' => '90%LC锛�10%TT',
+        'ZLT2' => '80%LC锛�20%TT',
+        'ZLT3' => '70%LC锛�30%TT',
+        'ZLT4' => '95%LC锛�5%TT',
+        'ZLT5' => '50%L/C锛�50%TT after',
+        'ZT20' => '20% T/T ADV,80% T/T AFTER',
+        'ZT30' => '30% T/T ADV, 70%T/T AFTER',
+        'ZT35' => '35% TT ADV锛�65% TT AFTER',
+        'ZT40' => '40% TT ADV锛�60% TT AFTER',
+        'ZT50' => '50% TT ADV锛�50% TT AFTER',
+        'ZT55' => '95%TT ADV锛�5%TT AFTER',
+        'ZT90' => '楠屾敹鍚堟牸鍚嶵/T鏀粯90%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯10%',
+        'ZTT1' => 'TT AFTER DELIVERY 45 DAY',
+        'ZTT2' => 'TT AFTER DELIVERY 120 DAY',
+        'ZTT3' => '100%TT鍙戣揣鍚�15涓伐浣滄棩鍐呮敮浠�',
+        'ZTT4' => '楠屾敹鍚堟牸鍚嶵/T鏀粯80%锛岃澶囨甯歌繍琛屼笁涓湀T/T鏀粯20%',
+        'ZZ60' => '60 DAYS AFTER ISSUING INVOICE',
+        'ZZ95' => '95% L/C AFTER,5% T/T AFTER 6M FROM ACCEPTANCE DATE',
+        'ZZLC' => '100% L/C AT SIGHT',
+        'ZZTT' => '100% TT IN ADVANCE'
+    };
+
+    public QuotePDFController() {
+        targetId = ApexPages.currentPage().getParameters().get('Id');
+        isPrintPrice = ApexPages.currentPage().getParameters().get('printprice');
+    }
+
+    // 鐢婚潰鍒濆鍖�
+    public PageReference init() {
+        if (targetId == null || targetId.length() == 0) {
+            return null;
+        }
+
+        is_hidden_user = false;
+        // String profileId = UserInfo.getProfileId();
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+        
+        // profileId = profileId.substring(0, 15);
+        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {
+            is_hidden_user = true;
+        }
+        is_dealer_user = false;
+        if (UserInfo.getUserType() == 'PowerPartner') {
+            is_dealer_user = true;
+        }
+
+        // 鎶ヤ环淇℃伅
+        List<Quote> quoList = [select Id, Name, CreatedDate, OpportunityId, Opportunity.Dealer__c, Opportunity.DealerSalesStaffName__c, AccountId, PrintPrice__c, TotalPrice,
+                                      DeliveryLeadTime__c, PaymentTerms__c, ExpirationDate, Warranty__c, Opportunity.TradeType__c, Opportunity.CurrencyIsoCode, Comment__c,
+                                      SetName1__c, SetQty1__c, SetName2__c, SetQty2__c, SetName3__c, SetQty3__c, SetName4__c, SetQty4__c, SetName5__c, SetQty5__c,
+                                      SetName6__c, SetQty6__c, SetName7__c, SetQty7__c, SetName8__c, SetQty8__c, SetName9__c, SetQty9__c, SetName10__c, SetQty10__c,
+                                      SetName11__c, SetQty11__c, SetName12__c, SetQty12__c, SetName13__c, SetQty13__c, SetName14__c, SetQty14__c, SetName15__c, SetQty15__c,
+                                      SetName16__c, SetQty16__c, SetName17__c, SetQty17__c, SetName18__c, SetQty18__c, SetName19__c, SetQty19__c, SetName20__c, SetQty20__c,
+                                      SetName21__c, SetQty21__c, SetName22__c, SetQty22__c, SetName23__c, SetQty23__c, SetName24__c, SetQty24__c, SetName25__c, SetQty25__c,
+                                      SetName26__c, SetQty26__c, SetName27__c, SetQty27__c, SetName28__c, SetQty28__c, SetName29__c, SetQty29__c, SetName30__c, SetQty30__c,
+                                      Custom_Price_Total__c, Custom_Price_Total_Text__c, Shipment_Term__c
+                                 from Quote
+                                where Id = :targetId];
+        Quote quo = new Quote();
+        if (quoList.size() > 0) {
+            quo = quoList[0];
+        } else {
+            return null;
+        }
+        // 甯佺
+        currencyIsoCode = quo.Opportunity.CurrencyIsoCode;
+        // 浠g悊鍟嗕俊鎭�
+        List<Account> dealerList = [select Id, Name, Address1__c, Phone, Fax
+                                      from Account
+                                     where Id = :quo.Opportunity.Dealer__c];
+        Account dealer = new Account();
+        if (dealerList.size() > 0) {
+            dealer = dealerList[0];
+        }
+        // 璇环鑱旂郴浜轰俊鎭�
+        List<OpportunityContactRole> ocrList = [select Id, OpportunityId, IsPrimary, ContactId
+                                                  from OpportunityContactRole
+                                                 where OpportunityId = :quo.OpportunityId 
+                                                 order by IsPrimary];
+        String conid = null;
+        if (ocrList.size() > 0) {
+            conid = ocrList[0].ContactId;
+        }
+        for (OpportunityContactRole ocr : ocrList) {
+            if (ocr.IsPrimary == true) {
+                conid = ocr.ContactId;
+                break;
+            }
+        }
+        Contact con = new Contact();
+        if (conid != null && conid.length() > 0) {
+            con = [select Id, Name, Phone, Email, Account.Name from Contact where Id = :conid];
+        }
+        // PDF鎶ヤ环淇℃伅
+        quoteInfo = new QuoteInfo(quo, dealer, con);
+        // 鎶ヤ环浜у搧淇℃伅
+        List<QuoteLineItem> qliList = [select Id, QuoteId, Quantity, UnitPrice, Subtotal, Description, Set__c, TotalPrice,
+                                              Product2Id, Product2.ProductCode, Product2.Description, Custom_Price__c, PricebookEntry.Hidden_flag__c,
+                                              Product2.Product_ECCode__c
+                                         from QuoteLineItem
+                                        where QuoteId = :targetId
+                                        order by Set__c, LineNumber];
+
+        pageCnt = 1;
+        printRecords = new List<SetInfo>();
+        String strSetCnt = System.Label.QuoteEntryMaxSet;
+        Integer intSetCnt = Integer.valueOf(strSetCnt);
+        Integer cnt = 1;
+        for (Integer i = 1; i <= intSetCnt; i++) {
+            String sName = (String) quo.get('SetName' + i + '__c');
+            if (sName != null && sName.length() > 0) {
+                String setName = 'set' + (i < 10 ? '0' : '') + i;
+                SetInfo si = new SetInfo(cnt, setName, quo, qliList, isPrintPrice, is_hidden_user, is_dealer_user);
+                printRecords.add(si);
+                pageCnt += si.pCnt;
+                cnt += 1;
+            }
+        }
+        system.debug('=====pageCnt:' + pageCnt);
+
+        return null;
+    }
+
+    // PDF涓讳俊鎭�
+    public class QuoteInfo {
+        public boolean printPrice {get; private set;}
+
+        public String quoteDate {get; private set;}
+        public String quoteNo {get; private set;}
+
+        public String dealerName {get; private set;}
+        public String dealerContactName {get; private set;}
+        public String dealerContactPhone {get; private set;}
+        public String dealerAddress {get; private set;}
+        public String dealerPhone {get; private set;}
+        public String dealerFax {get; private set;}
+        public String dealerEmail {get; private set;}
+
+        public String accountName {get; private set;}
+        public String accountContactName {get; private set;}
+        public String accountContactPhone {get; private set;}
+        public String accountContactEmail {get; private set;}
+
+        public String comment {get; private set;}
+
+        public String note1 {get; private set;}
+        public String note2 {get; private set;}
+        public String note3 {get; private set;}
+        public String note4 {get; private set;}
+        public String note5 {get; private set;}
+        public String note6 {get; private set;}
+        public String note7 {get; private set;}
+
+        public QuoteInfo(Quote quo, Account acc, Contact con) {
+            printPrice = quo.PrintPrice__c;
+
+            Datetime cDate = quo.CreatedDate;
+            quoteDate = cDate.format('yyyy-MM-dd');
+            quoteNo = quo.Name;
+
+            dealerName = acc.Name;
+            dealerContactName = quo.Opportunity.DealerSalesStaffName__c;
+            dealerContactPhone = '';
+            dealerAddress = acc.Address1__c;
+            dealerPhone = acc.Phone;
+            dealerFax = acc.Fax;
+            dealerEmail = '';
+
+            accountName = con.Account.Name;
+            accountContactName = con.Name;
+            accountContactPhone = con.Phone;
+            accountContactEmail = con.Email;
+
+            String temp = quo.Comment__c;
+            if (temp != null) {
+                temp = temp.replace('\n', '<br/>');
+            }
+            comment = temp;
+
+            note1 = paymentTermsMap.get(quo.PaymentTerms__c);
+            note2 = paymentTermsMap.get(quo.PaymentTerms__c);
+            Date n3 = quo.ExpirationDate;
+            note3 = n3 == null ? '-' : DateTime.newInstance(n3, Time.newInstance(0, 0, 0, 0)).format('MMMM,dd,yyyy');
+            Decimal n4 = quo.Warranty__c;
+            note4 = n4 == null ? '0' : n4.format();
+            note5 = quo.Shipment_Term__c;
+            note6 = quo.Opportunity.TradeType__c == 'Taxation' ? 'tax included' : 'tax exempted';
+            note7 = quo.Opportunity.TradeType__c == 'Taxation' ? '鍚◣' : '鍏嶇◣';
+        }
+    }
+
+    public class SetInfo {
+        private Integer maxLine = 36;
+
+        public String units {get; private set;}
+        public String description {get; private set;}
+        public Integer qty {get; private set;}
+        public Decimal total {get; private set;}
+        public List<List<LineInfo>> setPage {get; private set;}
+        public Integer pCnt {get; private set;}
+
+        public SetInfo(Integer no, String setName, Quote info, List<QuoteLineItem> qliList, String isPrintPrice, boolean is_hidden_user, boolean is_dealer_user) {
+            units = String.valueOf(no);
+            String fieldName = setName.substring(3);
+            fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
+            description = (String) info.get('SetName' + fieldName + '__c');
+            Decimal d_qty = (Decimal) info.get('SetQty' + fieldName + '__c');
+            qty = d_qty == null ? 1 : d_qty.intValue();
+            total = 0;
+
+            setPage = new List<List<LineInfo>>();
+            pCnt = 0;
+            Integer i = 0;
+            Integer tmp = 0;
+            List<LineInfo> sPage = new List<LineInfo>();
+            for (QuoteLineItem qli : qliList) {
+                if (qli.Set__c == setName) {
+                    i += 1;
+                    LineInfo line = new LineInfo(i, qli, qty, info.PrintPrice__c);
+                    //LineInfo line = new LineInfo(i, qli, 1, isPrintPrice=='true');
+                    if (tmp + line.lineCost <= maxLine && i > 1) {
+                        sPage.add(line);
+                        tmp += line.lineCost;
+                    } else {
+                        system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
+                        sPage = new List<LineInfo>();
+                        setPage.add(sPage);
+                        sPage.add(line);
+                        tmp = line.lineCost;
+                        pCnt += 1;
+                    }
+                    total += line.totalPrice * qty;
+
+                    if (is_hidden_user == true || is_dealer_user == true && qli.PricebookEntry.Hidden_flag__c == true) {
+                        line.price = 0;
+                        line.subTotal = 0;
+                        line.totalPrice = 0;
+                    }
+                }
+            }
+            system.debug('=====pCnt:' + pCnt);
+        }
+    }
+
+    // PDF鏄庣粏琛屼俊鎭�
+    public class LineInfo {
+        private Integer codeBreak = 10;
+        private Integer descriptionBreak = 9;
+        private Integer commentBreak = 9;
+
+        public Integer lineCost {get; private set;}
+        public QuoteLineItem qli {get; private set;}
+
+        public Integer lineNo {get; private set;}
+        public String productCode {get; private set;}
+        public String productEC {get; private set;}
+        public String description {get; private set;}
+        public String comment {get; private set;}
+        public Integer quantity {get; private set;}
+        public Decimal price {get; private set;}
+        public Decimal subTotal {get; private set;}
+        public Decimal totalPrice {get; private set;}
+
+        public Integer pageqty {get; private set;}
+
+        public LineInfo(Integer i, QuoteLineItem info, Integer qty, boolean printPrice) {
+            // 涓嶆樉绀轰环鏍兼椂锛屾瘡琛屽彲鏄剧ず瀛楃澧炲姞
+            if (printPrice == false) {
+                descriptionBreak = 15;
+                commentBreak = 15;
+            }
+            // 璁$畻鏁版嵁鎵�鍗犺鏁�
+            lineCost = 1;
+            productCode = info.Product2.ProductCode;
+            if (productCode.startsWith('00000000000')) {
+                productCode = productCode.substring(11);
+            }
+            productEC = info.Product2.Product_ECCode__c;
+            Integer cost1 = productCode == null ? 1 : Math.mod(productCode.length(), codeBreak) == 0 ? productCode.length() / codeBreak : productCode.length() / codeBreak + 1;
+            if (lineCost < cost1) {
+                lineCost = cost1;
+            }
+            description = info.product2.Description;
+            Integer cost2 = description == null ? 1 : Math.mod(description.length(), descriptionBreak) == 0 ? description.length() / descriptionBreak : description.length() / descriptionBreak + 1;
+            if (lineCost < cost2) {
+                lineCost = cost2;
+            }
+            comment = info.Description;
+            Integer cost3 = comment == null ? 1 : Math.mod(comment.length(), commentBreak) == 0 ? comment.length() / commentBreak : comment.length() / commentBreak + 1;
+            if (lineCost < cost3) {
+                lineCost = cost3;
+            }
+            // 椤圭洰璧嬪��
+            qli = info;
+            lineNo = i;
+            //productCode = setBr(productCode, codeBreak);
+            description = setBr(description, descriptionBreak);
+            comment = setBr(comment, commentBreak);
+            Decimal d_quantity = info.Quantity / qty;
+            quantity = d_quantity.intValue();
+            price = info.Custom_Price__c == null ? 0 : info.Custom_Price__c / qty / quantity;
+            price = price.setScale(2, System.RoundingMode.HALF_UP);
+            subTotal = info.Custom_Price__c == null ? 0 : info.Custom_Price__c / qty;
+            subTotal = subTotal.setScale(2, System.RoundingMode.HALF_UP);
+            totalPrice = info.Custom_Price__c == null ? 0 : info.Custom_Price__c / qty;
+            totalPrice = totalPrice.setScale(2, System.RoundingMode.HALF_UP);
+
+            pageqty = qty;
+        }
+
+        // 鎵嬪姩鎹㈣
+        private String setBr(String orgstr, Integer breakcnt) {
+            String tmp = '';
+            if (orgstr == null) {
+                orgstr = '';
+            }
+            for (Integer i = 0; i < orgstr.length() / breakcnt + 1; i++) {
+                if (i == orgstr.length() / breakcnt) {
+                    tmp += orgstr.substring(i * breakcnt);
+                } else {
+                    tmp += orgstr.substring(i * breakcnt, (i + 1) * breakcnt) + '<br/>';
+                }
+            }
+            return tmp;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/QuotePDFController.cls-meta.xml b/scr/classes/QuotePDFController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/QuotePDFController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuotePDFControllerTest.cls b/scr/classes/QuotePDFControllerTest.cls
new file mode 100644
index 0000000..4cd2017
--- /dev/null
+++ b/scr/classes/QuotePDFControllerTest.cls
@@ -0,0 +1,126 @@
+@isTest
+private class QuotePDFControllerTest {
+
+	@isTest static void test_init() {
+		Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456'
+        );
+        insert user;
+
+        Contact contact = new Contact(
+            LastName = 'contact',
+            AccountId = user.Id
+        );
+        insert contact;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10
+        );
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20
+        );
+        insert new OpportunityLineItem[] {oli1, oli2};
+
+        OpportunityContactRole ocr = new OpportunityContactRole(
+            OpportunityId = opp.Id,
+            ContactId = contact.Id,
+            IsPrimary = true
+        );
+        insert ocr;
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname1',
+            SetQty1__c = 1
+        );
+        insert quo;
+
+        QuoteLineItem qli1 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10,
+            Custom_Price__c = 15,
+            Set__c = 'set01',
+            SingleProduct__c = false
+        );
+        QuoteLineItem qli2 = new QuoteLineItem(
+            QuoteId = quo.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20,
+            Custom_Price__c = 25,
+            Set__c = 'set01'
+        );
+        insert new QuoteLineItem[] {qli1, qli2};
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        PageReference page = new PageReference('/apex/QuotePDF?Id=' + quo.Id + '&printprice=true');
+        System.Test.setCurrentPage(page);
+        QuotePDFController controller = new QuotePDFController();
+
+        controller.init();
+	}
+
+}
\ No newline at end of file
diff --git a/scr/classes/QuotePDFControllerTest.cls-meta.xml b/scr/classes/QuotePDFControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/QuotePDFControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuoteTriggerHandler.cls b/scr/classes/QuoteTriggerHandler.cls
new file mode 100644
index 0000000..5c3284b
--- /dev/null
+++ b/scr/classes/QuoteTriggerHandler.cls
@@ -0,0 +1,128 @@
+public without sharing class QuoteTriggerHandler {
+
+	public static void setDealerGroup(List<Quote> newList, Map<Id, Quote> newMap, List<Quote> oldList, Map<Id, Quote> oldMap) {
+        List<String> oppIdList = new List<String>();
+        for (Quote newQuote : newList) {
+            oppIdList.add(newQuote.OpportunityId);
+        }
+
+        if (oppIdList.size() > 0) {
+            List<OpportunityTeamMember> otmList = [select Id, UserId, User.ProfileId from OpportunityTeamMember where opportunityId = :oppIdList];
+            List<OpportunityTeamMember> delList = new List<OpportunityTeamMember>();
+            for (OpportunityTeamMember otm : otmList) {
+                String profileId = otm.User.ProfileId;
+                if (profileId.substring(0, 15) == System.Label.RT_BS_No_Price ||
+                    profileId.substring(0, 15) == System.Label.RT_BS_No_Price_Email) {
+                    delList.add(otm);
+                }
+            }
+
+            if (delList.size() > 0) delete delList;
+    }
+
+       
+	}
+
+    public static void setPaymetTerms(List<Quote> newList, Map<Id, Quote> newMap, List<Quote> oldList, Map<Id, Quote> oldMap){
+        System.debug('1111');
+        Map<String,Quote> oppMap = new Map<String,Quote>();
+        //String quoId = '';
+        for (Quote newQuote : newList) {
+            Quote old = oldMap.get(newQuote.Id);
+            System.debug(newQuote.PaymentTerms__c);
+            System.debug(old.PaymentTerms__c);
+            if(newQuote.PaymentTerms__c != old.PaymentTerms__c){
+                oppMap.put(newQuote.OpportunityId, newQuote);
+            }
+           /* if(newQuote.ProductSegment__c == 'BS' && newQuote.Is_Decided__c != oldMap.get(newQuote.iD).Is_Decided__c){
+                quoId = newQuote.Id;
+            }*/
+        }
+        System.debug(oppMap.keySet().size());
+        if(oppMap.keySet().size()>0){
+            System.debug(oppMap.keySet());
+            List<Order> orderList = [select Id,OpportunityId from Order where Status__c = 'Active' and OpportunityId = :oppMap.keySet()];
+            System.debug(orderList);
+            if(orderList.size() > 0){
+                System.debug('22222222222');
+                for(Order odr : orderList){
+                    //鐜嬮箯浼熸柊鍔犲垽鏂紝鍙湁宸插悓姝ョ殑鎶ヤ环鎵嶄細鍚屾鍚堝悓鐨勪粯娆炬潯浠�
+                    if(oppMap.get(odr.OpportunityId).IsSyncing){
+                        odr.PaymentTerms__c = oppMap.get(odr.OpportunityId).PaymentTerms__c;
+                    }
+                }
+                System.debug(orderList);
+                update orderList;
+            }
+        }
+
+        /*if(quoId != '' && quoId != null){
+            List<QuoteLineItem> qliList = [select id,DontSingleProduct__c from QuoteLineItem where QuoteId = :quoId];
+            String temp = '';
+            for(QuoteLineItem qli : qliList){
+                if(qli.DontSingleProduct__c != '1'){
+                    temp+=(' '+qli.DontSingleProduct__c);
+                }
+            }
+            Quote quo = new Quote();
+            quo.id = quoId;
+            quo.DontSingleProductCode__c = temp;
+
+            if(temp.length() >0) update quo;
+        }*/
+    }
+
+    public static void setDontSingleProductCode(List<Quote> newList, Map<Id, Quote> newMap, List<Quote> oldList, Map<Id, Quote> oldMap){ 
+        //String quoId = '';
+
+        Quote quo = newList[0];
+        // Opportunity opp = [select Id,Dealer__c from Opportunity where Id = :quo.OpportunityId];
+        // if(opp.Dealer__c != '0012800001HoORb' && opp.Dealer__c != '0012800001HoPY4' && opp.Dealer__c != '0012800001HoPaz'){
+        // WLIG-BVP4L2 瑙﹀彂101 鏂板缓涓�涓叕寮忓瓧娈礝ppDealer__c锛屽幓鎺変笂闈㈢殑妫�绱�
+        if(quo.OppDealer__c != '0012800001HoORb' && quo.OppDealer__c != '0012800001HoPY4' && quo.OppDealer__c != '0012800001HoPaz'){
+
+            //if(quo.ProductSegment__c == 'BS' && quo.Is_Decided__c != oldMap.get(quo.Id).Is_Decided__c && quo.Is_Decided__c == true){
+                List<QuoteLineItem> qliList = [select id,DontSingleProduct__c from QuoteLineItem where QuoteId = :quo.Id];
+                String temp = '';
+                for(QuoteLineItem qli : qliList){
+                    if(qli.DontSingleProduct__c != '1'){
+                        temp+=(' '+qli.DontSingleProduct__c);
+                    }
+                }
+                quo.DontSingleProductCode__c = temp;
+           // }
+        }
+
+    }
+
+    public static void check(List<Quote> newList, Map<Id, Quote> newMap, List<Quote> oldList, Map<Id, Quote> oldMap){
+        //if(newList[0].Is_Decided__c == true){
+            String quoid =  newList[0].id;
+            List<QuoteLineItem> qliList= [select id,Product2.NMPAStatus__c,Product2.ProductCode,Product2.ProductStatusFormula__c,QuoLiOrderIsChange__c,quoLiVerifyProductValid__c from QuoteLineItem where QuoteId = :quoid];
+            String str = '';
+            Boolean isok = true;
+            for(QuoteLineItem qli : qliList){
+                // WLIG-BTA8C2 XHL 20200925 -Start
+                // 鍚堝悓鍙樻洿 骞朵笖 鎶ヤ环浜у搧鐨� 楠岃瘉浜у搧鏈夋晥鎬� 涓� false 鏃惰烦杩囬獙璇�
+                if (qli.QuoLiOrderIsChange__c && qli.quoLiVerifyProductValid__c == false) {
+                // WLIG-BTA8C2 XHL 20200925 -End
+                } else {
+                    if(qli.Product2.ProductStatusFormula__c == '0' ){
+                        if(newList[0].Is_Decided__c == true && oldList[0].Is_Decided__c == false){
+                            str += (' '+qli.Product2.ProductCode);
+                            isok = false;
+                        }else{
+                            
+                        }
+                    }   
+                }
+                
+            }
+            if(isok == false){
+                newList[0].addError(str + '浜у搧鐘舵�佷笉姝g‘銆�');
+            }
+        //}
+
+   } 
+
+}
\ No newline at end of file
diff --git a/scr/classes/QuoteTriggerHandler.cls-meta.xml b/scr/classes/QuoteTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/QuoteTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuoteTriggerTest.cls b/scr/classes/QuoteTriggerTest.cls
new file mode 100644
index 0000000..3aec4aa
--- /dev/null
+++ b/scr/classes/QuoteTriggerTest.cls
@@ -0,0 +1,306 @@
+@isTest
+private class QuoteTriggerTest {
+
+	@isTest static void test_method_one() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+		User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'test@test.com';
+        user.Username = 'test111@test222.com';
+        user.CommunityNickname = 'test20201015';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+
+        User user2 = new User();
+        user2.LastName = 'test2';
+        user2.FirstName = 'test2';
+        user2.Alias = 'test2';
+        user2.Email = 'test2@test2.com';
+        user2.Username = 'test222@test233666.com';
+        user2.CommunityNickname = 'test2';
+        user2.IsActive = true;
+        user2.EmailEncodingKey = 'ISO-2022-JP';
+        user2.TimeZoneSidKey = 'Asia/Tokyo';
+        user2.LocaleSidKey = 'ja_JP';
+        user2.LanguageLocaleKey = 'ja';
+        user2.ProfileId = System.Label.RT_BS_No_Price;
+        user2.ContactId = con.Id;
+        insert user2;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine'
+        );
+        insert opp;
+
+        OpportunityTeamMember otm1 = new OpportunityTeamMember();
+        otm1.opportunityId = opp.Id;
+        otm1.userId = user.Id;
+        otm1.teamMemberRole = 'Sales Manager';
+        insert otm1;
+
+        OpportunityTeamMember otm2 = new OpportunityTeamMember();
+        otm2.opportunityId = opp.Id;
+        otm2.userId = user2.Id;
+        otm2.teamMemberRole = 'Sales Manager';
+        insert otm2;
+
+        List<OpportunityTeamMember> otmList = [select Id from OpportunityTeamMember where opportunityId = :opp.Id];
+        System.assertEquals(2, otmList.size());
+
+        Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            PaymentTerms__c = 'ZZTT'
+        );
+        insert quo;
+
+        List<OpportunityTeamMember> otmList2 = [select Id from OpportunityTeamMember where opportunityId = :opp.Id];
+        //System.assertEquals(1, otmList2.size());
+
+        quo.PaymentTerms__c = 'Z9TT';
+
+        update quo;
+	}
+
+   
+      @isTest static void test_init1() {
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'N5679000';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.ProductCode = 'product2';
+        product2.Product_ECCode__c = 'product2';
+        product2.IsActive = true;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product3';
+        product3.IsActive = true;
+
+        insert new Product2[] {product1, product2, product3};
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        insert new PricebookEntry[] {standardPrice1, standardPrice2, standardPrice3};
+
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product1.Id,
+            UnitPrice = 30,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry entry2 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product2.Id,
+            UnitPrice = 30,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        PricebookEntry entry3 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product3.Id,
+            UnitPrice = 30,
+            IsActive = true,
+            UseStandardPrice = false,
+            CurrencyIsoCode = 'CNY'
+        );
+
+        insert new PricebookEntry[] {entry1, entry2, entry3};
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 30
+        );
+
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry2.Id,
+            Quantity = 2,
+            UnitPrice = 30
+        );
+
+        OpportunityLineItem oli3 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            PricebookEntryId = entry3.Id,
+            Quantity = 3,
+            UnitPrice = 30
+        );
+
+        insert new OpportunityLineItem[] {oli1, oli2, oli3};
+
+        PageReference page = new PageReference('/apex/NewQuoteService?oppid=' + opp.Id + '&openType=service');
+        System.Test.setCurrentPage(page);
+        NewQuoteEntryController controller = new NewQuoteEntryController();
+
+        controller.init();
+
+        controller.quo.Name = '鎶ヤ环1';
+        controller.quo.PaymentTerms__c = 'Z0LC';
+        controller.quo.Shipment_Term__c = 'CIP';
+        controller.quo.Shipment_Term2__c = 'BEIJING';
+        controller.quo.DeliveryLeadTime__c = 90;
+        controller.quo.Warranty__c = 1;
+        controller.quo.ExpirationDate = Date.today();
+        controller.quo.Custom_Price_Total_Text__c = 1000;
+
+/*        controller.activities[0].pageObject.PricebookEntryId = entry1.Id;
+        controller.activities[0].pageObject.Set__c = 'set01';
+        controller.activities[0].pageObject.UnitPrice = 11;
+        controller.activities[0].pageObject.Quantity = 1
+        controller.activities[0].pageObject.Discount = 0;
+        controller.activities[0].pageObject.Custom_Price__c = 20;
+        controller.activities[0].pageObject.Description = 'test1';*/
+        
+        controller.Save();
+
+        //system.assertEquals('',controller.errormessage);
+
+        controller.excelImport();
+
+        controller.OppReflection();
+
+        controller.BackBtn();
+        System.Test.StartTest();
+        controller.Decide();
+        List<Quote> QuoteList = [select Id from Quote]; 
+        //update QuoteList[0];
+        if(QuoteList.size() > 0){
+            update QuoteList[0];
+        }
+        System.Test.StopTest();
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/QuoteTriggerTest.cls-meta.xml b/scr/classes/QuoteTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/QuoteTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuotesPDFController.cls b/scr/classes/QuotesPDFController.cls
new file mode 100644
index 0000000..b94d45a
--- /dev/null
+++ b/scr/classes/QuotesPDFController.cls
@@ -0,0 +1,336 @@
+public with sharing class QuotesPDFController {
+    //鎶ヤ环ID
+    public String id {get; set;}
+    //鎶ヤ环
+    public Quotes__c quo {get; set;}
+    //鎶ヤ环琛岄」鐩�
+    public List<Quotes_item__c> qiList {get; set;}
+    public List<lineDataInfo> lineList{get;set;}
+    public List<lineDataInfo> lineList2{get;set;}
+    //鐢熸垚鐨凱DF椤垫暟
+    public Integer pageNum{get;set;}
+    //涓嶅惈绋庡悎璁� 鍚堣
+    public Decimal amount{get;set;}
+    //绋庨 鍚堣
+    public Decimal taxAmt{get;set;}
+    //鎬婚噾棰� 鍚堣
+    public Decimal grossAmt{get;set;}
+    public String conName{get;set;}
+
+    // 绗竴椤典笉浼氫镜鍏ラ〉鑴氫俊鎭殑鏈�澶ц鏁�
+    private Decimal firstCount = 50;
+    // 绗竴椤垫暟鎹镜鍏ラ〉鑴氫俊鎭紝绗竴椤电殑鏈�澶ц鏁�
+    private Decimal firstMaxCount = 60;
+    // 浠庣浜岄〉寮�濮嬩笉渚靛叆椤佃剼淇℃伅锛屽崟椤垫渶澶ц鏁�
+    private Decimal dataCount = 119;
+    // 浠庣浜岄〉寮�濮嬩镜鍏ラ〉鑴氫俊鎭紝鍗曢〉鏈�澶ц鏁�
+    private Decimal dataCountMax = 129;
+    // 褰撳墠椤甸潰淇℃伅鐨勮鏁�
+    private Integer count{get;set;}
+    // 涓�琛屾樉绀虹殑瀛楃鏁�
+    private Decimal ITEM_NAME_NUMBER_strNum = 10;
+    // 涓�琛屾樉绀虹殑瀛楃鏁�
+    private Decimal PART_NUMBERNew_strNum = 15;
+    // 涓�琛屾樉绀虹殑瀛楃鏁�
+    private Decimal DESCRIPTION_strNum = 40;
+    //鎺ユ敹鍦板潃鏈夊洖杞︼紝涓�琛屾渶澶у彲浠ユ湁姹夊瓧闀垮害
+    private Decimal RECEIVEDESCRIPTION_strNum = 21;
+
+    public QuotesPDFController() {
+        //鑾峰彇鎶ヤ环ID
+        id = System.currentPageReference().getParameters().get('id');
+    }
+
+    /**
+     * [init description]鍒濆鍖栨柟娉�
+     */
+    public void init(){
+        pageNum = 0;
+        //鏁版嵁淇℃伅鍒�42琛� 灏变細鎶婇〉鑴氫俊鎭《鍒颁笅涓�椤�
+        //firstCount = 40;
+        //id涓嶄负绌猴紝鏌ユ壘瀵瑰簲鎶ヤ环鍜屾姤浠疯椤圭洰
+        if(id != null && id != ''){
+            //鏌ヨ鎶ヤ环 CONTACT_EMAIL__c(鑱旂郴閭)锛孋ONTACT_PHONE__c(鑱旂郴鐢佃瘽)锛孊ILL_TO__c(浠樻浜�)
+            //SUBTOTAL__c
+            //DISCOUNT__c
+            //TAX__c
+            //TOTAL__c
+            quo = [SELECT id,ESTIMATE__c,DATE__c,EXPIRES__c,CURRENCY__c,TERMS__c,INCOTERM__c,PO__c,LEAD_TIME__c,CONTACT_EMAIL__c,CONTACT_PHONE__c,CONTACT_NAME__c,BILL_TO__c,SHIP_TO__c,CUSTOMER_MESSAGE__c,SWOName__c,QuotesType__c,COMPANYName__c,SUBTOTAL__c,DISCOUNT__c,TAX__c,TOTAL__c FROM Quotes__c WHERE Id = :id];
+            List<Contact> conList = [select Id,Name from Contact where Id =: quo.CONTACT_NAME__c];
+            if(conList!=null && conList.size()!=0){
+                conName = conList[0].Name;
+            }
+            //鏌ヨ鎶ヤ环琛岄」鐩�
+            qiList = [SELECT id,PART_NUMBERNew__c,ITEM_NAME_NUMBER__c,QUANTITY__c,UPC_CODE__c,DESCRIPTION__c,RATE__c,AMOUNT__c,TAX_RATE__c,TAX_AMT__c,GROSS_AMT__c,DESCROPTION_NAME__c,ProductOTcode__c FROM Quotes_item__c where QUOTE__c = :id];
+            /*for(Integer t = 0 ; t<13 ; t++){
+                Quotes_item__c item = new Quotes_item__c();
+                item.DESCRIPTION__c = 'wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww';
+                qiList.add(item);
+            }*/
+            if(qiList!=null && qiList.size()!=0){
+                lineList = new List<lineDataInfo>();
+                lineList2 = new List<lineDataInfo>();
+                Map<String,Decimal> oneDataRowNum = new Map<String,Decimal>();
+                // 璁$畻鎵�鏈夋暟鎹湁鍥炶溅鎹㈣鎯呭喌锛屼竴鏉℃暟鎹崰鐢ㄥ琛岀殑琛屾暟銆�
+                Decimal dataNum = 0;
+                //涓嶅惈绋庡悎璁� 鍚堣
+                amount = 0.00;
+                //绋庨 鍚堣
+                taxAmt = 0;
+                //鎬婚噾棰� 鍚堣
+                grossAmt = 0;
+                for(Integer i = 0; i<qiList.size() ; i++){
+
+                    String str = qiList[i].ProductOTcode__c;
+                    //a锛宐锛宑 涓�鏉℃暟鎹腑涓�涓瓧娈靛崰鐢ㄩ〉闈㈣鏁帮紝椤甸潰涓湁涓変釜瀛楁杈冮暱锛岄渶瑕佽绠楁瘡鏉℃暟鎹崰椤甸潰鐨勮鏁帮紝纭畾鏁版嵁鏄惁浼氫镜鍏ラ〉鑴氫俊鎭腑
+                    Decimal a = 0;
+                    Decimal b = 0;
+                    Decimal c = 0;
+                    System.debug(qiList[i].DESCROPTION_NAME__c);
+                    if (qiList[i].DESCROPTION_NAME__c == 'Payment Info' && qiList[i].DESCRIPTION__c != null) {
+                        // 璁$畻鍑烘潵鐨勫崰鐢ㄩ〉闈㈣鏁板姞涓�  姣忔潯鏁版嵁鍚庨潰瑕佸姞涓�琛岀┖鐧借
+                        a = getLine(RECEIVEDESCRIPTION_strNum,qiList[i].DESCRIPTION__c)+1;
+                    }else if(qiList[i].DESCROPTION_NAME__c == 'DESCRIPTION' && qiList[i].DESCRIPTION__c!=null){
+                        // 璁$畻鍑烘潵鐨勫崰鐢ㄩ〉闈㈣鏁板姞涓�  姣忔潯鏁版嵁鍚庨潰瑕佸姞涓�琛岀┖鐧借
+                        str = qiList[i].DESCRIPTION__c;
+                        a = ((str.length()!=0) ? math.ceil(str.length()/RECEIVEDESCRIPTION_strNum) : 1)+1;
+                    }else{
+                        // 璁$畻鍑烘潵鐨勫崰鐢ㄩ〉闈㈣鏁板姞涓�  姣忔潯鏁版嵁鍚庨潰瑕佸姞涓�琛岀┖鐧借
+                        a = (str!=null && str.length()!=0 ? math.ceil(str.length()/ITEM_NAME_NUMBER_strNum) : 1)+1;
+                        // 璁$畻鍑烘潵鐨勫崰鐢ㄩ〉闈㈣鏁板姞涓�  姣忔潯鏁版嵁鍚庨潰瑕佸姞涓�琛岀┖鐧借
+                        str = qiList[i].PART_NUMBERNew__c;
+                        b = (str!=null && str.length()!=0 ? math.ceil(str.length()/PART_NUMBERNew_strNum) : 1)+1;
+                        // 璁$畻鍑烘潵鐨勫崰鐢ㄩ〉闈㈣鏁板姞涓�  姣忔潯鏁版嵁鍚庨潰瑕佸姞涓�琛岀┖鐧借
+                        str = qiList[i].DESCRIPTION__c;
+                        c = (str!=null && str.length()!=0 ? math.ceil(str.length()/DESCRIPTION_strNum) : 1)+1;
+                    }
+                    //姣旇緝涓�鏉℃暟鎹腑鍗曚釜瀛楁鎵�鍗犻〉闈㈣鏁帮紝鍙栨渶澶у��
+                    if(a>=b && a>=c){
+                        dataNum += a;
+                        oneDataRowNum.put(qiList[i].Id, a);
+                    }else if(b>=a && b>=c){
+                        dataNum += b;
+                        oneDataRowNum.put(qiList[i].Id, b);
+                    }else if(c>=a && c>=b){
+                        dataNum += c;
+                        oneDataRowNum.put(qiList[i].Id, c);
+                    }
+                    if(qiList[i].DESCROPTION_NAME__c != 'DESCRIPTION' && qiList[i].DESCROPTION_NAME__c != 'Payment Info'){
+                        amount = amount + (qiList[i].AMOUNT__c != null ? qiList[i].AMOUNT__c : 0.00);
+                        taxAmt = taxAmt + (qiList[i].TAX_AMT__c != null ? qiList[i].TAX_AMT__c : 0.00);
+                        qiList[i].GROSS_AMT__c = (qiList[i].AMOUNT__c != null ? qiList[i].AMOUNT__c : 0.00) + (qiList[i].TAX_AMT__c != null ? qiList[i].TAX_AMT__c : 0.00);
+                        grossAmt = grossAmt + (qiList[i].GROSS_AMT__c != null ? qiList[i].GROSS_AMT__c : 0.00);
+                    }
+                }
+                //鍔犱笂鏈�鍚庝竴琛屽悎璁�
+                dataNum = dataNum+3;
+                // 瀛樻斁鏀惧湪PDF椤甸潰鏈�鍚庣殑浠樻淇℃伅 Payment Info
+                List<Quotes_item__c> buyInfo = new List<Quotes_item__c>();
+                // 瀛樻斁鏀惧湪鏈�鍚庣殑澶囨敞 DESCRIPTION 淇℃伅
+                List<Quotes_item__c> descriptionList = new List<Quotes_item__c>();
+                //鏋勫缓鏈�鍚庝竴琛屽悎璁¤
+                Quotes_item__c lastTotal = new Quotes_item__c();
+                lastTotal.DESCRIPTION__c = 'Subtotal for SWO Number: '+(quo.SWOName__c!=null?quo.SWOName__c:'');
+                lastTotal.AMOUNT__c = amount;
+                lastTotal.TAX_AMT__c = taxAmt;
+                lastTotal.GROSS_AMT__c = grossAmt;
+                System.debug('firstCount'+firstCount);
+                System.debug('firstMaxCount'+firstMaxCount);
+                System.debug('dataNum'+dataNum);
+                if(firstCount>=dataNum){
+                    // 鏁版嵁娌℃湁渚靛叆椤佃剼淇℃伅
+                    for(Quotes_item__c it : qiList){
+                        if(it.DESCROPTION_NAME__c == 'Payment Info'){
+                            buyInfo.add(it);
+                            continue;
+                        }else if(it.DESCROPTION_NAME__c == 'DESCRIPTION'){
+                            descriptionList.add(it);
+                            continue;
+                        }else{
+                            lineList.add(new lineDataInfo(it));
+                            lineList.add(new lineDataInfo());
+                        }
+                    }
+                    //鏈�鍚庢坊鍔犲悎璁¤鏀舵淇℃伅
+                    addHead(lineList,buyInfo,lastTotal,descriptionList);
+
+                    Decimal a = firstCount-dataNum;
+                    for(Integer i = 0 ; i<a-1 ; i++){
+                        lineList.add(new lineDataInfo());
+                    }
+                }else if(firstCount<dataNum && dataNum<firstMaxCount){
+                    // 鏁版嵁渚靛叆椤佃剼淇℃伅锛岃繕娌℃湁鍒颁笅涓�椤�
+                    for(Quotes_item__c it : qiList){
+                        if(it.DESCROPTION_NAME__c == 'Payment Info'){
+                            buyInfo.add(it);
+                            continue;
+                        }else if(it.DESCROPTION_NAME__c == 'DESCRIPTION'){
+                            descriptionList.add(it);
+                            continue;
+                        }else{
+                            lineList.add(new lineDataInfo(it));
+                            lineList.add(new lineDataInfo());
+                        }
+                    }
+                    //鏈�鍚庢坊鍔犲悎璁¤鏀舵淇℃伅
+                     addHead(lineList,buyInfo,lastTotal,descriptionList);
+                    // a 闇�瑕佽ˉ绌虹櫧琛屾妸绗竴椤垫拺婊�
+                    Decimal a = firstMaxCount-dataNum;
+                    for(Integer i = 0 ; i<a-1 ; i++){
+                        lineList.add(new lineDataInfo());
+                    }
+                }else if(firstMaxCount<dataNum){
+                    pageNum = 2;
+                    //鏁版嵁渚靛叆鍒扮浜岄〉
+                    //onePageNow 褰撳墠绗竴椤电疮璁″~鍏呰鏁�
+                    Decimal onePageNow = 0;
+                    //dataIndex 绗竴椤靛綋鍓嶅~鍏呮暟鎹殑鏁版嵁涓嬫爣锛岀浜岄〉浠庢涓嬫爣寮�濮嬪~鍏呮暟鎹�
+                    Integer dataIndex = 0;
+                    for(Quotes_item__c item : qiList){
+                        dataIndex ++;
+                        //杩欐潯鏁版嵁鏄敹娆句俊鎭紝鏈�鍚庢坊鍔�
+                        if(item.DESCROPTION_NAME__c == 'Payment Info'){
+                            buyInfo.add(item);
+                            continue;
+                        }
+                        if(item.DESCROPTION_NAME__c == 'DESCRIPTION'){
+                            descriptionList.add(item);
+                            continue;
+                        }
+                        //绗竴椤靛~鍏呰繖鏉℃暟鎹悗鍗犵敤琛屾暟锛岄渶瑕佸姞涓婃渶鍚庝竴琛岀殑鍚堣琛�
+                        onePageNow += (oneDataRowNum.get(item.Id)+1);
+
+                        if(onePageNow > firstMaxCount){
+                            //a 绗竴椤甸渶瑕佽ˉ婊℃坊鍔犵殑绌虹櫧琛屾潯鏁�
+                            Decimal a = firstMaxCount - (onePageNow - oneDataRowNum.get(item.Id));
+                            for(Integer i=0 ; i<a ; i++){
+                                lineList.add(new lineDataInfo());
+                            }
+                            break;
+                        }
+                        if(item.DESCROPTION_NAME__c == 'DESCRIPTION'){
+                            /*setItem(lineList,item.DESCRIPTION__c);
+                            lineList.add(new lineDataInfo());*/
+                        }else{
+                            lineList.add(new lineDataInfo(item));
+                            lineList.add(new lineDataInfo());
+                        }
+                    }
+                    for(Integer i = dataIndex ; i<qiList.size() ; i++){
+                        if(qiList[i].DESCROPTION_NAME__c == 'Payment Info'){
+                            buyInfo.add(qiList[i]);
+                            continue;
+                        }else if(qiList[i].DESCROPTION_NAME__c == 'DESCRIPTION'){
+                            descriptionList.add(qiList[i]);
+                            continue;
+                        }else{
+                            lineList2.add(new lineDataInfo(qiList[i]));
+                            lineList2.add(new lineDataInfo());
+                        }
+                    }
+                    addHead(lineList,buyInfo,lastTotal,descriptionList);
+                }
+            }
+        }else{
+            //鎶ヤ环涓虹┖娣诲姞绌虹殑鎶ヤ环鍜屾姤浠疯椤圭洰
+            quo = new Quotes__c();
+            qiList = new List<Quotes_item__c>();
+        }
+    }
+    /**
+     * [save description]淇濆瓨鏂规硶
+     */
+    public void save(){
+
+    }
+    // 鍔犲叆鏈�鍚庣殑鍚堣淇℃伅鍜屾敹娆句俊鎭�
+    public void addHead(List<lineDataInfo> lineData,List<Quotes_item__c> buyInfo,Quotes_item__c lastLine,List<Quotes_item__c> descriptionList){
+        if(lineData!=null && lineData.size()!=0){
+           /* if(lastLine!=null){
+                lineData.add(new lineDataInfo(lastLine));
+                lineData.add(new lineDataInfo());
+            }*/
+            if(buyInfo!=null&&buyInfo.size()!=0){
+                for(Quotes_item__c item : buyInfo){
+                    setItem(lineData,item.DESCRIPTION__c);
+                    lineData.add(new lineDataInfo());
+                }
+            }
+            if(descriptionList != null && descriptionList.size()!=0){
+                for(Quotes_item__c item : descriptionList){
+                    lineData.add(new lineDataInfo(item.DESCRIPTION__c));
+                    lineData.add(new lineDataInfo());
+                }
+            }
+        }
+    }
+
+    //浼犲叆涓�涓暟瀛� 鍜屼竴涓瓧绗︿覆锛岃绠楁瘡涓�琛屾湁璇ユ暟瀛椾釜瀛楃锛屽瓧绗︿覆鍒嗗嚑琛�
+    public Decimal getLine(Decimal num,String str){
+        System.debug('getLine:'+str);
+        if(String.isNotBlank(str)){
+            if(str.indexOf('锛�')!=-1){
+                str = str.replaceAll('锛�',';');
+            }
+            Decimal lineNum = 0;
+            Integer a = str.indexOf(';');
+            if(a!=-1){
+                String[] str_list = str.split(';');
+                for(String str_son:str_list){
+                    lineNum += math.ceil(str_son.length()/num);
+                }
+            }else{
+                lineNum += math.ceil(str.length()/num);
+            }
+            return lineNum;
+        }
+        return 1;
+    }
+
+    public void setItem(List<lineDataInfo> dataList,String str){
+        
+        if(String.isNotBlank(str)){
+            System.debug('str:'+str);
+            if(str.indexOf('锛�')!=-1){
+                str = str.replaceAll('锛�',';');
+            }
+            String[] strList = str.split(';');
+            System.debug('strList:'+strList);
+            if(strList!=null && strList.size()!=0){
+               for(String s:strList){
+                    System.debug('s:'+s);
+                    dataList.add(new lineDataInfo(s));
+                } 
+            }
+        }
+    }
+
+    public class lineDataInfo{
+        public String description{get;set;}
+        public String productName{get;set;}
+        public Quotes_item__c qi{get;set;}
+
+        public lineDataInfo(){
+            description = '绌虹櫧琛�';
+            qi = new Quotes_item__c();
+        }
+        public lineDataInfo(Quotes_item__c in_qi){
+            qi = in_qi;
+            if (String.isNotBlank(in_qi.ProductOTcode__c)) {
+                /*productName = in_qi.ProductOTcode__c.startsWith('00000000000')?in_qi.ProductOTcode__c.substring(12,in_qi.ProductOTcode__c.length):in_qi.ProductOTcode__c;*/
+                if(in_qi.ProductOTcode__c.startsWith('00000000000')){
+                    productName = String.valueOf(in_qi.ProductOTcode__c).substring(11,String.valueOf(in_qi.ProductOTcode__c).length());
+                }else{
+                    productName = in_qi.ProductOTcode__c;
+                }
+            }else{
+                productName = 'Service Quote Subtotal';
+            }
+            description = in_qi.DESCRIPTION__c;
+        }
+        public lineDataInfo(String in_des){
+            description = in_des;
+            qi = new Quotes_item__c();
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/QuotesPDFController.cls-meta.xml b/scr/classes/QuotesPDFController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/QuotesPDFController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuotesPDFControllerTest.cls b/scr/classes/QuotesPDFControllerTest.cls
new file mode 100644
index 0000000..2558a13
--- /dev/null
+++ b/scr/classes/QuotesPDFControllerTest.cls
@@ -0,0 +1,217 @@
+@isTest
+private class QuotesPDFControllerTest {
+    static testMethod void testMethod1() {
+
+    	List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'DESCRIPTION';
+        product1.IsActive = true;
+        product1.ProductCode = 'DESCRIPTION';
+        product1.Product_ECCode__c = 'test01';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'Payment Info';
+        product2.IsActive = true;
+        product2.ProductCode = 'Payment Info';
+        product2.Product_ECCode__c = 'Test01锛汿est02';
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product2.Description = 'Test01锛汿est02';
+
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'Service Quote Subtotal';
+        product3.IsActive = true;
+        product3.ProductCode = 'Service Quote Subtotal';
+        product3.Product_ECCode__c = 'Test01锛汿est02;test03';
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product3;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        // swo.ITEM__c = product1.Id;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        quotes.DATE__c = Date.today();
+        quotes.LEAD_TIME__c = '1 week';
+        quotes.STATUS__c = 'Qualifying';
+        quotes.LOCATION__c = 'China - Service';
+        quotes.TERMS__c = '1% 10 Net 30';
+        quotes.EXPIRES__c = Date.today();
+        quotes.EXP_CLOSE__c = Date.today();
+        quotes.ORDER_TYPE__c = 'LS Core Clinical';
+
+        insert quotes;
+        //DESCRIPTION__c,PART_NUMBERNew__c,
+        Quotes_item__c quotesItem =  new Quotes_item__c();
+        quotesItem.QUOTE__c =  quotes.Id;
+        quotesItem.QuotesItemProduct__c = product1.Id;
+        quotesItem.DESCRIPTION__c = 'Test01锛汿est02';
+        quotesItem.QUANTITY__c = 22;
+        quotesItem.AMOUNT__c = 22;
+        quotesItem.RATE__c = 222;
+        insert quotesItem;
+
+        Quotes_item__c quotesItem1 =  new Quotes_item__c();
+        quotesItem1.QUOTE__c =  quotes.Id;
+        quotesItem1.QuotesItemProduct__c = product2.Id;
+        quotesItem1.DESCRIPTION__c = 'Test01锛汿est02';
+        quotesItem1.QUANTITY__c = 22;
+        quotesItem1.AMOUNT__c = 22;
+        quotesItem1.RATE__c = 222;
+        insert quotesItem1;
+
+        Quotes_item__c quotesItem2 =  new Quotes_item__c();
+        quotesItem2.QUOTE__c =  quotes.Id;
+        quotesItem2.QuotesItemProduct__c = product3.Id;
+        quotesItem1.DESCRIPTION__c = 'Test01锛汿est02';
+        quotesItem2.QUANTITY__c = 22;
+        quotesItem2.AMOUNT__c = 22;
+        quotesItem2.RATE__c = 222;
+        insert quotesItem2;
+
+        PageReference page = new PageReference('/apex/QuotesPDF?id='+quotes.Id);
+        System.Test.setCurrentPage(page);
+        QuotesPDFController controller = new QuotesPDFController();
+        controller.init();
+    }
+    static testMethod void testMethod2() {
+
+    	List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'DESCRIPTION';
+        product1.IsActive = true;
+        product1.ProductCode = 'DESCRIPTION';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        Product2 product2 = new Product2();
+        product2.Name = 'Payment Info';
+        product2.IsActive = true;
+        product2.ProductCode = 'Payment Info';
+        product2.ProductStatus__c = '1';
+        product2.NMPAStatus_one__c = 'Z1';
+        product2.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product2.Description = 'Test01锛汿est02';
+
+        insert product2;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'Service Quote Subtotal';
+        product3.IsActive = true;
+        product3.ProductCode = 'Service Quote Subtotal';
+        product3.ProductStatus__c = '1';
+        product3.NMPAStatus_one__c = 'Z1';
+        product3.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product3.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product3;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        // swo.ITEM__c = product1.Id;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        quotes.DATE__c = Date.today();
+        quotes.LEAD_TIME__c = '1 week';
+        quotes.STATUS__c = 'Qualifying';
+        quotes.LOCATION__c = 'China - Service';
+        quotes.TERMS__c = '1% 10 Net 30';
+        quotes.EXPIRES__c = Date.today();
+        quotes.EXP_CLOSE__c = Date.today();
+        quotes.ORDER_TYPE__c = 'LS Core Clinical';
+
+        insert quotes;
+
+        Quotes_item__c quotesItem =  new Quotes_item__c();
+        quotesItem.QUOTE__c =  quotes.Id;
+        quotesItem.QuotesItemProduct__c = product1.Id;
+        quotesItem.QUANTITY__c = 22;
+        quotesItem.AMOUNT__c = 22;
+        quotesItem.RATE__c = 222;
+        insert quotesItem;
+
+        Quotes_item__c quotesItem1 =  new Quotes_item__c();
+        quotesItem1.QUOTE__c =  quotes.Id;
+        quotesItem1.QuotesItemProduct__c = product2.Id;
+        quotesItem1.DESCRIPTION__c = 'Test01锛汿est02';
+        quotesItem1.QUANTITY__c = 22;
+        quotesItem1.AMOUNT__c = 22;
+        quotesItem1.RATE__c = 222;
+        insert quotesItem1;
+
+        Quotes_item__c quotesItem2 =  new Quotes_item__c();
+        quotesItem2.QUOTE__c =  quotes.Id;
+        quotesItem2.QuotesItemProduct__c = product3.Id;
+        quotesItem2.QUANTITY__c = 22;
+        quotesItem2.AMOUNT__c = 22;
+        quotesItem2.RATE__c = 222;
+        insert quotesItem2;
+
+        for(Integer i = 0 ; i<50 ; i++){
+        	quotesItem2.id = null;
+        	insert quotesItem2;
+        }
+
+        PageReference page = new PageReference('/apex/QuotesPDF?id='+quotes.Id);
+        System.Test.setCurrentPage(page);
+        QuotesPDFController controller = new QuotesPDFController();
+        controller.init();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/QuotesPDFControllerTest.cls-meta.xml b/scr/classes/QuotesPDFControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/QuotesPDFControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/QuotesesEmailComeBackListen.cls b/scr/classes/QuotesesEmailComeBackListen.cls
new file mode 100644
index 0000000..611d5a7
--- /dev/null
+++ b/scr/classes/QuotesesEmailComeBackListen.cls
@@ -0,0 +1,91 @@
+global class QuotesesEmailComeBackListen implements Messaging.InboundEmailHandler {
+    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
+    	System.debug('杩涘叆Quoteses鍥炲閭欢鐩戝惉');
+    	String id = '';
+		if(String.isNotBlank(email.subject)){
+			List<String> str = email.subject.split('~');
+			if(str!=null && str.size()!=0){
+				//鎴彇閭欢鍏宠仈淇℃伅锛屾煡璇㈤偖浠跺叧鑱斿璞★紝鍒ゆ柇鏄惁璺宠繃閭欢鏈嶅姟
+				String name = str[1];
+				if(String.isNotBlank(name)){
+					List<Quotes__c> quotesList = [select Id,notSaveEmail__c,Name from Quotes__c where Name=:name];
+						if (quotesList!=null && quotesList.size()!=0) {
+							id = quotesList[0].Id;
+							System.debug('Quoteses閭欢鍥炲鐩戝惉:'+quotesList[0].notSaveEmail__c);
+							if(quotesList[0].notSaveEmail__c){
+							System.debug('璺宠繃閭欢鏈嶅姟鐩戝惉');
+							quotesList[0].notSaveEmail__c = false;
+							update quotesList[0];
+							return null;
+						}
+					}
+				}
+			}
+		}
+		Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
+		createEmail(email,id);
+		//SendEmail();
+		result.success = true;
+		return result;
+	} 
+
+	public void createEmail(Messaging.InboundEmail email,String id){
+		Mail_Merge__c mailMerge = new Mail_Merge__c();
+		//閭欢鏍囬
+		if(String.isNotBlank(email.subject)){
+			mailMerge.SUBJECTCOPY__c = email.subject;
+			List<String> str = email.subject.split('~');
+			if(str!=null && str.size()!=0){
+				mailMerge.SUBJECT__c = str[0];
+				mailMerge.Name = str[0];
+			}
+		}else{
+			mailMerge.SUBJECTCOPY__c = '';
+			mailMerge.SUBJECT__c = '';
+			mailMerge.Name = '';
+		}
+		mailMerge.Quotes__c = id;
+		mailMerge.RECORD_TYPE__c = 'Quotes';
+		//鍙戜欢浜哄湴鍧�
+		mailMerge.FROM__c = email.fromAddress;
+		//鏀朵欢浜哄湴鍧�
+		mailMerge.RECIPIENT__c = getAddresses(email.toAddresses);
+		//鎶勯�佷汉
+		mailMerge.CC__c = getAddresses(email.ccAddresses);
+		//閭欢淇℃伅
+		mailMerge.MESSAGE__c = email.plainTextBody;
+		//鏀跺彇鍥炲閭欢鏃堕棿
+		mailMerge.DATE__c = Date.today();
+		
+		mailMerge.TYPE__c = 'reply';
+		
+		insert mailMerge;
+		//淇濆瓨閭欢闄勪欢
+		saveFile(email.binaryAttachments,mailMerge.Id);
+
+	}
+
+	public String getAddresses(List<String> addresses){
+		String returnStr = '';
+		if(addresses!=null && addresses.size()!=0){
+			for(String str:addresses){
+				returnStr += str+';';
+			}
+		}
+		return returnStr;
+	}
+
+	public void saveFile(List<Messaging.InboundEmail.BinaryAttachment> binaryAttachments,String Id){
+		if (binaryAttachments != null && binaryAttachments.size()!=0) {
+			List<Attachment> attachmentList = new List<Attachment>();
+			for(Messaging.InboundEmail.BinaryAttachment emailFile : binaryAttachments){
+				Attachment attachment = new Attachment();
+				attachment.Name = emailFile.fileName;
+				attachment.Body = emailFile.body;
+				attachment.ParentId = Id;
+				attachmentList.add(attachment);
+			}
+			insert attachmentList;
+		}
+	} 
+}
\ No newline at end of file
diff --git a/scr/classes/QuotesesEmailComeBackListen.cls-meta.xml b/scr/classes/QuotesesEmailComeBackListen.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/QuotesesEmailComeBackListen.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/RadiationUtil.cls b/scr/classes/RadiationUtil.cls
new file mode 100644
index 0000000..e39f810
--- /dev/null
+++ b/scr/classes/RadiationUtil.cls
@@ -0,0 +1,577 @@
+global class RadiationUtil {
+
+    public static Boolean EscapeOrderTriggerHandler = true;
+    /**
+     * [updateRadiationTypeQuantity description]鏇存柊浠g悊鍟嗚瘉鐓ф槑缁嗭紝鏇存柊濂ユ灄宸存柉浠g悊鍟嗙殑璇佺収鏄庣粏
+     * @param Id           [description]鍚堝悓Id
+     * @param orderFounder [description]鍚堝悓鍒涘缓浜�
+     * @param dealerId     [description]浠g悊鍟咺d
+     * @param toloseFlag   [description]鏍规嵁鏉′欢澧炲姞杩樻槸鍑忓幓浠g悊鍟嗚喘涔版槑缁嗙殑鏁伴噺
+     */
+    public static void updateRadiationTypeQuantity (String Id, String orderFounder, String dealerId, Boolean toloseFlag, String operationType, String operator) {
+
+        String olympusAccountId = System.label.Olympus_Id;
+
+        String orderId = Id;
+        //鑾峰彇鍚堝悓鐨勮緪灏勭被鍨嬪拰鏁伴噺
+        Map<String, Integer> radiationTypeQuantityMap =  GetModelQuantityMap(Id);
+        if ( radiationTypeQuantityMap.size() > 0 ) {
+
+            //鏌ヤ唬鐞嗗晢鐨勪唬鐞嗗晢璐拱鏄庣粏
+            Map<String, PurchaseDetails__c> dealerModelQuantityMap = GetPurchaseDetailsMap(dealerId);
+            //鏌ュゥ鏋楀反鏂殑浠g悊鍟嗚喘涔版槑缁�
+            Map<String, PurchaseDetails__c> olympusModelQuantityMap = GetPurchaseDetailsMap(olympusAccountId);
+            // 鏌ユ壘 鍚堝悓鎻愪氦瀵瑰簲鐨勪唬鐞嗗晢璐拱鏄庣粏
+            Map<String, PurchaseDetails__c> dealerResult = new Map<String, PurchaseDetails__c>();
+            Map<String, PurchaseDetails__c> olympusResult = new Map<String, PurchaseDetails__c>();
+            // 鍚堝悓椹冲洖銆佸悎鍚岃皟鍥炪�佸悎鍚岀姸鎬佺敱鎵瑰噯鍙樿崏妗�--->宸插敭浜у搧鏁伴噺    
+            if (toloseFlag) {
+                // 1.鏌ユ壘鍚堝悓 鐨� 璐拱鏄庣粏鍙樻洿璇︽儏 鎿嶄綔绫诲瀷鏄� 鍚堝悓鎻愪氦鍜屽悎鍚岃崏妗堜腑鍙樻壒鍑�        
+                List<ChangedReport__c> selectChangedReportList = [
+                SELECT Id,Name,ChangedPurchase__c,ChangedReportOrder__c,OperationType__c,
+                       ChangedPurchase__r.PurchaseAccount__c 
+                FROM ChangedReport__c 
+                WHERE ChangedReportOrder__c = :orderId AND OperationType__c IN ('鍚堝悓鎻愪氦','鍚堝悓鑽夋涓彉鎵瑰噯')  Order by Id ];
+
+                if (selectChangedReportList.size() > 0) {
+                    // 2.鍙栧嚭鍚堝悓瀵瑰簲鐨勪唬鐞嗗晢鏈�鏂扮殑 璐拱鏄庣粏鍙樻洿璇︽儏
+                    Map<String,String> tempMap = new Map<String,String>();
+                    for (ChangedReport__c changedReport:selectChangedReportList) {
+                        String accountIdSub = changedReport.ChangedPurchase__r.PurchaseAccount__c;
+                        accountIdSub = accountIdSub.substring(0,15);
+                        tempMap.put(accountIdSub,changedReport.ChangedPurchase__c);
+                    }
+                    if (tempMap.size() > 0) {
+                        // 3.鍙栧嚭瀵瑰簲鐨� 浠g悊鍟嗚緪灏勪骇鍝佽喘涔版槑缁�
+                        List<PurchaseDetails__c> purchaseDetailsList = [
+                        SELECT Id, Name, RemainingNumber__c, SoldNumber__c,
+                                                 PurProductModel__c, PurchaseAccount__c
+                        FROM PurchaseDetails__c
+
+                        WHERE Id IN :tempMap.values()];
+                        
+                        if (purchaseDetailsList.size() > 0) {
+                            for (PurchaseDetails__c purchaseDetail : purchaseDetailsList) {
+                                String accountIdSub = purchaseDetail.PurchaseAccount__c;
+                                accountIdSub = accountIdSub.substring(0,15);
+
+                                if (dealerId.equals(accountIdSub)) {
+                                    dealerResult.put(purchaseDetail.PurProductModel__c, purchaseDetail);
+                                } else if(olympusAccountId.equals(accountIdSub)){
+                                    olympusResult.put(purchaseDetail.PurProductModel__c, purchaseDetail);
+                                }
+                                
+                            }
+                        }
+                    }
+                }
+            }
+
+            
+            Map<String, ChangedReport__c> reportMap = new Map<String, ChangedReport__c>();
+            Map<String, ChangedReport__c> insertReportMap = new Map<String, ChangedReport__c>();
+            for ( String radiationType : radiationTypeQuantityMap.keySet()) {
+
+                //浠g悊鍟嗙殑浠g悊鍟嗚喘涔版槑缁嗚祴鍊�
+                Integer quantity = radiationTypeQuantityMap.get(radiationType);
+                if (dealerModelQuantityMap.size() > 0) {
+                    if ( dealerModelQuantityMap.containsKey(radiationType)) {
+
+                        if (toloseFlag) {//鍑忓幓宸插敭浜у搧鏁伴噺
+                            reportMap.putAll(upsertChangedReport(dealerId, radiationType, operationType, orderId, -quantity, operator));
+                            dealerResult.get(radiationType).SoldNumber__c -= quantity;
+                        } else {//澧炲姞宸插敭浜у搧鏁伴噺
+                            reportMap.putAll(upsertChangedReport(dealerId, radiationType, operationType, orderId, quantity, operator));
+                            dealerModelQuantityMap.get(radiationType).SoldNumber__c += quantity;
+                        }
+
+                    } else {//澧炲姞宸插敭浜у搧鏁伴噺
+                        reportMap.putAll(upsertChangedReport(dealerId, radiationType, operationType, orderId, quantity, operator));
+                        dealerModelQuantityMap = insertPurchaseDetail(dealerModelQuantityMap, dealerId, radiationType, radiationTypeQuantityMap);
+                    }
+                } else {
+                    if (toloseFlag) {//鍑忓幓宸插敭浜у搧鏁伴噺
+                        reportMap.putAll(upsertChangedReport(dealerId, radiationType, operationType, orderId, -quantity, operator));
+                        dealerResult.get(radiationType).SoldNumber__c -= quantity;
+                    } else {//澧炲姞宸插敭浜у搧鏁伴噺
+                        reportMap.putAll(upsertChangedReport(dealerId, radiationType, operationType, orderId, quantity, operator));
+                        dealerModelQuantityMap = insertPurchaseDetail(dealerModelQuantityMap, dealerId, radiationType, radiationTypeQuantityMap);
+                    }
+                   
+
+                }
+
+                //濂ユ灄宸存柉鐨勪唬鐞嗗晢璐拱鏄庣粏璧嬪��
+                if (olympusModelQuantityMap.size() > 0 ) {
+                    if (olympusModelQuantityMap.containsKey(radiationType)) {
+                        if (toloseFlag) {//鍑忓幓宸插敭浜у搧鏁伴噺
+                            reportMap.putAll(upsertChangedReport(olympusAccountId, radiationType, operationType, orderId, -quantity, operator));
+                            olympusResult.get(radiationType).SoldNumber__c -= quantity;
+                        } else {//澧炲姞宸插敭浜у搧鏁伴噺
+                            reportMap.putAll(upsertChangedReport(olympusAccountId, radiationType, operationType, orderId, quantity, operator));
+                            olympusModelQuantityMap.get(radiationType).SoldNumber__c += quantity;
+                        }
+
+                    } else {//澧炲姞宸插敭浜у搧鏁伴噺
+                        reportMap.putAll(upsertChangedReport(olympusAccountId, radiationType, operationType, orderId, quantity, operator));
+                        olympusModelQuantityMap = insertPurchaseDetail(olympusModelQuantityMap, olympusAccountId, radiationType, radiationTypeQuantityMap);
+                    }
+                } else {//鍑忓幓宸插敭浜у搧鏁伴噺
+                    if (toloseFlag) {
+                        reportMap.putAll(upsertChangedReport(olympusAccountId, radiationType, operationType, orderId, -quantity, operator));
+                        olympusResult.get(radiationType).SoldNumber__c -= quantity;
+                    } else {//澧炲姞宸插敭浜у搧鏁伴噺
+                        reportMap.putAll(upsertChangedReport(olympusAccountId, radiationType, operationType, orderId, quantity, operator));
+                        olympusModelQuantityMap = insertPurchaseDetail(olympusModelQuantityMap, olympusAccountId, radiationType, radiationTypeQuantityMap);
+                    }
+                    
+                }
+            }
+            
+            if (toloseFlag) {
+                if ( dealerResult.size() > 0 && dealerResult != null) {
+                    upsert dealerResult.values();
+
+                    insertReportMap.putAll(insertChangedReport(dealerResult,reportMap));
+                } 
+
+                if ( olympusResult.size() > 0 && olympusResult != null) {
+                    upsert olympusResult.values();
+                    insertReportMap.putAll(insertChangedReport(olympusResult, reportMap));
+                }
+
+            } else {
+                if ( dealerModelQuantityMap.size() > 0 && dealerModelQuantityMap != null) {
+                    upsert dealerModelQuantityMap.values();
+                    insertReportMap.putAll(insertChangedReport(dealerModelQuantityMap,reportMap));
+                } 
+
+                if ( olympusModelQuantityMap.size() > 0 && olympusModelQuantityMap != null) {
+                    upsert olympusModelQuantityMap.values();
+                    insertReportMap.putAll(insertChangedReport(olympusModelQuantityMap, reportMap));
+                }
+            }
+                
+            if ( insertReportMap.size() > 0 && insertReportMap != null) {
+                insert insertReportMap.values();
+            }
+            
+            Map<String, Integer> radiationMap =  new Map<String, Integer>();
+            String accountDealerErrorMessage = updateCertificationDetails(dealerId, orderFounder, radiationMap, true);
+            String olympusDealerErrorMessage = updateCertificationDetails(olympusAccountId, orderFounder, radiationMap, true);
+        }
+
+    }
+    /**
+     * 浠g悊鍟嗚喘涔版槑缁嗘搷浣滆鎯呰祴鍊�
+     * @Author   绋�閲岀硦娑�
+     * @DateTime 2020-02-22
+     * @param    detailsMap [description]浠g悊鍟嗚喘涔版槑缁�
+     * @param    reportMap  [description]浠g悊鍟嗚喘涔版槑缁嗘搷浣滆鎯�
+     * @return              [description]
+     */
+    public static Map<String, ChangedReport__c> insertChangedReport( Map<String, PurchaseDetails__c> detailsMap, Map<String, ChangedReport__c> reportMap) {
+        for (PurchaseDetails__c detail : detailsMap.values()) {
+            String accountId = detail.PurchaseAccount__c;
+            //String accountIdafter = accountId.subString(0,15);
+            String key = accountId.subString(0, 15) + detail.PurProductModel__c;
+            if (reportMap.containsKey(key)) {
+                reportMap.get(key).ChangedPurchase__c = detail.Id;
+            }
+        }
+
+        return reportMap;
+    }
+    /**
+     * [updateCertificationDetails description]鏇存柊浠g悊鍟嗙殑璇佺収鏄庣粏
+     * @param  accountId    [description]浠g悊鍟咺d
+     * @param  orderFounder [description]鍚堝悓鍒涘缓浜�
+     * @param  dataMap      [description]寰呴獙璇佺殑鏁版嵁
+     * @param  updateFlag   [description]鏄惁鏇存柊鏁版嵁
+     * @return              [description]
+     */
+    public static String updateCertificationDetails( String accountId, String orderFounder, Map<String, Decimal> dataMap, Boolean updateFlag) {
+
+        Map<String, CertificationDetails__c> certificationDetailMap = GetAccountCertificationDetail(accountId);
+        Map<String, CertificationDetails__c> temporaryCertificationDetailMap = GetAccountCertificationDetail(accountId);
+        Map<String, PurchaseDetails__c> purchaseDetailMap = GetPurchaseDetailsMap(accountId);
+
+        Map<String, CertificationDetails__c> updatecertificationDetailMap = new Map<String, CertificationDetails__c>();
+        String record = '';
+        String errorMessage = '';
+        if (certificationDetailMap.size() > 0 && certificationDetailMap != null ) {
+
+            if (dataMap.size() > 0 && dataMap != null) {
+
+                for (String temp : dataMap.keySet()) {
+                    if (certificationDetailMap.containsKey(temp)) {
+
+                    } else {
+                        if (certificationDetailMap.containsKey('Delta鍜孷anta')) {
+                            List<String> childModels = new List<String> {'Delta', 'Vanta'};
+                            if (childModels.contains(temp)) {
+
+                            } else {
+                                errorMessage = '浣犱笉鑳�' + temp + '绯诲垪浜у搧' + certificationDetailMap.keySet();
+                                return errorMessage;
+                            }
+                        } else {
+                            errorMessage = '浣犱笉鑳�' + temp + '绯诲垪浜у搧' + certificationDetailMap.keySet();
+                            return errorMessage;
+
+                        }
+
+                    }
+                }
+            }
+
+            // 閬嶅巻鏌ヨ鍑烘潵鐨勮瘉鐓ф槑缁�
+            for (String model : certificationDetailMap.keySet()) {
+
+                Decimal purchaseQuantity = 0;
+                //鑾峰彇杈愬皠璇佺収鏄庣粏涓婏紝璇ュ瀷鍙峰搴旂殑鏁伴噺
+                Decimal certificationQuantity = certificationDetailMap.get(model).ProductModelNumber__c;
+                //鑾峰彇璇佺収鐨勫鎴峰悕绉�
+                String accountName = certificationDetailMap.get(model).CertificationDetailAccountName__c;
+                //鑾峰彇璇佺収鐨勫鎴锋槸鍚︽暟閲忕鎺�
+                Boolean ifQuantityCtrl = certificationDetailMap.get(model).LicenseInformation__r.IfQuantityCtrl__c;
+                //鑾峰彇璇佺収鐨勫鎴风殑璁板綍绫诲瀷
+                String  accountRecordType = certificationDetailMap.get(model).AccountRecordType__c;
+                //璇佺収鐨勫鎴疯褰曠被鍨嬩负浠g悊鍟嗗苟涓旈潪鏁伴噺绠℃帶鐩存帴璺宠繃
+                if (!ifQuantityCtrl && 'Dealer'.equals(accountRecordType)) {
+                    system.debug(' 鎴戣璺宠繃浜嗭紝璇锋敞鎰�');
+                    continue;    
+                } else {
+                    if (certificationQuantity == null || certificationQuantity == 0) {
+                        errorMessage += record = '瀹㈡埛鍚� [ ' + accountName + ' ] 浜у搧杈愬皠绫诲瀷 [ ' + model + ' ] 鎵�瀵瑰簲鍙敭鏁伴噺寮傚父锛侊紒锛�';
+                        return errorMessage;
+                    }
+                }
+                Decimal percentage = 0;
+                Decimal originalQuantity = 0;
+                Decimal newQuantity = 0;
+                Boolean errorFlag = false;
+                if (model.equals('Delta鍜孷anta')) {
+                    List<String> childModels = new List<String> {'Delta', 'Vanta'};
+                    for (String childModel : childModels) {
+                        if (purchaseDetailMap.containsKey(childModel)) {
+                            originalQuantity += purchaseDetailMap.get(childModel).SoldNumber__c;
+                        }
+                        if (dataMap != null && dataMap.size() > 0 && dataMap.containsKey(childModel)) {
+
+                            newQuantity += dataMap.get(childModel);
+                        }
+                    }
+
+                } else {
+                    if (purchaseDetailMap.containsKey(model)) {
+                        originalQuantity = purchaseDetailMap.get(model).SoldNumber__c;
+
+                    }
+                    if (dataMap != null && dataMap.size() > 0 && dataMap.containsKey(model)) {
+                        newQuantity += dataMap.get(model);
+                    }
+                }
+
+                purchaseQuantity = originalQuantity + newQuantity;
+
+                percentage = purchaseQuantity / certificationQuantity;
+
+                if (updateFlag) {
+
+                    record = '瀹㈡埛鍚� [ ' + accountName + ' ] 浜у搧杈愬皠绫诲瀷 [ ' + model + ' ] 宸插敭鍑烘暟閲忎负 [ ' + originalQuantity + ' ] 浠讹紝鍏佽鍞嚭鐨勬暟閲忎负 [ ' + certificationQuantity + ' ]浠躲��' ;
+                    // if (percentage <= 1) {
+
+                    temporaryCertificationDetailMap = radiationSendEmailSign(certificationDetailMap, orderFounder, model, record, percentage, updateFlag);
+                        // system.debug('temporaryCertificationDetailMap----->'+'(---'+accountName+'---)'+temporaryCertificationDetailMap);
+                    updatecertificationDetailMap.putAll(temporaryCertificationDetailMap);
+                    // } else {
+                    //     errorMessage += record + '宸茶秴鍑哄彲鍞暟閲忛檺鍒讹紝鏃犳硶淇濆瓨銆俓n';
+                    // }
+
+                } else {
+                    if (newQuantity > 0) {
+                        record = '瀹㈡埛鍚� [ ' + accountName + ' ] 浜у搧杈愬皠绫诲瀷 [ ' + model + ' ] 宸插敭鍑烘暟閲忎负 [ ' + originalQuantity + ' ] 浠讹紝鏂板 [ ' + newQuantity + ' ]浠讹紝鍏佽鍞嚭鐨勬暟閲忎负 [ ' + certificationQuantity + ' ]浠躲��';
+                        if (percentage > 1) {
+
+                            errorMessage += record + '宸茶秴鍑哄彲鍞暟閲忛檺鍒躲�俓n';
+                        }
+                    }
+
+                }
+
+            }
+
+            if (updateFlag) {
+
+                if ( updatecertificationDetailMap.size() > 0) {
+                    update updatecertificationDetailMap.values();
+                }
+            }
+        }
+
+        return errorMessage;
+
+
+    }
+
+    /**
+     * [radiationSendEmailSign description]妫�楠屾槸鍚﹁秴杩囧彲鍞笂闄愮殑80%锛�90%
+     * @param  certificationDetailMap [description]浠g悊鍟嗙殑璇佺収鏄庣粏
+     * @param  orderFounder           [description]鍚堝悓鍒涘缓浜篒d
+     * @param  model                  [description]杈愬皠浜у搧鍨嬪彿
+     * @param  record                 [description]鐧惧垎姣旇褰�
+     * @param  percentage             [description]鐧惧垎姣�
+     * @param  updateFlag             [description]鏄惁鏇存柊鏁版嵁
+     * @return                        [description]
+     */
+    public static Map<String, CertificationDetails__c> radiationSendEmailSign(Map<String, CertificationDetails__c> certificationDetailMap, String orderFounder, String model, String record, Decimal percentage, Boolean updateFlag) {
+
+        Map<String, CertificationDetails__c> result = new  Map<String, CertificationDetails__c>();
+        String olympusAccountId = System.label.Olympus_Id;
+
+        CertificationDetails__c  detail = certificationDetailMap.get(model);
+        system.debug('detail----->'+detail);
+        // 褰撲唬鐞嗗晢涓�"濂ユ灄宸存柉浠g悊鍟�"鏃讹紝瑕佺粰"椹枩鑺濄�佺帇鍐変箣"鍙戦�侀偖浠�
+        if (olympusAccountId == detail.CertificationDetailAccount__c) {
+            detail.OSHSafeguardOne__c = System.label.OSHSafeguardOne;
+            detail.OSHSafeguardTwo__c = System.label.OSHSafeguardTwo;
+        } 
+        if (percentage >= 1) {
+            detail.Ceiling100__c = true;
+            detail.Ceiling80__c = true;
+            detail.Ceiling90__c = true;
+            detail.Record100__c = record + '宸茶揪鍒板彲鍞笂闄愶紝璇锋敞鎰忥紒';
+            result.put(model, detail);
+        }  else if (percentage >= 0.9) {
+            detail.Ceiling80__c = true;
+            detail.Ceiling90__c = true;
+            detail.Record90__c = record + '宸茶秴杩囧彲鍞笂闄愮殑90%锛岃娉ㄦ剰锛�';
+            result.put(model, detail);
+        } else {
+
+            if (percentage >= 0.8 && !detail.Ceiling90__c) {
+                detail.Ceiling80__c = true;
+
+                detail.Record80__c = record + '宸茶秴杩囧彲鍞笂闄愮殑80%锛岃娉ㄦ剰锛�';
+                result.put(model, detail);
+            }
+        }
+        return result;
+
+    }
+    /**
+     * [GetAccountCertificationDetail description]鏌ユ壘浠g悊鍟嗙殑鐨勮瘉鐓ф槑缁�
+     * @param  accountId [description]浠g悊鍟咺d
+     * @return           [description]
+     */
+    public static Map<String, CertificationDetails__c> GetAccountCertificationDetail (String accountId) {
+        Map<String, CertificationDetails__c> result = new Map<String, CertificationDetails__c>();
+        List<CertificationDetails__c> certificationDetailsList = [ select Id, Name, ProdustionType__c, 
+                                    ProductModelNumber__c, Ceiling80__c, Record80__c, Ceiling90__c, Record90__c , 
+                                    CertificationDetailAccount__c, CertificationDetailAccountName__c,
+                                    LicenseInformation__r.IfQuantityCtrl__c,AccountRecordType__c,Record100__c,
+                                    Ceiling100__c
+                                    from CertificationDetails__c 
+                                    where CertificationDetailAccount__c = :accountId  
+                                        and ActivitieTypes__c = '閿�鍞�' and IsActive__c = true];
+
+        for  (CertificationDetails__c detail : certificationDetailsList) {
+            result.put(detail.ProdustionType__c, detail);
+        }
+
+
+        return result;
+
+
+    }
+    /**
+     * [insertPurchaseDetail description]涓轰唬鐞嗗晢鐨勪唬鐞嗗晢璐拱鏄庣粏璧嬪��
+     * @param  modelQuantityMap         [description]浠g悊鍟嗛攢鍞槑缁�
+     * @param  id                       [description]浠g悊鍟咺d
+     * @param  productModel             [description]浜у搧杈愬皠绫诲瀷
+     * @param  radiationTypeQuantityMap [description]鏂板鐨勭被鍨嬪強瀵瑰簲鐨勬暟閲�
+     * @return                          [description]
+     */
+    public static Map<String, PurchaseDetails__c> insertPurchaseDetail(Map<String, PurchaseDetails__c> modelQuantityMap,
+            String id, String productModel, Map<String, Integer> radiationTypeQuantityMap) {
+    	
+        Map<String, CertificationDetails__c>  certificationDetailMap = GetAccountCertificationDetail(id);
+        String effectiveYear = String.valueOf(Date.today().year());
+       
+        PurchaseDetails__c purchaseDetail = new PurchaseDetails__c();
+        purchaseDetail.SoldNumber__c = radiationTypeQuantityMap.get(productModel);
+        purchaseDetail.PurProductModel__c = productModel;
+        purchaseDetail.PurchaseAccount__c = id;
+        purchaseDetail.TakeEffectInYear__c = effectiveYear;
+
+        for (String model:certificationDetailMap.keySet()) {
+            if ('Delta鍜孷anta'.equals(model)) {
+
+                List<String> childModels = new List<String> {'Delta', 'Vanta'};
+                for (String childModel : childModels) {
+                    if (childModel.equals(productModel)) {
+                        purchaseDetail.PurchaseDetail__c = certificationDetailMap.get(model).Id;    
+                    }
+                }
+
+            } else {
+                purchaseDetail.PurchaseDetail__c = certificationDetailMap.get(productModel).Id;
+            }
+        }
+        // purchaseDetail.PurchaseDetail__c = certificationDetailMap.get(productModel).Id;            
+        modelQuantityMap.put(productModel, purchaseDetail);
+        return modelQuantityMap;
+    }
+
+    /**
+     * 浠g悊鍟嗚喘涔版槑缁嗘搷浣滆鎯�
+     * @Author   XHL
+     * @DateTime 2020-02-22
+     * @param    accountId     [description]浠g悊鍟咺d
+     * @param    radiationType [description]杈愬皠浜у搧绯诲垪
+     * @param    operationType [description]鎿嶄綔绫诲瀷
+     * @param    orderId       [description]鍚堝悓Id
+     * @param    quantity      [description]鍙樻洿鏁伴噺
+     * @param    operator      [description]鎿嶄綔浜�
+     * @return                 [description]
+     */
+    public static Map<String, ChangedReport__c>  upsertChangedReport(String accountId, String radiationType, String operationType, String orderId, Integer quantity, String operator) {
+        
+        Map<String, ChangedReport__c> result = new Map<String, ChangedReport__c>();
+        String key = accountId + radiationType;
+        ChangedReport__c  changedReport = new ChangedReport__c();
+        changedReport.ChangedReportOrder__c = orderId;
+        changedReport.RadiationType__c = radiationType;
+        changedReport.OperationType__c = operationType;
+        changedReport.Operator__c = operator;
+        changedReport.ChangeQuantity__c = quantity;
+
+        result.put(key, changedReport);
+
+        return result;
+
+    }
+    /**
+     * [GetPurchaseDetailsMap description]鑾峰彇瀹㈡埛鐨勪唬鐞嗗晢璐拱鏄庣粏鐨勬暟鎹�
+     * @param  accountId [description]浠g悊鍟咺d
+     * @return           [description]
+     */
+    public static Map<String, PurchaseDetails__c> GetPurchaseDetailsMap( String accountId) {
+        String effectiveYear = String.valueOf(Date.today().year());
+        Map<String, PurchaseDetails__c> result = new Map<String, PurchaseDetails__c>();
+        List<PurchaseDetails__c> purchaseDetailsList = [select Id, Name, RemainingNumber__c, SoldNumber__c,
+                                 PurProductModel__c, PurchaseAccount__c
+                                 from PurchaseDetails__c
+                                 where TakeEffectInYear__c = :effectiveYear and PurchaseAccount__c = :accountId];
+        if (purchaseDetailsList.size() > 0) {
+            for (PurchaseDetails__c purchaseDetail : purchaseDetailsList) {
+                result.put(purchaseDetail.PurProductModel__c, purchaseDetail);
+            }
+        }
+
+        return  result;
+    }
+
+    /**
+     * [GetModelQuantityMap description]姹囨�昏緪灏勪骇鍝佺殑鍨嬪彿鍜屾暟閲�
+     * @param  Id [description]鍚堝悓Id
+     * @return    [description]
+     */
+    public static  Map<String, Integer> GetModelQuantityMap(String Id) {
+        Map<String, Integer> result = new Map<String, Integer>();
+        List<OrderItem> orderItemList = [select Id, PriceBookEntry.Product2.If_Radiation_Product__c,
+                                         PriceBookEntry.Product2.RadiationType__c, PriceBookEntry.Product2.If_Exempt_Product__c, Quantity, Order.Opportunity.Dealer__c
+                                         from OrderItem
+                                         where OrderId = :Id
+                                                 order by QuoteLineItemId, Id];
+        if ( orderItemList.size() > 0) {
+
+            for ( OrderItem orderItem : orderItemList) {
+                Boolean radiationFlag = orderItem.PriceBookEntry.Product2.If_Radiation_Product__c;
+                Boolean exemptFlag = orderItem.PriceBookEntry.Product2.If_Exempt_Product__c;
+                if ( radiationFlag && !exemptFlag) {
+                    String radiationType = orderItem.PriceBookEntry.Product2.RadiationType__c;
+                    Integer quantity  = Integer.valueOf(orderItem.Quantity);
+                    if ( result.containsKey(radiationType)) {
+                        Integer num = result.get(radiationType) + quantity;
+                        result.put(radiationType, num);
+                    } else {
+                        result.put(radiationType, quantity);
+                    }
+                }
+
+            }
+        }
+
+        return result;
+    }
+
+    public static  Map<String, Integer> GetOpportunityLineMap(String Id) {
+        Map<String, Integer> result = new Map<String, Integer>();
+        List<OpportunityLineItem> oppItemList = [select Id, PriceBookEntry.Product2.If_Radiation_Product__c,
+                                  PriceBookEntry.Product2.RadiationType__c, PriceBookEntry.Product2.If_Exempt_Product__c, Quantity, Opportunity.Dealer__c
+                                  from OpportunityLineItem
+                                  where OpportunityId = :Id
+                                          order by Id];
+        if ( oppItemList.size() > 0) {
+
+            for ( OpportunityLineItem oppItem : oppItemList) {
+                Boolean radiationFlag = oppItem.PriceBookEntry.Product2.If_Radiation_Product__c;
+                Boolean exemptFlag = oppItem.PriceBookEntry.Product2.If_Exempt_Product__c;
+                if ( radiationFlag && !exemptFlag) {
+                    String radiationType = oppItem.PriceBookEntry.Product2.RadiationType__c;
+                    Integer quantity  = Integer.valueOf(oppItem.Quantity);
+                    if ( result.containsKey(radiationType)) {
+                        Integer num = result.get(radiationType) + quantity;
+                        result.put(radiationType, num);
+                    } else {
+                        result.put(radiationType, quantity);
+                    }
+                }
+
+            }
+        }
+
+        return result;
+    }
+
+    /**
+     * 妫�鏌ヤ唬鐞嗗晢鑳藉惁鍙互鍗栨煇浜涜緪灏勪骇鍝�
+     * @param  accountId [description]
+     * @param  dataMap   [description]
+     * @return           [description]
+     */
+    public static String GetCertificationDetail (String accountId, Map<String, Decimal> dataMap) {
+        Map<String, CertificationDetails__c> certificationDetailMap = GetAccountCertificationDetail(accountId);
+        System.debug(certificationDetailMap);
+        String record = '';
+        String errorMessage = '';
+        if (certificationDetailMap.size() > 0 && certificationDetailMap != null ) {
+
+            for (String temp : dataMap.keySet()) {
+                if (certificationDetailMap.containsKey(temp)) {
+
+                } else {
+                    if (certificationDetailMap.containsKey('Delta鍜孷anta')) {
+                        List<String> childModels = new List<String> {'Delta', 'Vanta'};
+                        if (childModels.contains(temp)) {
+
+                        } else {
+                            errorMessage = '浣犱笉鑳�' + temp + '绯诲垪浜у搧' + certificationDetailMap.keySet();
+                            return errorMessage;
+                        }
+                    } else {
+                        errorMessage = '浣犱笉鑳�' + temp + '绯诲垪浜у搧' + certificationDetailMap.keySet();
+                        return errorMessage;
+
+                    }
+
+                }
+            }
+        }
+        return errorMessage;
+
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/RadiationUtil.cls-meta.xml b/scr/classes/RadiationUtil.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/RadiationUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/RadiationUtilTest.cls b/scr/classes/RadiationUtilTest.cls
new file mode 100644
index 0000000..44582d6
--- /dev/null
+++ b/scr/classes/RadiationUtilTest.cls
@@ -0,0 +1,607 @@
+@isTest
+private class RadiationUtilTest {
+    
+    static testMethod void myTest0() {
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        List<RecordType> dealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Account accBS = new Account(
+            Name = '*',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer ANI',
+            FacilityName__c='abc',
+            PostCode__c='00000'
+        );
+        insert accBS;
+
+        Account dealerAccount = new Account(
+            Name = '*',
+            RecordTypeId = dealer[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Dealer',
+            FacilityName__c='abc',
+            PostCode__c='000001'
+        );
+        insert dealerAccount;
+
+        PurchaseDetails__c details = new PurchaseDetails__c();
+        details.PurchaseAccount__c = dealerAccount.Id;
+        details.TakeEffectInYear__c = '2020';
+        details.SoldNumber__c = 1;
+        details.PurProductModel__c = 'Delta';
+        insert details;
+
+        License_Information__c information = new License_Information__c();
+        information.ValidFrom__c = Date.today().addDays(-22);
+        information.ValidTo__c = Date.today().addDays(22);
+        information.LicenseAndAccount__c = dealerAccount.Id;
+        information.StorageAddress__c = '鍖椾含鏈濋槼浜┈妗�';
+        information.BusinessLicense__c = 'test01';
+        information.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert information;
+
+        CertificationDetails__c  certification = new CertificationDetails__c(); 
+        certification.ActivitieTypes__c = '閿�鍞�';
+        certification.ProdustionType__c = 'Delta鍜孷anta';
+        certification.ProductModelNumber__c = 10;
+        certification.LicenseInformation__c = information.Id ;
+
+        insert certification;
+        String olympusAccountId = System.label.Olympus_Id;
+        PurchaseDetails__c details1 = new PurchaseDetails__c();
+        details1.PurchaseAccount__c = olympusAccountId;
+        details1.TakeEffectInYear__c = '2020';
+        details1.SoldNumber__c = 1;
+        details1.PurProductModel__c = 'Delta';
+        insert details1;
+
+        License_Information__c olympusinformation = new License_Information__c();
+
+        olympusinformation.ValidFrom__c = Date.today().addDays(-22);
+        olympusinformation.ValidTo__c = Date.today().addDays(22);
+        olympusinformation.LicenseAndAccount__c = olympusAccountId;
+        olympusinformation.StorageAddress__c = '鍖椾含鏈濋槼浜┈妗�';
+        olympusinformation.BusinessLicense__c = 'test01';
+        olympusinformation.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert olympusinformation;
+
+        CertificationDetails__c  olympuscertification = new CertificationDetails__c(); 
+        olympuscertification.ActivitieTypes__c = '閿�鍞�';
+        olympuscertification.ProdustionType__c = 'Delta鍜孷anta';
+        olympuscertification.ProductModelNumber__c = 10;
+        olympuscertification.LicenseInformation__c = olympusinformation.Id ;
+
+        insert olympuscertification;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accBS.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'ANI',
+            ProductSegment__c = 'ANI',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.If_Radiation_Product__c = true;
+        product1.RadiationType__c = 'Vanta';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        
+
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accBS.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Machine_Parts__c = 'Machine',
+            InquiryResult__c = '112233',
+            Dealer__c = dealerAccount.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+             OpportunityId = opp.Id,
+             PricebookEntryId = entry1.Id,
+             Quantity = 1,
+             UnitPrice = 10
+         );
+         insert new OpportunityLineItem[] {oli1};
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accBS.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            SpecialDeliveryAccount_D__c = accBS.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            BusMagDepRev__c = Date.today(),
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        OrderItem oi1 = new OrderItem(
+            OrderId = odr.Id,
+            PriceBookEntryId = entry1.Id,
+            Quantity = 8,
+            UnitPrice = 10
+        );
+        insert oi1;
+
+        Opportunity opp1 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        System.assertEquals(null, opp1.Order_Date__c);
+        System.assertEquals(null, opp1.DeliveryDate__c);
+
+        odr.OrderDate__c = Date.today();
+        update odr;
+
+        odr.ApproveStatus__c = 'OrderPass';
+        update odr;
+        odr.ApproveStatus__c = 'Draft' ;
+        update odr;
+        odr.Status__c = 'Inactive';
+        update odr;
+
+    }
+
+    static testMethod void myTest1() {
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        List<RecordType> dealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Account accBS = new Account(
+            Name = '*',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer ANI',
+            FacilityName__c='abc',
+            PostCode__c='0000003'
+        );
+        insert accBS;
+
+        Account dealerAccount = new Account(
+            Name = '*',
+            RecordTypeId = dealer[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Dealer',
+            FacilityName__c='abc',
+            PostCode__c='000004'
+        );
+        insert dealerAccount;
+
+        PurchaseDetails__c details = new PurchaseDetails__c();
+        details.PurchaseAccount__c = dealerAccount.Id;
+        details.TakeEffectInYear__c = String.valueOf(Date.today().year());
+        details.SoldNumber__c = 1;
+        details.PurProductModel__c = 'Delta';
+        insert details;
+
+        License_Information__c information = new License_Information__c();
+        information.ValidFrom__c = Date.today().addDays(-22);
+        information.ValidTo__c = Date.today().addDays(22);
+        information.LicenseAndAccount__c = dealerAccount.Id;
+        information.StorageAddress__c = '鍖椾含鏈濋槼浜┈妗�';
+        information.BusinessLicense__c = 'test01';
+        information.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert information;
+
+        CertificationDetails__c  certification = new CertificationDetails__c(); 
+        certification.ActivitieTypes__c = '閿�鍞�';
+        certification.ProdustionType__c = 'Delta';
+        certification.ProductModelNumber__c = 10;
+        certification.LicenseInformation__c = information.Id ;
+
+        insert certification;
+        String olympusAccountId = System.label.Olympus_Id;
+        PurchaseDetails__c details1 = new PurchaseDetails__c();
+        details1.PurchaseAccount__c = olympusAccountId;
+        details1.TakeEffectInYear__c = String.valueOf(Date.today().year());
+        details1.SoldNumber__c = 1;
+        details1.PurProductModel__c = 'Delta';
+        insert details1;
+
+        License_Information__c olympusinformation = new License_Information__c();
+
+        olympusinformation.ValidFrom__c = Date.today().addDays(-22);
+        olympusinformation.ValidTo__c = Date.today().addDays(22);
+        olympusinformation.LicenseAndAccount__c = olympusAccountId;
+        olympusinformation.StorageAddress__c = '鍖椾含鏈濋槼浜┈妗�';
+        olympusinformation.BusinessLicense__c = 'test01';
+        olympusinformation.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert olympusinformation;
+
+        CertificationDetails__c  olympuscertification = new CertificationDetails__c(); 
+        olympuscertification.ActivitieTypes__c = '閿�鍞�';
+        olympuscertification.ProdustionType__c = 'Delta';
+        olympuscertification.ProductModelNumber__c = 10;
+        olympuscertification.LicenseInformation__c = olympusinformation.Id ;
+
+        insert olympuscertification;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accBS.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'ANI',
+            ProductSegment__c = 'ANI',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.If_Radiation_Product__c = true;
+        product1.RadiationType__c = 'Delta';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accBS.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Machine_Parts__c = 'Machine',
+            InquiryResult__c = '112233',
+            Dealer__c = dealerAccount.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+             OpportunityId = opp.Id,
+             PricebookEntryId = entry1.Id,
+             Quantity = 1,
+             UnitPrice = 10
+         );
+         insert new OpportunityLineItem[] {oli1};
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accBS.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            SpecialDeliveryAccount_D__c = accBS.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            BusMagDepRev__c = Date.today(),
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        OrderItem oi1 = new OrderItem(
+            OrderId = odr.Id,
+            PriceBookEntryId = entry1.Id,
+            Quantity = 7,
+            UnitPrice = 10
+        );
+        insert oi1;
+
+        Opportunity opp1 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        System.assertEquals(null, opp1.Order_Date__c);
+        System.assertEquals(null, opp1.DeliveryDate__c);
+
+        odr.OrderDate__c = Date.today();
+        update odr;
+
+        odr.ApproveStatus__c = 'OrderSubmit';
+        update odr;
+        
+    }
+
+    static testMethod void myTest2() {
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer ANI'];
+        List<RecordType> dealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Account accBS = new Account(
+            Name = '*',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer ANI',
+            FacilityName__c='abc',
+            PostCode__c='0000005'
+        );
+        insert accBS;
+
+        Account dealerAccount = new Account(
+            Name = '*',
+            RecordTypeId = dealer[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Dealer',
+            FacilityName__c='abc',
+            PostCode__c='000006'
+        );
+        insert dealerAccount;
+
+        PurchaseDetails__c details = new PurchaseDetails__c();
+        details.PurchaseAccount__c = dealerAccount.Id;
+        details.TakeEffectInYear__c = String.valueOf(Date.today().year());
+        details.SoldNumber__c = 1;
+        details.PurProductModel__c = 'Delta';
+        insert details;
+
+        License_Information__c information = new License_Information__c();
+        information.ValidFrom__c = Date.today().addDays(-22);
+        information.ValidTo__c = Date.today().addDays(22);
+        information.LicenseAndAccount__c = dealerAccount.Id;
+        information.StorageAddress__c = '鍖椾含鏈濋槼浜┈妗�';
+        information.BusinessLicense__c = 'test01';
+        information.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert information;
+
+        CertificationDetails__c  certification = new CertificationDetails__c(); 
+        certification.ActivitieTypes__c = '閿�鍞�';
+        certification.ProdustionType__c = 'Delta';
+        certification.ProductModelNumber__c = 10;
+        certification.LicenseInformation__c = information.Id ;
+
+        insert certification;
+        String olympusAccountId = System.label.Olympus_Id;
+        PurchaseDetails__c details1 = new PurchaseDetails__c();
+        details1.PurchaseAccount__c = olympusAccountId;
+        details1.TakeEffectInYear__c = '2020';
+        details1.SoldNumber__c = 1;
+        details1.PurProductModel__c = 'Delta';
+        insert details1;
+
+        License_Information__c olympusinformation = new License_Information__c();
+
+        olympusinformation.ValidFrom__c = Date.today().addDays(-22);
+        olympusinformation.ValidTo__c = Date.today().addDays(22);
+        olympusinformation.LicenseAndAccount__c = olympusAccountId;
+        olympusinformation.StorageAddress__c = '鍖椾含鏈濋槼浜┈妗�';
+        olympusinformation.BusinessLicense__c = 'test01';
+        olympusinformation.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        insert olympusinformation;
+
+        CertificationDetails__c  olympuscertification = new CertificationDetails__c(); 
+        olympuscertification.ActivitieTypes__c = '閿�鍞�';
+        olympuscertification.ProdustionType__c = 'Delta';
+        olympuscertification.ProductModelNumber__c = 10;
+        olympuscertification.LicenseInformation__c = olympusinformation.Id ;
+
+        insert olympuscertification;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accBS.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'ANI',
+            ProductSegment__c = 'ANI',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        product1.If_Radiation_Product__c = true;
+        product1.RadiationType__c = 'Delta';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accBS.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Machine_Parts__c = 'Machine',
+            InquiryResult__c = '112233',
+            Dealer__c = dealerAccount.Id
+        );
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+         OpportunityLineItem oli1 = new OpportunityLineItem(
+             OpportunityId = opp.Id,
+             PricebookEntryId = entry1.Id,
+             Quantity = 1,
+             UnitPrice = 10
+         );
+         insert new OpportunityLineItem[] {oli1};
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accBS.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            SpecialDeliveryAccount_D__c = accBS.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            BusMagDepRev__c = Date.today(),
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        OrderItem oi1 = new OrderItem(
+            OrderId = odr.Id,
+            PriceBookEntryId = entry1.Id,
+            Quantity = 11,
+            UnitPrice = 10
+        );
+        insert oi1;
+
+        Opportunity opp1 = [select id,Order_Date__c,DeliveryDate__c from Opportunity where Id = :opp.Id];
+        System.assertEquals(null, opp1.Order_Date__c);
+        System.assertEquals(null, opp1.DeliveryDate__c);
+
+        odr.OrderDate__c = Date.today();
+        update odr;
+
+        odr.ApproveStatus__c = 'OrderSubmit';
+        update odr;
+
+        odr.ApproveStatus__c = 'OrderDraft';
+        update odr;
+        
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/RadiationUtilTest.cls-meta.xml b/scr/classes/RadiationUtilTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/RadiationUtilTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/RepairDetailsTriggerHandler.cls b/scr/classes/RepairDetailsTriggerHandler.cls
new file mode 100644
index 0000000..9820b4c
--- /dev/null
+++ b/scr/classes/RepairDetailsTriggerHandler.cls
@@ -0,0 +1,63 @@
+public without sharing class RepairDetailsTriggerHandler {
+    public static String setNumber(List<RepairDetails__c> newList, Map<Id, RepairDetails__c> newMap, List<RepairDetails__c> oldList, Map<Id, RepairDetails__c> oldMap){
+        //system.debug('setNumber');
+        Map<String,List<RepairDetails__c>> repairMap = new Map<String,List<RepairDetails__c>>();
+        for(RepairDetails__c repd : newList){
+            if(repairMap.containsKey(repd.Repair__c)){
+                repairMap.get(repd.Repair__c).add(repd);
+            }else{
+                repairMap.put(repd.Repair__c, new List<RepairDetails__c>());
+                repairMap.get(repd.Repair__c).add(repd);
+            }
+            //system.debug(repairMap);
+        }
+        if(repairMap.size() > 0){
+            //count(id) 涓嶄负0鏃朵慨鏀筃ame
+            Set<String> rep = repairMap.keySet();
+            List<AggregateResult> repair = [select count(id) ID ,Repair__c from RepairDetails__c where Repair__c =: rep group by Repair__c];
+            List<RepairDetails__c> repdList = [select Repair__c, Repair__r.name from RepairDetails__c where Repair__c =: rep];
+            Map<String,String> id_name = new Map<String,String>();
+            //system.debug(repair);
+            //system.debug(repdList);
+            for(RepairDetails__c rd : repdList){
+                id_name.put(rd.Repair__c, rd.Repair__r.Name);
+            }
+            List<String> overID = new List<String>();
+            //system.debug(id_name);
+            for(AggregateResult  ar : repair){
+                String rep1 = (String)ar.get('repair__c');
+                List<RepairDetails__c> repairDList = repairMap.get(rep1);
+                //system.debug(repairDList);
+                Integer num = (Integer)ar.get('ID') == null ? 0 : (Integer)ar.get('ID');
+                //system.debug(rep1+'--------'+num);
+                for(RepairDetails__c red : repairDList){
+                    red.Name = id_name.get(rep1) + (num > 8 ? '-'+(++num) : '-0'+(++num));
+                }
+                overID.add(rep1);
+                repairMap.put(rep1, repairDList); 
+            }
+            //count(id)涓簄ull鏃惰缃甀D;
+            List<String> newID = new List<String>();
+            if(overID.size() == 0){
+                newId.addAll(repairMap.keySet());
+            }else{
+                for(String id : repairMap.keySet()){
+                    if(overID.contains(id) == false){
+                       newID.add(id);
+                    }
+                }
+            }
+            if(newID.size()>0){
+                List<Repair__c> needList = [select id,Name from Repair__c where id =: newID];
+                for(Repair__c re : needList){
+                    Integer i = 1;
+                    for(RepairDetails__c red : repairMap.get(re.id)){
+                        red.Name = re.Name + (i > 9 ? '-'+(i++) : '-0'+(i++));
+                    }
+                }
+            }
+            //system.debug(newList);
+        }
+        return '';   
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/RepairDetailsTriggerHandler.cls-meta.xml b/scr/classes/RepairDetailsTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/RepairDetailsTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/RepairDetailsTriggerTest.cls b/scr/classes/RepairDetailsTriggerTest.cls
new file mode 100644
index 0000000..16e5ffc
--- /dev/null
+++ b/scr/classes/RepairDetailsTriggerTest.cls
@@ -0,0 +1,42 @@
+@isTest
+private class RepairDetailsTriggerTest {
+	
+	@isTest static void test_method_one() {
+		Repair__c repair1 = new Repair__c();
+		repair1.Name = 'test';
+		insert repair1;
+		
+		Repair__c repair2 = new Repair__c();
+		repair2.Name = 'test';
+		insert repair2;
+
+		RepairDetails__c repairDetails1 = new RepairDetails__c();
+		repairDetails1.Repair__c = repair1.id;
+		repairDetails1.Name = 'test';
+		insert repairDetails1;
+
+		RepairDetails__c repairDetails2 = new RepairDetails__c();
+		repairDetails2.Repair__c = repair1.id;
+		repairDetails2.Name = 'test';
+		insert repairDetails2;
+
+		List<RepairDetails__c> repList = new list<RepairDetails__c>();
+		RepairDetails__c repairDetails3 = new RepairDetails__c();
+		repairDetails3.Repair__c = repair1.id;
+		repairDetails3.Name = 'test';
+
+		RepairDetails__c repairDetails4 = new RepairDetails__c();
+		repairDetails4.Repair__c = repair2.id;
+		repairDetails4.Name = 'test';
+
+		RepairDetails__c repairDetails5 = new RepairDetails__c();
+		repairDetails5.Repair__c = repair2.id;
+		repairDetails5.Name = 'test';
+		
+		repList.add(repairDetails3);
+		repList.add(repairDetails4);
+		repList.add(repairDetails5);
+		insert repList;
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/RepairDetailsTriggerTest.cls-meta.xml b/scr/classes/RepairDetailsTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/RepairDetailsTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/RepairTriggerHandler.cls b/scr/classes/RepairTriggerHandler.cls
new file mode 100644
index 0000000..1ec285a
--- /dev/null
+++ b/scr/classes/RepairTriggerHandler.cls
@@ -0,0 +1,118 @@
+public without sharing class RepairTriggerHandler {
+    public static void setdate(List<Repair__c> newList, Map<Id, Repair__c> newMap, List<Repair__c> oldList, Map<Id, Repair__c> oldMap) {
+        for(Repair__c rep : newList){
+            if(rep.RecordTypeId == '0120K000000wOGe'){
+           // if(rep.RecordTypeId == '0120l000000WwBL'){
+                if(rep.ServicePlace__c == '鐜板満'){
+                    if( rep.CustomerRequestDate__c == null || rep.ServiceStartDate__c== null){
+                        rep.StartDatenwb__c  = null;
+                    }else{
+                        Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.CustomerRequestDate__c,rep.ServiceStartDate__c);
+                        rep.StartDatenwb__c = (calendarUtil.getNumfromCalendarMap(dateMap,rep.CustomerRequestDate__c,rep.ServiceStartDate__c)-1)+'';
+                    }
+                }
+                               
+                if(rep.ServiceType__c=='缁翠慨' ){
+                    if(rep.ServiceProperty__c =='鏈夊伩'){
+                       if( rep.QuotationAgreeDate__c == null || rep.CompletionDate__c== null){
+                           rep.MaintenanceDatewb__c  = null;
+                       }else{
+                           Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.QuotationAgreeDate__c,rep.CompletionDate__c);
+                           rep.MaintenanceDatewb__c = (calendarUtil.getNumfromCalendarMap(dateMap,rep.QuotationAgreeDate__c,rep.CompletionDate__c)-1)+'';
+                       }
+                    }else if(rep.ServiceProperty__c =='鏃犲伩'){
+                       if( rep.ServiceStartDate__c == null || rep.CompletionDate__c== null){
+                           rep.MaintenanceDatewb__c  = null;
+                       }else{
+                           Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.ServiceStartDate__c,rep.CompletionDate__c);
+                           rep.MaintenanceDatewb__c = (calendarUtil.getNumfromCalendarMap(dateMap,rep.ServiceStartDate__c,rep.CompletionDate__c)-1)+'';
+                       }
+                    }else{
+                        rep.MaintenanceDatewb__c = null;
+                    }
+                }else{
+                    rep.MaintenanceDatewb__c = null;
+                }
+                    
+                if(rep.ServiceType__c=='缁翠慨' ){
+                    if(rep.QuotationAgreeDate__c == null ){
+                       if( rep.BugDate__c == null || rep.CompletionDate__c == null){
+                            rep.Downtime__c = null;
+                       }else{
+                           Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.BugDate__c,rep.CompletionDate__c);
+                           rep.Downtime__c = (calendarUtil.getNumfromCalendarMap(dateMap,rep.BugDate__c,rep.CompletionDate__c)-1)+'';
+                       }
+                    }else{
+                        
+                        if(rep.QuotationDate__c == null || rep.QuotationAgreeDate__c == null || rep.BugDate__c == null || rep.CompletionDate__c == null){
+                            rep.Downtime__c = null;
+                        }else{
+                    
+                           Integer num1 = 0;
+                           Integer num2 = 0;
+                       
+                           Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.QuotationDate__c,rep.QuotationAgreeDate__c);
+                           num1 = calendarUtil.getNumfromCalendarMap(dateMap,rep.QuotationDate__c,rep.QuotationAgreeDate__c)-1;
+                       
+                           Map<String,OlympusCalendar__c> dateMap1 = calendarUtil.getCalendarMap(rep.BugDate__c,rep.CompletionDate__c);
+                           num2 = calendarUtil.getNumfromCalendarMap(dateMap1,rep.BugDate__c,rep.CompletionDate__c)-1;
+                       
+                           rep.Downtime__c = (num2 - num1)+'';
+                       }
+                    }                    
+                }else{
+                    rep.Downtime__c = null;
+                }               
+            }else if(rep.RecordTypeId == '0120K000000wOGg'){ //else if(rep.RecordTypeId == '0120l000000WwBQ'){
+                if(rep.ServicePlace__c == '鐜板満'){
+                    if( rep.QuotationAgreeDate__c == null || rep.ReciveRepairDay__c== null){
+                        rep.StartDatenwb__c  = null;
+                    }else{
+                        Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.ReciveRepairDay__c,rep.QuotationAgreeDate__c);
+                        rep.StartDatenwb__c = (calendarUtil.getNumfromCalendarMap(dateMap,rep.ReciveRepairDay__c,rep.QuotationAgreeDate__c)-1)+'';
+                    }
+                }
+                               
+                if(rep.ServiceType__c=='缁翠慨' ||rep.ServiceType__c=='缁存姢' ){
+                 
+                       if( rep.CompletionDate__c == null || rep.QuotationAgreeDate__c== null){
+                           rep.MaintenanceDatewb__c  = null;
+                       }else{
+                           Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.QuotationAgreeDate__c,rep.CompletionDate__c);
+                           rep.MaintenanceDatewb__c = (calendarUtil.getNumfromCalendarMap(dateMap,rep.QuotationAgreeDate__c,rep.CompletionDate__c)-1)+'';
+                       }
+                }else{
+                    rep.MaintenanceDatewb__c = null;
+                }
+                    
+                if(rep.ServiceType__c=='缁翠慨'||rep.ServiceType__c=='缁存姢' ){
+                    if(rep.ReciveRepairDay__c == null || rep.CompletionDate__c == null ){
+                        rep.Downtime__c = null;
+                    }else{
+                       if( rep.ReciveRepairDay__c ==  rep.CompletionDate__c){
+                            rep.Downtime__c ='0';
+                       }else{
+                           if(rep.QuotationDate__c == null || rep.QuotationAgreeDate__c == null || rep.ReciveRepairDay__c == null || rep.CompletionDate__c == null){
+                               rep.Downtime__c = null;
+                            }else{
+                    
+                                Integer num1 = 0;
+                                Integer num2 = 0;
+                       
+                                Map<String,OlympusCalendar__c> dateMap = calendarUtil.getCalendarMap(rep.QuotationDate__c,rep.QuotationAgreeDate__c);
+                                num1 = calendarUtil.getNumfromCalendarMap(dateMap,rep.QuotationDate__c,rep.QuotationAgreeDate__c)-1;
+                       
+                                Map<String,OlympusCalendar__c> dateMap1 = calendarUtil.getCalendarMap(rep.ReciveRepairDay__c,rep.CompletionDate__c);
+                                num2 = calendarUtil.getNumfromCalendarMap(dateMap1,rep.ReciveRepairDay__c,rep.CompletionDate__c)-1;
+                       
+                                rep.Downtime__c = (num2 - num1)+'';
+                           }   
+                       }                        
+                    }                    
+                }else{
+                    rep.Downtime__c = null;
+                }                               
+            }
+        }    
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/RepairTriggerHandler.cls-meta.xml b/scr/classes/RepairTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..e3d1b51
--- /dev/null
+++ b/scr/classes/RepairTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/RepairTriggerHandlerTest.cls b/scr/classes/RepairTriggerHandlerTest.cls
new file mode 100644
index 0000000..fb0d3e1
--- /dev/null
+++ b/scr/classes/RepairTriggerHandlerTest.cls
@@ -0,0 +1,106 @@
+@isTest
+private class RepairTriggerHandlerTest {
+    
+    static testMethod void myUnitTest() {
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc13 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc14 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc15 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc16 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc17 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc13,oc14,oc15,oc16,oc17};
+
+        
+        Repair__c rep1 = new Repair__c();
+        rep1.Name='test';
+        rep1.ServicePlace__c='鐜板満';
+        
+        insert rep1;
+        rep1.ServiceStartDate__c=Date.today().addDays(6);
+        rep1.CustomerRequestDate__c=Date.today().addDays(3);
+        
+        update rep1;
+        
+        rep1.ServiceType__c='缁翠慨';
+        rep1.ServiceProperty__c ='鏈夊伩';
+        
+        update rep1;
+        
+        rep1.QuotationAgreeDate__c =Date.today().addDays(11);
+        rep1.CompletionDate__c=Date.today().addDays(10);
+        update rep1;
+        
+        rep1.ServiceProperty__c ='鏃犲伩';
+        
+        update rep1;
+        
+        rep1.ServiceStartDate__c = null;
+        rep1.CompletionDate__c= null;
+        update rep1;
+        
+        rep1.ServiceType__c=null;
+        update rep1;
+        
+        rep1.ServiceType__c='缁翠慨';
+        rep1.QuotationAgreeDate__c = null ;
+        rep1.BugDate__c = Date.today().addDays(10);
+        rep1.CompletionDate__c =Date.today().addDays(11);
+        update rep1;
+        
+        rep1.QuotationDate__c = null;
+        rep1.QuotationAgreeDate__c = null;
+        rep1.BugDate__c = null; 
+        rep1.CompletionDate__c = null;
+        update rep1;
+        
+        rep1.QuotationDate__c = Date.today().addDays(9);
+        rep1.QuotationAgreeDate__c =  Date.today().addDays(10);
+        rep1.BugDate__c =  Date.today().addDays(1); 
+        rep1.CompletionDate__c = Date.today().addDays(11);
+        update rep1;   
+        
+        
+        Repair__c rep = new Repair__c();
+        rep.Name='test';
+        rep.RecordTypeId = Schema.SObjectType.Repair__c.getRecordTypeInfosByDeveloperName().get('RVI').getRecordTypeId();     
+        rep.ServicePlace__c='鐜板満';
+        insert rep;
+        
+        rep.ReciveRepairDay__c=Date.today().addDays(3);
+        rep.QuotationAgreeDate__c=Date.today().addDays(6);
+        update rep;
+        
+        rep.ServiceType__c='缁翠慨';
+        update rep;
+        
+        rep.QuotationAgreeDate__c = Date.today().addDays(6) ;
+        rep.CompletionDate__c =Date.today().addDays(11);
+        update rep;
+        
+        rep.ServiceType__c='缁存姢';
+        rep.QuotationDate__c = Date.today().addDays(9) ;
+        rep.QuotationAgreeDate__c = Date.today().addDays(10);
+        rep.ReciveRepairDay__c = Date.today().addDays(1) ;
+        rep.CompletionDate__c = Date.today().addDays(11);
+        update rep;
+                             
+        
+        
+     
+        
+                  
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/RepairTriggerHandlerTest.cls-meta.xml b/scr/classes/RepairTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..e3d1b51
--- /dev/null
+++ b/scr/classes/RepairTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG001TriggerHandler.cls b/scr/classes/SBG001TriggerHandler.cls
new file mode 100644
index 0000000..8f43ef4
--- /dev/null
+++ b/scr/classes/SBG001TriggerHandler.cls
@@ -0,0 +1,1057 @@
+// Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+public without sharing class SBG001TriggerHandler {
+    // Account or Contact 鐨処d
+    public static Set<Id> SBG001_Ids = new Set<Id>();
+    public static String debug_msg = '';
+    // 瀹㈡埛璁板綍绫诲瀷_鍔炰簨澶処d
+    public static String   Account_Agency_Id = System.Label.Account_Agency_Id;
+    //001淇敼Rest gwy start 2021-04-06
+    //public class SBG001ResrException extends Exception {}
+    public static String status;
+    public class SBG001 {
+        public SSBDCustomerContacts_element SSBDCustomerContacts;
+    }
+
+    public class SSBDCustomerContacts_element {
+        public NFMUtil.Monitoring Monitoring;
+        public SSBDCustomerContact_element[] SSBDCustomerContact;
+    }
+
+    public class SSBDCustomerContact_element {
+        public String CustomerCode;   
+        public String CustomerDescription;   
+        public String CustomerDescription2Description3;    
+        public String CustomerAreaCity;
+        public String TelephoneMobile;  
+        public String FaxEmail;
+        public String PostalCode;
+        public String Address;   
+        public String CustomerCategory;   
+        public String Industry;
+        public String UserType;
+        public String ContactOffice;   
+        public String ContactCode;  
+        public String ContactEffectiveDateFrom;
+        public String PurposeOfAdvice;
+        
+    }
+        //001淇敼Rest gwy end 2021-04-06
+
+    // on Account (after insert, before update)
+    public static void SBG001AccountTrigger(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
+System.debug('-----SBG001AccountTrigger start');
+        if (NFMUtil.EscapeSBG001TriggerHandler){
+            return;
+        }
+        // TODO needChild 瀵惧繙
+//                enduser.customercode        = con.account.managementcode_f__c;
+//                enduser.customerdescription = con.account.name;
+//                enduser.customerdescription2description3
+//                                            = (string.isblank(con.account.divisionname__c) ? '' : con.account.divisionname__c)
+//                                                + ',' + (string.isblank(con.account.departmentname__c) ? '' : con.account.departmentname__c);
+//                enduser.customerareacity    = (string.isblank(con.account.provincecode__c) ? '' : con.account.provincecode__c)
+//                                                + ',' + (string.isblank(con.account.city__c) ? '' : con.account.city__c);
+//                enduser.customercategory    = '瀹㈡埛' + (string.isblank(con.account.productsegment__c) ? '' : con.account.productsegment__c);
+//                enduser.industry            = 'bs15';       // todo mapping string.isblank(acc.use__c) ? '' : acc.use__c;
+
+        Map<Id, Id> accIds = new Map<Id, Id>();           // 鏇存柊瀵捐薄 Id 銈掋偦銉冦儓
+        System.debug('newList:' + newList.size());
+        if (Trigger.isAfter) {
+            if (Trigger.isInsert) {
+                for(Account acc : newList) {
+                    if ((SBG001TriggerHandler.SBG001_Ids.contains(acc.Id) == false
+                            && (acc.RecordTypeId == '01228000000TdF6'       // IE
+                                || acc.RecordTypeId == '01228000000TdFB'    // RVI
+                                || acc.RecordTypeId == '01228000000TdFG'    // NDT
+                                || acc.RecordTypeId == '01228000000TdFL'    // ANI
+                                || acc.RecordTypeId == '01228000000TdF1'    // BS
+                            )
+                            && acc.stautesD__c == 'Pass') || acc.RecordTypeId == SBG001TriggerHandler.Account_Agency_Id //鍔炰簨澶�
+                    ) {
+                        accIds.put(acc.Id, acc.Id);
+                        SBG001TriggerHandler.SBG001_Ids.add(acc.Id);
+                        SBG001TriggerHandler.debug_msg += 'SBG001_callout_insert_' + acc.Name;
+                    }
+                }
+            }
+        }
+        if (Trigger.isBefore) {
+            if (Trigger.isUpdate) {
+                for(Account acc : newList) {
+                    Account old = oldMap.get(acc.Id);
+                    if ((SBG001TriggerHandler.SBG001_Ids.contains(acc.Id) == false
+                            && (acc.RecordTypeId == '01228000000TdF6'       // IE
+                                || acc.RecordTypeId == '01228000000TdFB'    // RVI
+                                || acc.RecordTypeId == '01228000000TdFG'    // NDT
+                                || acc.RecordTypeId == '01228000000TdFL'    // ANI
+                                || acc.RecordTypeId == '01228000000TdF1'    // BS 
+                            )
+                            && acc.stautesD__c == 'Pass'
+                            && (acc.ManagementCode_Ext__c       != old.ManagementCode_Ext__c
+                                    || acc.stautesD__c          != old.stautesD__c
+                                    || acc.AccountStatus__c     != old.AccountStatus__c
+                                    || acc.DivisionName__c      != old.DivisionName__c
+                                    || acc.DepartmentName__c    != old.DepartmentName__c
+                                    || acc.ProvinceCode__c      != old.ProvinceCode__c
+                                    || acc.City__c              != old.City__c
+                                    || acc.Phone                != old.Phone
+                                    || acc.MobilePhoneNumber__c != old.MobilePhoneNumber__c
+                                    || acc.Fax                  != old.Fax
+                                    || acc.PostCode__c          != old.PostCode__c
+                                    || acc.Address1__c          != old.Address1__c
+                                    || acc.ProductSegment__c    != old.ProductSegment__c
+                                    || acc.Use__c               != old.Use__c
+                                    || acc.Sub_Use__c           != old.Sub_Use__c
+                                    || acc.EnglishName__c       != old.EnglishName__c
+                                    || acc.Name                 != old.Name
+                            )) || acc.RecordTypeId == SBG001TriggerHandler.Account_Agency_Id// 鍔炰簨澶�
+                    ) {
+                        accIds.put(acc.Id, acc.Id);
+                        SBG001TriggerHandler.SBG001_Ids.add(acc.Id);
+                        SBG001TriggerHandler.debug_msg += 'SBG001_callout_update_' + acc.Name;
+                    }
+                }
+            }
+        }
+        if (Trigger.isBefore) {
+            if (Trigger.isUpdate) {
+                for(Account acc : newList) {
+                    Account old = oldMap.get(acc.Id);
+                    System.debug('isBatch__c'+acc.isBatch__c);
+                    if ( acc.isBatch__c == true) {
+                        acc.isBatch__c = false;
+                        if(accIds.containsKey(acc.Id) == false){
+                            accIds.put(acc.Id, acc.Id);
+                            SBG001TriggerHandler.SBG001_Ids.add(acc.Id);
+                            SBG001TriggerHandler.debug_msg += 'SBG001_callout_update_' + acc.Name;
+                        }
+                    }
+                }
+            }
+        }
+        if (accIds.size() > 0) {
+            // MessageGroupNumber 銇帯鐣�
+            BatchIF_Log__c iflog = new BatchIF_Log__c();
+            iflog.Type__c = 'SBG001';
+            iflog.Log__c  = 'callout start\n';
+            insert iflog;
+            iflog = [Select Id, Name from BatchIF_Log__c where Id = :iflog.Id];
+            System.debug(Logginglevel.DEBUG, 'SBG001_A_' + iflog.Name + ' start');                  // callout 銇腑 end 銇甽og銈掑嚭銇椼伨銇�
+            SBG001TriggerHandler.calloutAccount(iflog.Id, accIds.values());
+        }
+System.debug('-----SBG001AccountTrigger end');
+    }
+
+    // on Contact (after insert, before update)
+    public static void SBG001ContactTrigger(List<Contact> newList, Map<Id, Contact> newMap, List<Contact> oldList, Map<Id, Contact> oldMap) {
+System.debug('-----SBG001ContactTrigger start');
+        if (NFMUtil.EscapeSBG001TriggerHandler){
+            return;
+        }
+        Map<Id, Id> conIds = new Map<Id, Id>();           // 鏇存柊瀵捐薄 Id 銈掋偦銉冦儓
+        if (Trigger.isAfter) {
+            if (Trigger.isInsert) {
+                for(Contact con : newList) {
+                    System.debug('con++++++锛�' + con.Name);
+                    if ((SBG001TriggerHandler.SBG001_Ids.contains(con.Id) == false
+                            && (con.AccountRecordTypeId__c == '01228000000TdFL'         // ANI
+                                || con.AccountRecordTypeId__c == '01228000000TdF6'      // IE
+                                || con.AccountRecordTypeId__c == '01228000000TdFB'      // RVI
+                                || con.AccountRecordTypeId__c == '01228000000TdFG'      // NDT
+                                || con.AccountRecordTypeId__c == '01228000000TdF1'      // BS
+                            )
+                            && con.StatusD__c == 'Pass') || con.AccountRecordTypeId__c == SBG001TriggerHandler.Account_Agency_Id// 鍔炰簨澶�
+                    ) {
+                        if (!con.CampaignUpsertContact__c) {
+                            conIds.put(con.Id, con.Id);
+                            SBG001TriggerHandler.SBG001_Ids.add(con.Id);    
+                        }
+                        
+                        //TODO Name 鍙樻洿 澶辫触
+                        SBG001TriggerHandler.debug_msg += 'SBG001_callout_insert_' + con.FirstName + con.LastName;
+                    }
+                }
+            }
+        }
+        if (Trigger.isBefore) {
+            if (Trigger.isUpdate) {
+                for(Contact con : newList) {
+                    Contact old = oldMap.get(con.Id);
+                    if (SBG001TriggerHandler.SBG001_Ids.contains(con.Id) == false
+                            && (con.AccountRecordTypeId__c == '01228000000TdFL'         // ANI
+                                || con.AccountRecordTypeId__c == '01228000000TdF6'      // IE
+                                || con.AccountRecordTypeId__c == '01228000000TdFB'      // RVI
+                                || con.AccountRecordTypeId__c == '01228000000TdFG'      // NDT
+                                || con.AccountRecordTypeId__c == '01228000000TdF1'      // BS
+                                || con.AccountRecordTypeId__c == SBG001TriggerHandler.Account_Agency_Id // 鍔炰簨澶�
+                            )
+                            && con.StatusD__c == 'Pass'
+                            && (con.ManagementCode_Ext__c   != old.ManagementCode_Ext__c
+                                    || con.StatusD__c       != old.StatusD__c
+                                    || con.ContactStatus__c != old.ContactStatus__c
+                                    || con.LastName         != old.LastName
+                                    || con.Phone            != old.Phone
+                                    || con.MobilePhone      != old.MobilePhone
+                                    || con.Fax              != old.Fax
+                                    || con.Email            != old.Email
+                                    || con.PostCode__c      != old.PostCode__c
+                                    || con.Address1__c      != old.Address1__c
+                                    || con.Department       != old.Department
+                                    || con.FirstName        != old.FirstName
+                            )
+                    ) { 
+                        if (!con.CampaignUpsertContact__c) {
+                            conIds.put(con.Id, con.Id);
+                            SBG001TriggerHandler.SBG001_Ids.add(con.Id);
+                        }
+                        //TODO Name 鍙樻洿 澶辫触
+                        SBG001TriggerHandler.debug_msg += 'SBG001_callout_update_' + con.FirstName + con.LastName;
+                    }
+                }
+            }
+        }
+        if (Trigger.isBefore) {
+            if (Trigger.isUpdate) {
+                for(Contact con : newList) {
+                    Contact old = oldMap.get(con.Id);
+                    System.debug('isBatch__c:' + con.isBatch__c);
+                    if (con.isBatch__c == true) {
+                        con.isBatch__c = false;
+                        // con.CampaignUpsertContact__c = false;
+                        if(conIds.containsKey(con.Id) == false){
+                            conIds.put(con.Id, con.Id);
+                        
+                            SBG001TriggerHandler.SBG001_Ids.add(con.Id);
+                            //TODO Name 鍙樻洿 澶辫触
+                            SBG001TriggerHandler.debug_msg += 'SBG001_callout_update_' + con.FirstName + con.LastName;
+                        }
+                    }
+                }
+            }
+        }
+        if (conIds.size() > 0) {
+            // MessageGroupNumber 銇帯鐣�
+            BatchIF_Log__c iflog = new BatchIF_Log__c();
+            iflog.Type__c = 'SBG001';
+            iflog.Log__c  = 'callout start\n';
+            insert iflog;
+            iflog = [Select Id, Name from BatchIF_Log__c where Id = :iflog.Id];
+            System.debug(Logginglevel.DEBUG, 'SBG001_C_' + iflog.Name + ' start');                  // callout 銇腑 end 銇甽og銈掑嚭銇椼伨銇�
+            SBG001TriggerHandler.calloutContact(iflog.Id, conIds.values());
+        }
+System.debug('-----SBG001ContactTrigger end');
+    }
+
+    /**
+     * SBG001Account 鐨勯�佷俊鍑︾悊
+     *
+     * @param iflog_Id        銉偘銉嗐兗銉栥儷銇甀d
+     * @param accIds          閫佷俊瀵捐薄淇悊
+     */
+    @future (callout=true)
+    public static void calloutAccount(String iflog_Id, List<Id> accIds) {
+        if (accIds == null || accIds.size() == 0) {
+            return;
+        }
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        SBG001TriggerHandler.SBG001_Ids.addAll(accIds);
+        /*Sbg001Sync.HTTPS_Port stub = new Sbg001Sync.HTTPS_Port();
+        //Endusers_element stub = new Endusers_element();
+        stub.timeout_x = 100000; // timeout in milliseconds
+        stub.endpoint_x = NFMUtil.SBG001_ENDPOINT;
+        stub.inputHttpHeaders_x = new Map<String, String>();
+        stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+        if (NFMUtil.CLIENT_CERT_NAME != null) {
+            stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+        }*/
+        // 鑾峰彇 杞崲琛�
+        Map<String, String> transferMap = NFMUtil.BatchIF_Transfer('Account');
+        // MessageGroupNumber 銇彇寰�
+        List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c,retry_cnt__c from BatchIF_Log__c where Id = :iflog_Id];
+        BatchIF_Log__c iflog = null;
+        if (iflogList.size() > 0) {
+            iflog = iflogList.get(0);
+            iflog.ErrorLog__c = '';
+        } else {
+            // 銉囥兗銈垮彇銈屻仯銇︺仾銇勩仺銇�乺ollback銇曘倢銇︺亜銈嬨亾銇ㄣ仹銇�
+            return;
+        }
+        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + accIds.size() + '\n';
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        //001淇敼涓篟est gwy 2020-01-06 start
+        //Sbg001Sync.SSBDCustomerContacts_element endusers = new Sbg001Sync.SSBDCustomerContacts_element();
+        SSBDCustomerContacts_element SSBDCustomerContacts = new SSBDCustomerContacts_element();
+        //001淇敼涓篟est gwy 2020-01-06 end
+        SSBDCustomerContacts.Monitoring = new NFMUtil.Monitoring();
+        SSBDCustomerContacts.Monitoring.Tag                  = 'MSGH';
+        SSBDCustomerContacts.Monitoring.Sender               = '8405';
+        SSBDCustomerContacts.Monitoring.Receiver             = '1330';
+        SSBDCustomerContacts.Monitoring.MessageType          = 'SBG001';
+        SSBDCustomerContacts.Monitoring.MessageGroupNumber   = iflog.Name;
+        SSBDCustomerContacts.Monitoring.NumberOfRecord       = '' + accIds.size();
+        SSBDCustomerContacts.Monitoring.TransmissionDateTime = nowStr;
+        SSBDCustomerContacts.Monitoring.Text = '';
+        BatchIF_Log__c rowData = null;
+        try {
+            // 杌㈤�併儑銉笺偪銈掑彇寰�
+            List<Account> accList = [select
+                    Id, Name, FacilityName__c, RecordType.DeveloperName,
+                    AccountStatus__c, ManagementCode_F__c, DivisionName__c, DepartmentName__c, EnglishName__c,
+                    ProvinceCode__c, City__c, Phone, MobilePhoneNumber__c,
+                    Fax, PostCode__c, Address1__c,
+                    ProductSegment__c, MarketVerticals__c, Use__c, Sub_Use__c,
+                    CreatedDate, LastModifiedDate,
+                    UserType__c
+               from Account where Id IN :accIds];          // 鍓婇櫎銉囥兗銈裤倰妞滅储銇椼仾銇勩伅銇氥�丄ll ROWS 銇勩倝銇亜銇仛
+            System.debug(Logginglevel.DEBUG, 'SBG001_' + iflog.Name + ' accList.size()=' + accList.size());
+
+            // Enduser銇儑銉笺偪銇ō瀹�
+            //001淇敼涓篟est gwy 2020-01-06 start
+            //endusers.SSBDCustomerContact = new List<Sbg001Sync.SSBDCustomerContact_element>();
+            SSBDCustomerContacts.SSBDCustomerContact = new List<SSBDCustomerContact_element>();
+            //001淇敼涓篟est gwy 2020-01-06 end
+            for (Account acc : accList) {
+                //001淇敼涓篟est gwy 2020-01-06 start
+                //Sbg001Sync.SSBDCustomerContact_element enduser = new Sbg001Sync.SSBDCustomerContact_element();
+                //endusers.SSBDCustomerContact.add(enduser);
+                SSBDCustomerContact_element SSBDCustomerContact = new SSBDCustomerContact_element();
+                SSBDCustomerContacts.SSBDCustomerContact.add(SSBDCustomerContact);
+                //001淇敼涓篟est gwy 2020-01-06 end
+                SSBDCustomerContact.CustomerCode        = acc.ManagementCode_F__c;
+                SSBDCustomerContact.CustomerDescription = acc.FacilityName__c;
+                SSBDCustomerContact.CustomerDescription2Description3
+                                            = (String.isBlank(acc.DivisionName__c) ? '' : (acc.DivisionName__c=='鏃�' ? '' : acc.DivisionName__c));
+                if (acc.RecordTypeId == '01228000000TdF6' || acc.RecordTypeId == '01228000000TdFB' ||  acc.RecordTypeId == '01228000000TdFG' ||  acc.RecordTypeId == '01228000000TdFL') {      // IE or RVI
+                    SSBDCustomerContact.CustomerDescription2Description3 += ',' + (String.isBlank(acc.EnglishName__c) ? '' : acc.EnglishName__c);
+                } else {
+                    SSBDCustomerContact.CustomerDescription2Description3 += ',' + (String.isBlank(acc.DepartmentName__c) ? '' : acc.Departmentname__c);
+                }
+                SSBDCustomerContact.CustomerAreaCity    = (String.isBlank(acc.ProvinceCode__c) ? '' : acc.ProvinceCode__c)
+                                                + ',' + (String.isBlank(acc.City__c) ? '' : acc.City__c);
+                SSBDCustomerContact.TelephoneMobile     = (String.isBlank(acc.Phone) ? '' : acc.Phone)
+                                                + ',' + (String.isBlank(acc.MobilePhoneNumber__c) ? '' : acc.MobilePhoneNumber__c);
+                SSBDCustomerContact.FaxEmail            = String.isBlank(acc.Fax) ? '' : acc.Fax + ',';
+                SSBDCustomerContact.PostalCode          = String.isBlank(acc.PostCode__c) ? '' : acc.PostCode__c;
+                SSBDCustomerContact.Address             = String.isBlank(acc.Address1__c) ? '' : acc.Address1__c;
+                SSBDCustomerContact.CustomerCategory    = GetCustomerCategory(acc,null);//'瀹㈡埛' + (String.isBlank(acc.ProductSegment__c) ? '' : acc.ProductSegment__c);
+                //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-Start-20200525)
+                SSBDCustomerContact.UserType = '';
+                if ('Customer_IE'.equals(acc.RecordType.DeveloperName)) {
+                    // || 'Customer_BS'.equals(acc.RecordType.DeveloperName)
+                    // 20210527-SSBG璇环鍚堝悓浼樺寲椤圭洰-XHL Start
+                    String ExternalValue = acc.RecordType.DeveloperName + ':' + acc.UserType__c;
+                    SSBDCustomerContact.UserType            = GetUserType(ExternalValue,transferMap);
+                    // 20210527-SSBG璇环鍚堝悓浼樺寲椤圭洰-XHL End
+                } 
+                SSBDCustomerContact.Industry            = mappingUse(acc.RecordType.DeveloperName, acc.Use__c, acc.Sub_Use__c,transferMap); 
+                // else {
+                //     SSBDCustomerContact.Industry            = mappingUse(acc.RecordType.DeveloperName, acc.Use__c, acc.Sub_Use__c);  
+                // }
+                //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-End-20200525)
+                
+                SSBDCustomerContact.ContactOffice       = '';
+                SSBDCustomerContact.ContactCode         = acc.ManagementCode_F__c;
+                SSBDCustomerContact.ContactEffectiveDateFrom
+                                            = NFMUtil.formatDate2Str(acc.CreatedDate.date());
+                // PurposeOfAdvice 1:Delete 2:Add(Insert) 3:Change(Update)
+                String purposeOfAdvice = '3';
+                if (acc.AccountStatus__c == 'Cancel') {
+                    purposeOfAdvice    = '1';
+                }
+                else if (acc.CreatedDate == acc.LastModifiedDate) {
+                    purposeOfAdvice    = '2';
+                }
+                SSBDCustomerContact.PurposeOfAdvice     = purposeOfAdvice;
+                logstr += SSBDCustomerContact.CustomerCode + '(' + purposeOfAdvice + ')\n';
+            }
+
+            if (SSBDCustomerContacts.SSBDCustomerContact.size() > 0) {
+                if (System.Label.SBG001_IsOn == '1') {
+                    //001淇敼涓篟est gwy 2020-01-06 start
+                    //Sbg001Sync.SSBDCustomerContacts_element[] pEndusers = new Sbg001Sync.SSBDCustomerContacts_element[] { endusers };
+                    logstr += '\ncallout count=' + SSBDCustomerContacts.SSBDCustomerContact.size();
+                    //001淇敼涓篟est gwy 2020-01-06 end
+                    //OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG001_Sync_BC2GPI(pEndusers);
+                    // 鍘熷墖闈炲悓鏈熴仹銇欍伄銇с�乴ogs銈掔⒑瑾嶃仚銈嬪繀瑕併亴銇亜銇с仐銈囥亞銆�
+                    NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+                    Monitoring.Tag                  = SSBDCustomerContacts.Monitoring.Tag;
+                    Monitoring.Sender               = SSBDCustomerContacts.Monitoring.Sender;
+                    Monitoring.Receiver             = SSBDCustomerContacts.Monitoring.Receiver;
+                    Monitoring.MessageType          = SSBDCustomerContacts.Monitoring.MessageType;
+                    Monitoring.MessageGroupNumber   = SSBDCustomerContacts.Monitoring.MessageGroupNumber;
+                    Monitoring.NumberOfRecord       = SSBDCustomerContacts.Monitoring.NumberOfRecord;
+                    Monitoring.TransmissionDateTime = SSBDCustomerContacts.Monitoring.TransmissionDateTime;
+                    Monitoring.Text = '';
+
+                    // NFM001淇敼Rest 鏂板 start
+                    SBG001 sbg001 = new SBG001();
+                    sbg001.SSBDCustomerContacts = SSBDCustomerContacts;
+                    // NFM001淇敼Rest 鏂板 end
+
+                    //001淇敼涓篟est gwy 2020-01-06 start
+                    rowData = NFMUtil.makeRowData(Monitoring, 'SBG001', sbg001);
+                    // String rowDataStr = NFMUtil.getRowDataStr(rowData);
+                    // status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.SBG001_ENDPOINT); 
+                    // if (status == 'OK') {
+                    //     logstr += '\nstatus='+status;
+                    //     rowData.retry_cnt__c = 0;
+                    // } else {
+                    //     if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+                    //     if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                    //         rowData.retry_cnt__c++;
+                    //         LogAutoSendSchedule.assignOneMinute();
+                    //     }
+                    //     if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                    //         rowData.ErrorLog__c = 'status:' + status +
+                    //                               '\n閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+                    //     }
+                    // }
+                    //001淇敼涓篟est gwy 2020-01-06 end
+                    iflog.Log__c = logstr;
+                    execute(rowData, iflog);
+                }else{
+                    iflog.ErrorLog__c += 'SBG001_IsOff';
+                }
+            }
+            // logstr += '\nend';
+            // rowData.retry_cnt__c=0;
+        } catch (Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG001_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG001_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+        }
+        // if (rowData != null) {
+        //     insert rowData;
+        // }
+        // System.debug(Logginglevel.DEBUG, 'SBG001_' + iflog.Name + ' end');
+        // iflog.Log__c = logstr;
+        // update iflog;
+    }
+
+    /**
+     * SBG001Contact 鐨勯�佷俊鍑︾悊
+     *
+     * @param iflog_Id        銉偘銉嗐兗銉栥儷銇甀d
+     * @param conIds          閫佷俊瀵捐薄淇悊
+     */
+    @future (callout=true)
+    public static void calloutContact(String iflog_Id, List<Id> conIds) {
+        if (conIds == null || conIds.size() == 0) {
+            return;
+        }
+        calloutContactNotFuture(iflog_Id,conIds);
+    }
+    public static void calloutContactNotFuture(String iflog_Id, List<Id> conIds) {
+        if (conIds == null || conIds.size() == 0) {
+            return;
+        }
+        SBG001TriggerHandler.SBG001_Ids.addAll(conIds);
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        /*Sbg001Sync.HTTPS_Port stub = new Sbg001Sync.HTTPS_Port();
+        stub.timeout_x = 100000; // timeout in milliseconds
+        stub.endpoint_x = NFMUtil.SBG001_ENDPOINT;
+        stub.inputHttpHeaders_x = new Map<String, String>();
+        stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+        if (NFMUtil.CLIENT_CERT_NAME != null) {
+            stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+        }*/
+
+        // MessageGroupNumber 銇彇寰�
+        List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c,retry_cnt__c from BatchIF_Log__c where Id = :iflog_Id];
+        BatchIF_Log__c iflog = new BatchIF_Log__c();//null;
+        String messageGroupNumber = '';
+        // 鑾峰彇 杞崲琛�
+        Map<String, String> transferMap = NFMUtil.BatchIF_Transfer('Account');
+        if (iflogList.size() > 0) {
+            iflog = iflogList.get(0);
+            iflog.ErrorLog__c = '';
+            messageGroupNumber = iflog.Name;
+        } else {
+            // 銉囥兗銈垮彇銈屻仯銇︺仾銇勩仺銇�乺ollback銇曘倢銇︺亜銈嬨亾銇ㄣ仹銇�
+            iflog.Type__c = 'SBG001';
+            iflog.Log__c  = 'callout start\n';
+            messageGroupNumber = String.valueOf(Datetime.now().format('yyyyMMddHHmmss'));
+            iflog.MessageGroupNumber__c = messageGroupNumber;
+            iflog.ErrorLog__c = '';
+            // iflog.Log__c  = 'callout start\n';
+            // return;
+        }
+        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + conIds.size() + '\n';
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        //001淇敼涓篟est gwy 2020-01-06 start
+        //Sbg001Sync.SSBDCustomerContacts_element endusers = new Sbg001Sync.SSBDCustomerContacts_element();
+        SSBDCustomerContacts_element SSBDCustomerContacts = new SSBDCustomerContacts_element();
+        SSBDCustomerContacts.Monitoring = new NFMUtil.Monitoring();
+        //001淇敼涓篟est gwy 2020-01-06 end
+        SSBDCustomerContacts.Monitoring.Tag                  = 'MSGH';
+        SSBDCustomerContacts.Monitoring.Sender               = '8405';
+        SSBDCustomerContacts.Monitoring.Receiver             = '1330';
+        SSBDCustomerContacts.Monitoring.MessageType          = 'SBG001';
+        SSBDCustomerContacts.Monitoring.MessageGroupNumber   = messageGroupNumber;//iflog.Name;
+        SSBDCustomerContacts.Monitoring.NumberOfRecord       = '' + conIds.size();
+        SSBDCustomerContacts.Monitoring.TransmissionDateTime = nowStr;
+        SSBDCustomerContacts.Monitoring.Text = '';
+        BatchIF_Log__c rowData = null;
+        try {
+            // 杌㈤�併儑銉笺偪銈掑彇寰�
+            List<Contact> conList = [select
+                    Id, Name, Account.Name, Account.FacilityName__c, Account.DivisionName__c, Account.DepartmentName__c, Account.EnglishName__c,
+                    AccountRecordTypeId__c, Account.RecordType.DeveloperName, Account.ManagementCode_F__c,
+                    Account.ProvinceCode__c, Account.City__c,
+                    Account.ProductSegment__c, Account.MarketVerticals__c, Account.Use__c, Account.Sub_Use__c,
+                    ContactStatus__c, ManagementCode_F__c, Department,
+                    Phone, MobilePhone,
+                    Fax, Email, PostCode__c, Address1__c,
+                    CreatedDate, LastModifiedDate,
+                    Account.UserType__c
+               from Contact where Id IN :conIds];          // 鍓婇櫎銉囥兗銈裤倰妞滅储銇椼仾銇勩伅銇氥�丄ll ROWS 銇勩倝銇亜銇仛
+            // System.debug(Logginglevel.DEBUG, 'SBG001_' + iflog.Name + ' conList.size()=' + conList.size());
+
+            // Enduser銇儑銉笺偪銇ō瀹�
+            //001淇敼涓篟est gwy 2020-01-06 start
+            //endusers.SSBDCustomerContact = new List<Sbg001Sync.SSBDCustomerContact_element>();
+            SSBDCustomerContacts.SSBDCustomerContact = new List<SSBDCustomerContact_element>();
+            //001淇敼涓篟est gwy 2020-01-06 end
+            for (Contact con : conList) {
+                //001淇敼涓篟est gwy 2020-01-06 start
+                //Sbg001Sync.SSBDCustomerContact_element enduser = new Sbg001Sync.SSBDCustomerContact_element();
+                SSBDCustomerContact_element SSBDCustomerContact = new SSBDCustomerContact_element();
+                SSBDCustomerContacts.SSBDCustomerContact.add(SSBDCustomerContact);
+                //endusers.SSBDCustomerContact.add(enduser);
+                //001淇敼涓篟est gwy 2020-01-06 end
+                SSBDCustomerContact.CustomerCode        = con.Account.ManagementCode_F__c;
+                SSBDCustomerContact.CustomerDescription = con.Account.FacilityName__c;
+                SSBDCustomerContact.CustomerDescription2Description3
+                                        = (String.isBlank(con.Account.DivisionName__c) ? '' : (con.Account.DivisionName__c=='鏃�' ? '' : con.Account.DivisionName__c));
+                if (con.AccountRecordTypeId__c == '01228000000TdF6' || con.AccountRecordTypeId__c == '01228000000TdFB' || con.AccountRecordTypeId__c == '01228000000TdFG' || con.AccountRecordTypeId__c == '01228000000TdFL') {      // IE or RVI
+                    SSBDCustomerContact.CustomerDescription2Description3 += ',' + (String.isBlank(con.Account.EnglishName__c) ? '' : con.Account.EnglishName__c);
+                } else {
+                    SSBDCustomerContact.CustomerDescription2Description3 += ',' + (String.isBlank(con.Account.DepartmentName__c) ? '' : con.Account.Departmentname__c);
+                }
+                SSBDCustomerContact.CustomerAreaCity    = (String.isBlank(con.Account.ProvinceCode__c) ? '' : con.Account.ProvinceCode__c)
+                                                + ',' + (String.isBlank(con.Account.City__c) ? '' : con.Account.City__c);
+                SSBDCustomerContact.TelephoneMobile     = (String.isBlank(con.Phone) ? '' : con.Phone)
+                                                + ',' + (String.isBlank(con.MobilePhone) ? '' : con.MobilePhone);
+                SSBDCustomerContact.FaxEmail            = (String.isBlank(con.Fax) ? '' : con.Fax)
+                                                + ',' + (String.isBlank(con.Email) ? '' : con.Email);
+                SSBDCustomerContact.PostalCode          = String.isBlank(con.PostCode__c) ? '' : con.PostCode__c;
+                SSBDCustomerContact.Address             = String.isBlank(con.Address1__c) ? '' : con.Address1__c;
+                SSBDCustomerContact.CustomerCategory    = GetCustomerCategory(null,con);//'瀹㈡埛' + (String.isBlank(con.Account.ProductSegment__c) ? '' : con.Account.ProductSegment__c);
+                //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-Start-20200525)
+                SSBDCustomerContact.UserType = '';
+                if ('Customer_IE'.equals(con.Account.RecordType.DeveloperName)) {
+                     // || 'Customer_BS'.equals(con.Account.RecordType.DeveloperName)
+                    String ExternalValue = con.Account.RecordType.DeveloperName + ':' + con.Account.UserType__c;
+                    SSBDCustomerContact.UserType            = GetUserType(ExternalValue,transferMap);
+                } 
+                
+                SSBDCustomerContact.Industry            = mappingUse(con.Account.RecordType.DeveloperName, con.Account.Use__c, con.Account.Sub_Use__c,transferMap);
+                //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-End-20200525)
+                SSBDCustomerContact.ContactOffice       = String.isBlank(con.Name) ? '' : con.Name;
+                SSBDCustomerContact.ContactCode         = con.ManagementCode_F__c;
+                SSBDCustomerContact.ContactEffectiveDateFrom
+                                            = NFMUtil.formatDate2Str(con.CreatedDate.date());
+                // PurposeOfAdvice 1:Delete 2:Add(Insert) 3:Change(Update)
+                String purposeOfAdvice = '3';
+                if (con.ContactStatus__c == 'Cancel') {
+                    purposeOfAdvice    = '1';
+                }
+                else if (con.CreatedDate == con.LastModifiedDate) {
+                    purposeOfAdvice    = '2';
+                }
+                SSBDCustomerContact.PurposeOfAdvice     = purposeOfAdvice;
+                logstr += SSBDCustomerContact.CustomerCode + '(' + purposeOfAdvice + ')-'+SSBDCustomerContact.ContactCode + '\n';
+            }
+            if (SSBDCustomerContacts.SSBDCustomerContact.size() > 0) {
+                if (System.Label.SBG001_IsOn == '1') {
+                    //Sbg001Sync.SSBDCustomerContacts_element[] pEndusers = new Sbg001Sync.SSBDCustomerContacts_element[] { endusers };
+                    logstr += '\ncallout count=' + SSBDCustomerContacts.SSBDCustomerContact.size();
+                    //system.debug('pEndusers--->'+pEndusers);
+                    //OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG001_Sync_BC2GPI(pEndusers);
+                    // 鍘熷墖闈炲悓鏈熴仹銇欍伄銇с�乴ogs銈掔⒑瑾嶃仚銈嬪繀瑕併亴銇亜銇с仐銈囥亞銆�
+                    NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+                    Monitoring.Tag                  = SSBDCustomerContacts.Monitoring.Tag;
+                    Monitoring.Sender               = SSBDCustomerContacts.Monitoring.Sender;
+                    Monitoring.Receiver             = SSBDCustomerContacts.Monitoring.Receiver;
+                    Monitoring.MessageType          = SSBDCustomerContacts.Monitoring.MessageType;
+                    Monitoring.MessageGroupNumber   = SSBDCustomerContacts.Monitoring.MessageGroupNumber;
+                    Monitoring.NumberOfRecord       = SSBDCustomerContacts.Monitoring.NumberOfRecord;
+                    Monitoring.TransmissionDateTime = SSBDCustomerContacts.Monitoring.TransmissionDateTime;
+                    Monitoring.Text = '';
+
+                    // NFM001淇敼Rest 鏂板 start
+                    SBG001 sbg001 = new SBG001();
+                    sbg001.SSBDCustomerContacts = SSBDCustomerContacts;
+                    // NFM001淇敼Rest 鏂板 end
+
+                    //001淇敼涓篟est gwy 2020-01-06 start
+                    rowData = NFMUtil.makeRowData(Monitoring, 'SBG001', sbg001);
+                    // String rowDataStr = NFMUtil.getRowDataStr(rowData);
+                    // status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.SBG001_ENDPOINT); 
+                    // if (status == 'OK') {
+                    //     logstr += '\nstatus='+status;
+                    //     rowData.retry_cnt__c = 0;
+                    // } else {
+                    //     if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+                    //     if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                    //         rowData.retry_cnt__c++;
+                    //         LogAutoSendSchedule.assignOneMinute();
+                    //     }
+                    //     if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                    //         rowData.ErrorLog__c = 'status:' + status +
+                    //                               '\n閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+                    //     }
+                    // }
+                    //001淇敼涓篟est gwy 2020-01-06 end
+                    iflog.Log__c = logstr;
+                    execute(rowData, iflog);
+                }else{
+                    iflog.ErrorLog__c += 'SBG001_IsOff';
+                }
+            }
+            // logstr += '\nend';
+            // rowData.retry_cnt__c=0;
+            //iflogList.retry_cnt__c=0;
+
+        } catch (Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG001_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG001_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+        }
+        // if (rowData != null) {
+        //     insert rowData;
+        // }
+
+        // System.debug(Logginglevel.DEBUG, 'SBG001_' + iflog.Name + ' end');
+        // iflog.Log__c = logstr;
+        // upsert iflog;
+    }
+
+    public static String mappingUse(String recordTypeDeveloperName, String use, String subUse,Map<String, String> transferMap) {
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        String External_value = recordTypeDeveloperName + ':'+subUse;
+        String Field_API = 'Sub_Use__c';
+        if ('Customer_BS'.equals(recordTypeDeveloperName)) {
+            if (String.isBlank(use)) {
+                return '';
+            }
+            External_value = recordTypeDeveloperName + ':'+use; 
+            Field_API = 'Use__c';
+        } else if ('Customer_RVI'.equals(recordTypeDeveloperName) || 'Customer_IE'.equals(recordTypeDeveloperName) ||
+                 'Customer_NDT'.equals(recordTypeDeveloperName) || 'Customer_ANI'.equals(recordTypeDeveloperName)) {
+            if (String.isBlank(subUse)) {
+               return '';
+            }
+            
+        } else {
+            return '';
+        }
+        
+        String result = NFMUtil.getMapValue(transferMap, Field_API, External_value, iflog);
+        if (External_value.equals(result)) {
+            result = External_value.split(':')[1];
+        }
+        return result;
+    }
+    //IE/LS鏈�缁堢敤鎴�(鐢ㄦ埛灞炴�ц浆鎹�)
+    public static String GetUserType(String userType,Map<String, String> transferMap){
+        
+        if (String.isBlank(userType)){
+            return '';
+        }
+        BatchIF_Log__c iflog = new BatchIF_Log__c();       
+        // Map<String, String> transferMap = NFMUtil.BatchIF_Transfer('Account');
+        String result = NFMUtil.getMapValue(transferMap, 'UserType__c', userType, iflog); 
+        return result;
+    } 
+
+    /**
+     * XHL 20210819
+     *
+     * @param      acc   瀹㈡埛
+     * @param      con   鑱旂郴浜�
+     *
+     * @return     鑾峰彇瀹㈡埛鐨勮褰曠被鍨�
+     */
+    public static String GetCustomerCategory(Account acc,Contact con){
+        //鍔炰簨澶勫鎴烽粯璁S
+        String result = '瀹㈡埛BS';
+        // 鑾峰彇瀹㈡埛璁板綍绫诲瀷ID
+        String recordTypeId = acc != null ? acc.RecordTypeId:con.Account.RecordTypeId;
+        // 鑾峰彇瀹㈡埛鐨� 浜у搧鍒嗙被   
+        String productSegment = acc != null ? acc.ProductSegment__c:con.Account.ProductSegment__c;
+
+        if (!recordTypeId.equals(SBG001TriggerHandler.Account_Agency_Id)) {
+           result = '瀹㈡埛' + (String.isBlank(productSegment) ? '' : productSegment);
+        }
+        return result;
+    }
+
+    /**
+     * 绯荤粺鍙戦�佹帴鍙eけ璐ワ紝绠$悊鍛樻墜鍔ㄦ墽琛�
+     *
+     * @param      rowDataId  BatchLog Id
+     */
+    public static void execute2(String rowDataId) {
+        List<BatchIF_Log__c> row = [select id, name, MessageGroupNumber__c, retry_cnt__c,
+                                           RowDataFlg__c, ErrorLog__c, Type__c,
+                                           Log__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                                           Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c
+                                      from BatchIF_Log__c
+                                     where id = :rowDataId];
+        if (row.size() > 0) execute(row[0], null);
+    }
+
+    public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {
+        //gaozw
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        SBG001 sBG001 = (SBG001) JSON.deserialize(rowDataStr, SBG001.class);
+
+        String logstr = sBG001.SSBDCustomerContacts.Monitoring.MessageGroupNumber + ' start\n';
+        Boolean needUpdateIflog = false;
+        if  (iflog == null) {
+            needUpdateIflog = true;
+            iflog = new BatchIF_Log__c();
+            iflog.Type__c = 'SBG001';
+            iflog.MessageGroupNumber__c = sBG001.SSBDCustomerContacts.Monitoring.MessageGroupNumber;
+            iflog.Log__c = logstr;
+            iflog.ErrorLog__c = '';
+            // insert iflog;
+            // iflog = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog.Id];
+        } else {
+            logstr = iflog.Log__c;
+        }
+        try{
+            
+            status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.SBG001_ENDPOINT); 
+            system.debug('status--->'+status);
+            if (status == 'OK') {
+                logstr += '\nstatus='+status;
+                rowData.retry_cnt__c = 0;
+            } else {
+                if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+                if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                    rowData.retry_cnt__c++;
+                    LogAutoSendSchedule.assignOneMinute();
+                }
+                if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                    rowData.ErrorLog__c = 'status:' + status +
+                                          '\n閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+                }
+            }
+            logstr += '\nend';
+            // rowData.retry_cnt__c=0;
+        }catch(Exception ex) {
+            // TODO IOException
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG001_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG001_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+
+            //---xiongyl---add
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+            }
+        }
+        iflog.Log__c = logstr;
+        system.debug('iflog---->'+iflog);
+        if (rowData != null) {
+            upsert rowData;
+            upsert iflog;
+        }
+
+        // if (needUpdateIflog) {
+        //     upsert iflog;
+        //     update rowData;
+        // }
+    }
+    //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-End-20200525)
+    /*
+    public static String mappingUse(String recordTypeDeveloperName, String use, String subUse) {
+        if (recordTypeDeveloperName == 'Customer_BS') {
+            String rtn = String.isBlank(use) ? '' : use;
+            if (rtn == 'Cell Biology - Cancer Research') {
+                return 'BS11';
+            } 
+            else if (rtn == 'Cell Biology - Others') {
+                return 'BS12';
+            }
+            else if (rtn == 'Stem Cell Research') {
+                return 'BS13';
+            }
+            else if (rtn == 'Neuroscience') {
+                return 'BS14';
+            }
+            else if (rtn == '(LS Research) Other') {
+                return 'BS15';
+            }
+            else if (rtn == '(LS Research) Unknown') {
+                return 'BS16';
+            }
+            else if (rtn == 'Cell Culturing') {
+                return 'BS21';
+            }
+            else if (rtn == '(Wet Lab) Other') {
+                return 'BS22';
+            }
+            else if (rtn == 'Pathology/Cytology/Hematology') {
+                return 'BS31';
+            }
+            else if (rtn == 'IVF') {
+                return 'BS32';
+            }
+            else if (rtn == '(Clinical) Other') {
+                return 'BS33';
+            }
+            else if (rtn == '(Clinical) Unknown') {
+                return 'BS34';
+            }
+            else if (rtn == '(Education)Education') {
+                return 'BS41';
+            }
+            else if (rtn == '(Other) Other') {
+                return 'BS51';
+            }
+            else {
+                return rtn;
+            }
+        }
+        else if (recordTypeDeveloperName == 'Customer_RVI') {
+            String rtn = String.isBlank(subUse) ? '' : subUse;
+            if (rtn == 'Automotive') {
+                return 'R004';
+            }
+            else if (rtn == 'Civil Aviation') {
+                return 'R002';
+            }
+            else if (rtn == 'Security/Defense') {
+                return 'R006';
+            }
+            else if (rtn == 'Oil,Gas&Chemical') {
+                return 'R005';
+            }
+            else if (rtn == 'Power') {
+                return 'R001';
+            }
+            else if (rtn == 'General Manufacturing') {
+                return 'R003';
+            }
+            else if (rtn == 'Inspection/Service/Rental') {
+                return 'R007';
+            }
+            else if (rtn == 'Others') {
+                return 'R008';
+            }
+            else if (rtn == 'Thermal Power') {
+                return 'R009';
+            }
+            else if (rtn == 'Nuclear Power') {
+                return 'R010';
+            }
+            else if (rtn == 'Wind Power') {
+                return 'R011';
+            }
+            else if (rtn == 'Power(other)') {
+                return 'R001';
+            }
+            else {
+                return rtn;
+            }
+        }
+        //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-Start-20200525)
+        //else if (recordTypeDeveloperName == 'Customer_IE') {
+        //    String rtn = String.isBlank(subUse) ? '' : subUse;
+        //    if (rtn == 'LED') {
+        //        return 'I033';
+        //    }
+        //    else if (rtn == 'FPD') {
+        //        return 'I034';
+        //    }
+        //    else if (rtn == '鍗婂浣�') {
+        //        return 'I035';
+        //    }
+        //    else if (rtn == '鐢靛瓙閮ㄥ搧') {
+        //        return 'I036';
+        //    }
+        //    else if (rtn == '澶槼鑳�') {
+        //        return 'I037';
+        //    }
+        //    else if (rtn == '鐢靛瓙绫籣鍏朵粬') {
+        //        return 'I038';
+        //    }
+        //    else if (rtn == '閲戝睘') {
+        //        return 'I039';
+        //    }
+        //    else if (rtn == '姹借溅') {
+        //        return 'I040';
+        //    }
+        //    else if (rtn == '鐭虫补鍦拌川') {
+        //        return 'I041';
+        //    }
+        //    else if (rtn == '浜旈噾妯″叿') {
+        //        return 'I042';
+        //    }
+        //    else if (rtn == '閲嶅伐璁惧') {
+        //        return 'I043';
+        //    }
+        //    else if (rtn == '鏉愭枡绫籣鍏朵粬') {
+        //        return 'I044';
+        //    }
+        //    else {
+        //        return rtn;
+        //    }
+        //}
+        //  JZHU-BPQBVK-IE鏈�缁堢敤鎴锋帴鍙d紶杈撻�昏緫鍙樻洿(update-End-20200525)
+        else if (recordTypeDeveloperName == 'Customer_NDT') {
+            String rtn = String.isBlank(subUse) ? '' : subUse;
+            if (rtn == 'Power(other)') {
+                return 'R001';
+            }
+            else if (rtn == 'Civil Aviation') {
+                return 'R002';
+            }
+            else if (rtn == 'General Manufacturing') {
+                return 'R003';
+            }
+            else if (rtn == 'Automotive') {
+                return 'R004';
+            }
+            else if (rtn == 'Oil,Gas&Chemical') {
+                return 'R005';
+            }
+            else if (rtn == 'Security/Defense') {
+                return 'R006';
+            }
+            else if (rtn == 'Inspection/Service/Rental') {
+                return 'R007';
+            }
+            else if (rtn == 'Others') {
+                return 'R008';
+            }
+            else if (rtn == 'Thermal Power') {
+                return 'R009';
+            }
+            else if (rtn == 'Nuclear Power') {
+                return 'R010';
+            }
+            else if (rtn == 'Wind Power') {
+                return 'R011';
+            }
+            else {
+                return rtn;
+            }
+        }
+        else if (recordTypeDeveloperName == 'Customer_ANI') {
+            String rtn = String.isBlank(subUse) ? '' : subUse;
+            if (rtn == '搴熸棫閲戝睘') {
+                return 'A001';
+            }
+            else if (rtn == '鐐奸挗鍘�') {
+                return 'A002';
+            }
+            else if (rtn == 'PMI-鐭冲寲琛屼笟') {
+                return 'A003';
+            }
+            else if (rtn == 'PMI-绠¢亾鍒堕��') {
+                return 'A004';
+            }
+            else if (rtn == 'PMI-閲戝睘鍒堕��') {
+                return 'A005';
+            }
+            else if (rtn == 'PMI-鐢靛姏') {
+                return 'A006';
+            }
+            else if (rtn == 'RoHS') {
+                return 'A007';
+            }
+            else if (rtn == 'ELV') {
+                return 'A008';
+            }
+            else if (rtn == '鐜╁叿&鐨潻') {
+                return 'A009';
+            }
+            else if (rtn == '璐甸噾灞�-鍒堕��') {
+                return 'A010';
+            }
+            else if (rtn == '璐甸噾灞�-鍥炴敹') {
+                return 'A011';
+            }
+            else if (rtn == '鍕樻帰-鏀垮簻') {
+                return 'A012';
+            }
+            else if (rtn == '鍕樻帰-鐭夸笟鍏徃') {
+                return 'A013';
+            }
+            else if (rtn == 'Mining-鍐剁偧') {
+                return 'A014';
+            }
+            else if (rtn == 'Mining-寮�閲�') {
+                return 'A015';
+            }
+            else if (rtn == 'EPA') {
+                return 'A016';
+            }
+            else if (rtn == '鍦熷¥淇') {
+                return 'A017';
+            }
+            else if (rtn == '鍦熷¥鐮旂┒') {
+                return 'A018';
+            }
+            else if (rtn == '鑰冨彜&鏂囩墿') {
+                return 'A019';
+            }
+            else if (rtn == '褰曚簳') {
+                return 'A020';
+            }
+            else if (rtn == '涓夊厓鍌寲鍓�') {
+                return 'A021';
+            }
+            else if (rtn == '鍒惰嵂') {
+                return 'A022';
+            }
+            else if (rtn == 'Others') {
+                return 'R008';
+            }
+            else if (rtn == 'Thermal Power') {
+                return 'R009';
+            }
+            else if (rtn == 'Nuclear Power') {
+                return 'R010';
+            }
+            else if (rtn == 'Wind Power') {
+                return 'R011';
+            }
+            else if (rtn == 'Power(other)') {
+                return 'R001';
+            }
+            else {
+                return rtn;
+            }
+        }
+        else {
+            return '';
+        }
+    }
+     */
+    
+}
\ No newline at end of file
diff --git a/scr/classes/SBG001TriggerHandler.cls-meta.xml b/scr/classes/SBG001TriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..8b061c8
--- /dev/null
+++ b/scr/classes/SBG001TriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG001TriggerHandlerTest.cls b/scr/classes/SBG001TriggerHandlerTest.cls
new file mode 100644
index 0000000..fe5afbc
--- /dev/null
+++ b/scr/classes/SBG001TriggerHandlerTest.cls
@@ -0,0 +1,181 @@
+@isTest
+private class SBG001TriggerHandlerTest {
+    static testMethod void myUnitTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account acc = new Account();
+        acc.Name = 'test001';
+        acc.RecordTypeId = '01228000000TdF1';
+        acc.ProductSegment__c = 'BS';
+        acc.ManagementCode_Ext__c = '1234567';
+        acc.AccountStatus__c = 'Active';
+        acc.DepartmentName__c = 'DepartmentNametest';
+        acc.DivisionName__c = 'DivisionNametest';
+        acc.City__c = '鍖椾含';
+        acc.Phone = '18711111111';
+        acc.MobilePhoneNumber__c ='18711111112';
+        acc.Fax = '18711111113';
+        acc.PostCode__c = '100111';
+        acc.Address1__c = 'Address1';
+        acc.Sub_Use__c = 'LED';
+        acc.stautesD__c = 'Pass';
+        acc.UserType__c = '鐮旂┒鎵�';
+        insert acc;
+
+        //System.assertEquals('SBG001_callout_insert_test001', SBG001TriggerHandler.debug_msg);
+        SBG001TriggerHandler.debug_msg = '';
+        SBG001TriggerHandler.SBG001_Ids = new Set<Id>();
+
+        Test.startTest();
+
+
+        // acc.Name = 'test002';
+        //SBG001TriggerHandler.SBG001_Ids.contains(acc.Id) == false;
+        // update acc;
+        //System.assertEquals('SBG001_callout_update_test002', SBG001TriggerHandler.debug_msg);
+
+        // acc.isBatch__c = true;
+
+        // update acc;
+
+        Test.stopTest();
+    }
+
+    static testMethod void getUserTypeTest() {
+        List<BatchIF_Transfer__c> transfers = new List<BatchIF_Transfer__c>();
+        BatchIF_Transfer__c transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'UserType__c';
+        transfer.External_Value__c = '鐮旂┒鎵�';
+        transfer.Internal_Value__c = 'I053';
+        transfers.add(transfer);
+
+        insert transfers;
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account acc = new Account();
+        acc.Name = 'test001';
+        acc.RecordTypeId = '01228000000TdF1';
+        acc.ProductSegment__c = 'IE';
+        acc.ManagementCode_Ext__c = '123456701';
+        acc.AccountStatus__c = 'Active';
+        acc.DepartmentName__c = 'DepartmentNametest';
+        acc.DivisionName__c = 'DivisionNametest';
+        acc.City__c = '鍖椾含';
+        acc.Phone = '18711111111';
+        acc.MobilePhoneNumber__c ='18711111112';
+        acc.Fax = '18711111113';
+        acc.PostCode__c = '100111';
+        acc.Address1__c = 'Address1';
+        acc.Sub_Use__c = 'LED';
+        acc.stautesD__c = 'Pass';
+        acc.UserType__c = '鐮旂┒鎵�';
+        acc.RecordTypeId = rectIE[0].Id;
+        insert acc;
+
+        //System.assertEquals('SBG001_callout_insert_test001', SBG001TriggerHandler.debug_msg);
+        SBG001TriggerHandler.debug_msg = '';
+        SBG001TriggerHandler.SBG001_Ids = new Set<Id>();
+
+        Test.startTest();
+
+
+        // acc.Name = 'test002';
+        //SBG001TriggerHandler.SBG001_Ids.contains(acc.Id) == false;
+        // update acc;
+        //System.assertEquals('SBG001_callout_update_test002', SBG001TriggerHandler.debug_msg);
+
+        // acc.isBatch__c = true;
+
+        // update acc;
+
+        Test.stopTest();
+    }
+
+    static testMethod void contactinsTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+
+        Account acc = new Account();
+        acc.Name = 'test001';
+        acc.RecordTypeId = '01228000000TdF1';
+        acc.ProductSegment__c = 'BS';
+        acc.ManagementCode_Ext__c = '1234567';
+        acc.AccountStatus__c = 'Active';
+        acc.DepartmentName__c = 'DepartmentNametest';
+        acc.DivisionName__c = 'DivisionNametest';
+        acc.City__c = '鍖椾含';
+        acc.Phone = '18711111111';
+        acc.MobilePhoneNumber__c ='18711111112';
+        acc.Fax = '18711111113';
+        acc.PostCode__c = '100111';
+        acc.Address1__c = 'Address1';
+        acc.Sub_Use__c = 'LED';
+        insert acc;
+
+        SBG001TriggerHandler.debug_msg = '';
+        SBG001TriggerHandler.SBG001_Ids = new Set<Id>();
+
+        Contact con = new Contact();
+        con.StatusD__c = 'Pass';
+        con.FirstName = 'con';
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.ManagementCode_Ext__c = '1234568';
+        con.ContactStatus__c = 'Active';
+        con.Phone = '01012345678';
+        con.MobilePhone = '01012345679';
+        acc.Fax = '18711111113';
+        con.Email = 'EmailD__c@test.com';
+        con.Postcode__c = '100111';
+        con.Address1__c = 'Address1D';
+        con.Department = 'Department';
+        insert con;
+
+        //System.assertEquals('SBG001_callout_insert_contest', SBG001TriggerHandler.debug_msg);
+
+        SBG001TriggerHandler.debug_msg = '';
+        SBG001TriggerHandler.SBG001_Ids = new Set<Id>();
+
+        Test.startTest();
+        // con.FirstName = 'con_';
+        //con.Phone = '02012345678';
+        // update con;
+        //System.assertEquals('SBG001_callout_update_con_test', SBG001TriggerHandler.debug_msg);
+        
+        // con.isBatch__c = true;
+
+        update con;
+
+        Test.stopTest();
+
+    }
+
+    /*static testMethod void testMethod2() {
+        BatchIF_Log__c rowData = new BatchIF_Log__c();
+        BatchIF_Log__c iflog = null;
+        SBG001TriggerHandler.execute(rowData,iflog);
+    }*/
+
+    static testMethod void testMethod3(){
+        
+        String type = '';
+        String str = '';
+
+        type = 'Customer_RVI';
+        Map<String, String> transferMap = new Map<String, String>();
+        str = SBG001TriggerHandler.mappingUse(type,'','',transferMap);
+
+        type = 'Customer_IE';
+        str = SBG001TriggerHandler.mappingUse(type, '', '',transferMap);
+
+        type = 'Customer_NDT';
+        str = SBG001TriggerHandler.mappingUse(type, '', '',transferMap);
+
+        type = 'Customer_ANI';
+        str = SBG001TriggerHandler.mappingUse(type, '', '',transferMap);
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG001TriggerHandlerTest.cls-meta.xml b/scr/classes/SBG001TriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..b12420e
--- /dev/null
+++ b/scr/classes/SBG001TriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>31.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG004Rest.cls b/scr/classes/SBG004Rest.cls
new file mode 100644
index 0000000..6925646
--- /dev/null
+++ b/scr/classes/SBG004Rest.cls
@@ -0,0 +1,336 @@
+@RestResource(urlMapping='/SBG004/*')
+global with sharing class SBG004Rest  {
+	public class SBG004ResrException extends Exception {}
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public SBG004Rest.GeData[] GeData;
+    }
+    global class GeData {
+        public String  ProductCode;
+        public String  Currency_x;
+        public String  ProductSegment;
+        public String  TradeType;
+        public String  MachineParts;
+        public String  SalesChannel;
+        public Decimal CostPrice;
+        public String  EffectiveDateFrom;
+        public String  EffectiveDateTo;
+        public String  PurposeOfAdvice;
+        public String  Other1;
+        public String  Other2;
+        public String  Other3;
+    }
+
+    @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG004', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        //BatchIF_Log__c rowData = scope[0];
+        //String logstr = rowData.MessageGroupNumber__c + ' ' + startIndex + '/' + dataLength + ' start\n';
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+       
+        String logstr = '';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG004';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        //iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> purchasePriceList2 = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (purchasePriceList2 == null || purchasePriceList2.size() == 0) {
+            return;
+        }
+        List<String> productCodeList = new List<String>();
+        List<String> prekeys = new List<String>();
+        for (Integer i = 0; i <purchasePriceList2.size(); i++) 
+        {    GeData data = purchasePriceList2[i];
+            if (data.SalesChannel == '99') {
+                prekeys.add(data.ProductSegment + '_' + data.TradeType + '_dealer_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x);
+                prekeys.add(data.ProductSegment + '_' + data.TradeType + '_direct_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x);
+            } else {
+                String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+                prekeys.add(data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x);
+            }
+            productCodeList.add(purchasePriceList2.get(i).ProductCode);
+        }
+
+        Map <String,PricebookEntry > premap = new Map<String,PricebookEntry >();
+        for(PricebookEntry pre : [Select Id,Name,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,UnitPrice,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry where KEY__c in:prekeys])
+        {
+            premap.put(pre.KEY__c,pre);
+        }
+
+        Map <String,Pricebook2 > prebookmap = new Map<String,Pricebook2 >();
+        for(Pricebook2 pre : [Select Id,Name,MachineParts__c,ProductSegment__c,SalesChannel__c,TradeType__c,isActive
+                                 from Pricebook2 where IsStandard = false])
+        {
+            prebookmap.put(pre.ProductSegment__c + '_' + pre.TradeType__c + '_' + pre.SalesChannel__c + '_' + pre.MachineParts__c,pre);
+        }
+        System.debug('prebookis' + prebookmap);
+
+
+        Map<String, Product2> prdsMap = new Map<String, Product2>();
+        for (Product2 prd : [select Id, ProductCode, Product_ECCode__c,
+                                         EffectiveDateTo__c,
+                                         ProductModels__c,
+                                         ProductStatus__c
+                                    from Product2
+                                   where ProductModels__c = false and ProductCode in :productCodeList]
+        ) {
+            prdsMap.put(prd.ProductCode, prd);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            List<PricebookEntry> pres = new List<PricebookEntry>();
+            Set<String> updPresSet = new Set<String>();
+            Boolean retrycntFlag = false;
+            for (Integer i = 0; i < purchasePriceList2.size(); i++) {
+                //purchasePriceList.add(purchasePriceList2.get(i));
+                GeData data = purchasePriceList2.get(i);
+                if (data.PurposeOfAdvice == '1') {
+                        data.EffectiveDateTo = NFMUtil.formatDate2Str(Date.today().addDays(-1));
+                }
+                if (String.isBlank(purchasePriceList2.get(i).ProductCode) == false) {
+                    if (data.ProductCode == null || data.ProductCode == '') {
+                        iflog.ErrorLog__c += 'ProductCode is required\n';
+                        continue;
+                    }
+                    if (data.ProductSegment == null || data.ProductSegment == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']PriceType is required\n';
+                        continue;
+                    }
+                    if (data.Currency_x == null || data.Currency_x == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']Currency is required\n';
+                        continue;
+                    }
+                    if (data.EffectiveDateFrom == null || data.EffectiveDateFrom == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateFrom is required\n';
+                        continue;
+                    }
+                    if (data.EffectiveDateTo == null || data.EffectiveDateTo == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateTo is required\n';
+                        continue;
+                    }
+                    if(prdsMap.get(data.ProductCode) == null)
+                    {
+                        iflog.ErrorLog__c += 'Product[' + data.ProductCode + ']NotExist\n';
+                        retrycntFlag = true;
+                        continue;
+                    }
+
+                    if(data.SalesChannel == '99')
+                    {
+                        String pdedikey = data.ProductSegment + '_' + data.TradeType + '_' + 'direct' + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                        String pbedekey = data.ProductSegment + '_' + data.TradeType + '_' + 'dealer' + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                        String pddikey = data.ProductSegment + '_' + data.TradeType + '_' + 'direct' + '_' + data.MachineParts;
+                        String pddekey = data.ProductSegment + '_' + data.TradeType + '_' + 'dealer' + '_' + data.MachineParts;
+                        PricebookEntry pre1 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pddikey),pdedikey,updPresSet);
+                        PricebookEntry pre2 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pddekey),pbedekey,updPresSet);
+
+                        pres.add(pre1);
+                        pres.add(pre2);
+
+                    }
+                    else {
+                        String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+                        String pbekey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                        String pbkey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts;
+                        System.debug(prdsMap.get(data.ProductCode));
+                        System.debug(pbekey);
+                        System.debug(prebookmap);
+
+                        PricebookEntry pre1 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pbkey),pbekey,updPresSet);
+                        pres.add(pre1);
+                    }
+
+                }
+            }
+      
+            System.debug(logstr);
+            logstr += 'Execute Record:' + pres.size() + '\n';
+            if(pres.size()>0) {
+                upsert(pres);
+            }
+            logstr += '\nend';
+            
+            if (retrycntFlag) {
+                LogAutoSend(rowData,batch_retry_max_cnt,iflog);
+            } else {
+               rowData.retry_cnt__c = 0; 
+            }
+
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(ex);
+            System.debug(Logginglevel.ERROR, 'SBG004_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG004_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                LogAutoSendScheduleProduct.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+    global static void LogAutoSend (BatchIF_Log__c rowData,Integer batch_retry_max_cnt,BatchIF_Log__c iflog) {
+        system.debug('LogAutoSend---Start');
+        if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+        
+        if (rowData.retry_cnt__c < batch_retry_max_cnt){
+            rowData.retry_cnt__c++;
+            LogAutoSendScheduleProduct.assignOneMinute();
+        }
+        if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+            rowData.ErrorLog__c = iflog.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+        }
+
+        update rowData;
+
+    }
+    global static PricebookEntry setpricebookec(GeData data,Map<String,PricebookEntry> premap,String productid,Pricebook2 pricebook2,String pbekey, Set<String> updPresSet) {
+        System.debug('setpricebookec start productid=' + productid);
+        System.debug('setpricebookec start Pricebook2id=' + pricebook2.Id);
+        Date dateFrom = NFMUtil.parseStr2Date(data.EffectiveDateFrom, false);
+        Date dateTo = NFMUtil.parseStr2Date(data.EffectiveDateTo, true);
+        System.debug('fram' + dateFrom);
+        System.debug('to' + dateTo);
+        String curr = data.Currency_x == 'RMB' ? 'CNY' : data.Currency_x;
+        System.debug('Currency_x is ' + curr);
+        if (updPresSet.contains(pbekey))
+        {
+             throw new SBG004ResrException(pbekey + ' is doubled in message file.');
+        }
+
+        PricebookEntry pre = premap.get(pbekey);
+        if(pre != null){
+            System.debug('fram111' + pre.EffectiveDateFrom1__c);
+            System.debug('to111' + pre.EffectiveDateTo1__c);
+        }
+
+        // TODO CurrencyIsoCode 绛�
+        // UnitPrice = 0
+        if (pre == null) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     CostPrice1__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom1__c = dateFrom,
+                                     EffectiveDateTo1__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else if (pre.EffectiveDateFrom1__c == null || pre.EffectiveDateTo1__c < Date.today() || pre.EffectiveDateFrom1__c == dateFrom) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice1__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom1__c = dateFrom,
+                                     EffectiveDateTo1__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else if(pre.EffectiveDateFrom2__c == null || pre.EffectiveDateTo2__c < Date.today() || pre.EffectiveDateFrom2__c == dateFrom) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice2__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom2__c = dateFrom,
+                                     EffectiveDateTo2__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else if(pre.EffectiveDateFrom1__c < pre.EffectiveDateFrom2__c) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice1__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom1__c = dateFrom,
+                                     EffectiveDateTo1__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice2__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom2__c = dateFrom,
+                                     EffectiveDateTo2__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        updPresSet.add(pbekey);
+        return pre;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG004Rest.cls-meta.xml b/scr/classes/SBG004Rest.cls-meta.xml
new file mode 100644
index 0000000..e3d1b51
--- /dev/null
+++ b/scr/classes/SBG004Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG004RestTest.cls b/scr/classes/SBG004RestTest.cls
new file mode 100644
index 0000000..12a1109
--- /dev/null
+++ b/scr/classes/SBG004RestTest.cls
@@ -0,0 +1,645 @@
+@isTest
+private class SBG004RestTest {
+    static Product2 testSBG004Init() {
+        // 銉嗐偣銉堛儑銉笺偪
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        insert prd;
+        //Pricebook2 prdbook     = new Pricebook2();
+
+        Pricebook2 prdbook1 = new Pricebook2(
+            Name = 'testSBG004',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2(
+            Name = 'testSBG004',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+        return prd;
+    }
+
+
+    @isTest
+    static void testSBG004_void() {
+        testSBG004Init();
+        // null
+        // SBG004Rest.SBG004(null);
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        // Monitoring銈掋偦銉冦儓銇椼仾銇�
+        // SBG004Rest.SBG004(GeDatas);
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        // 蹇呴爤闋呯洰銈掋偦銉冦儓銇椼仾銇�
+        // SBG004Rest.SBG004(GeDatas);
+
+        // 鍟嗗搧銈炽兗銉夈亴瀛樺湪銇椼仾銇�
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.ProductCode  = 'testSBG004X';
+
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+
+        System.Test.stopTest();
+
+        Product2[] rslts = [select Id from Product2 where Product_ECCode__c = :GeData.ProductCode];
+        System.assertEquals(0, rslts.size());
+    }
+
+    @isTest
+    static void testSBG004_update() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+         GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = '99';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+
+        List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<PricebookEntry>  pres = [Select Id,Name,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD' OR KEY__c = 'BS_Taxation_dealer_Machine_testSBG004_USD'];
+        System.debug(pres.size());
+        System.assertEquals(2, pres.size());
+    }
+
+    @isTest
+    static void testSBG004_delete() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+        GeData.Currency_x         = 'RMB';
+
+
+
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+                List<PricebookEntry>  pres1 = [Select Id,Name,KEY__c from PricebookEntry ];
+                System.debug(pres1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_RMB'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_RMB');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+
+
+    @isTest
+    static void testSBG004_delete0() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20131203';
+        GeData.EffectiveDateTo    = '20191204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD';
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        //GeData.Currency_x         = 'RMB';
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+        //SBG004Rest.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20131202';
+        //GeData.EffectiveDateTo    = '20131202';
+        //SBG004Rest.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20141203';
+        //GeData.EffectiveDateTo    = '29121204';
+        //SBG004Rest.SBG004(GeDatas);
+
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+        System.debug(key1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_USD');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+   
+    @isTest
+    static void testSBG004_delete1() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20131203';
+        GeData.EffectiveDateTo    = '20191204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom2 = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo2 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.EffectiveDateFrom2__c = dateFrom2;
+        pbe.EffectiveDateTo2__c = dateTo2;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+        //GeData.Currency_x         = 'RMB';
+        //SBG004Rest.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20131202';
+        //GeData.EffectiveDateTo    = '20131202';
+        //SBG004Rest.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20141203';
+        //GeData.EffectiveDateTo    = '29121204';
+        //SBG004Rest.SBG004(GeDatas);
+
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+        System.debug(key1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_USD');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+
+    @isTest
+    static void testSBG004_delete2() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20131202';
+        GeData.EffectiveDateTo    = '20191204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+        //GeData.Currency_x         = 'RMB';
+        //SBG004Rest.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20131202';
+        //GeData.EffectiveDateTo    = '20131202';
+        //SBG004Rest.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20141203';
+        //GeData.EffectiveDateTo    = '29121204';
+        //SBG004Rest.SBG004(GeDatas);
+
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+        System.debug(key1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_USD');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+    @isTest
+    static void testSBG004_resend() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004Rest.GeData GeData = new SBG004Rest.GeData();
+        SBG004Rest.GeDatas GeDatas = new SBG004Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = '99';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+        System.Test.startTest();
+        // SBG004Rest.SBG004(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+        SBG004Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                            ErrorLog__c
+                                        from BatchIF_Log__c
+                                        where RowDataFlg__c = true
+                                        and Type__c = 'SBG004'
+                                        order by CreatedDate desc];
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        SBGITMRest.executefuture(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                Type__c, Log__c, ErrorLog__c,retry_cnt__c
+                from BatchIF_Log__c
+                where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        // System.assertEquals(0, bl[0].retry_cnt__c);
+    }
+
+    @isTest static void test_method_Send() {
+
+    Test.startTest();
+
+    RestRequest req = new RestRequest();
+    RestResponse res = new RestResponse();
+
+    // String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG004","MessageGroupNumber": 331591,"NumberOfRecord": 1,"TransmissionDateTime": 201908081115},"GeData": [{"TradeType": "Taxation","SalesChannel": "99","PurposeOfAdvice": "3","ProductSegment": "IE","ProductCode": "N5702700","Other3": "","Other2": "","Other1": "","MachineParts": "Machine","EffectiveDateTo": "99991231","EffectiveDateFrom": "20190801","Currency_x": "RMB","CostPrice": 12241.00}]}}';
+    String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH"},"GeData": [{"TradeType": "Taxation"}]}}';
+    req.requestURI = 'services/apexrest/SBG004/execute';
+    req.httpMethod = 'POST';
+    req.requestBody = Blob.valueof(JsonMsg);
+    RestContext.request = req;
+    RestContext.response= res;
+
+    SBG004Rest.execute();
+
+    Test.stopTest();
+
+   // { "GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG017", "MessageGroupNumber": 331591, "NumberOfRecord": 1, "TransmissionDateTime": 201903251115 },"GeData": [{ "StockAnswer": "OK111","SAPQuotationCode": "20022780  ", "Other3": "", "Other2": "", "Other1": "",  "OpportunityCode": "O-2018-067607"}]}}
+
+    //Test.setMock(HttpCalloutMock.class, new NFM205RestCalloutMock());
+    //NFM205Rest.execute1('{"Monitoring":{"TransmissionDateTime":"201812201320","Text":"","Tag":"MSGH","Sender":"SFDC","Receiver":"SPO","NumberOfRecord":"1","MessageType":"NFM205","MessageGroupNumber":"20180001722190"},"GeData":[{"Opportunity_Code":"HKBJ-GI-BJ0588881","Bidding_No":"as123121","Bidding_Content":"鎷涙爣鍐呭","Bid_Project_Name":"鎷涙爣椤圭洰鍚�","Bid_Date":"20181203","Authorized_Status":"1","Authorized_Finish_Sales":"30033","Authorized_DB_No":"MGZWESQHN201812001","Authorized_Date":"20190316","Autholization_Activated_Date":"20190415"}]}');
+}
+}
\ No newline at end of file
diff --git a/scr/classes/SBG004RestTest.cls-meta.xml b/scr/classes/SBG004RestTest.cls-meta.xml
new file mode 100644
index 0000000..e3d1b51
--- /dev/null
+++ b/scr/classes/SBG004RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG004WebService.cls b/scr/classes/SBG004WebService.cls
new file mode 100644
index 0000000..a7f49f7
--- /dev/null
+++ b/scr/classes/SBG004WebService.cls
@@ -0,0 +1,296 @@
+global class SBG004WebService {
+    public class SBG004WebServiceException extends Exception {}
+    private final Id rowData_Id;
+
+    global class GeDatas {
+        webservice NFMUtil.Monitoring Monitoring;
+        webservice SBG004WebService.GeData[] GeData;
+    }
+    global class GeData {
+        webservice String  ProductCode;
+        webservice String  Currency_x;
+        webservice String  ProductSegment;
+        webservice String  TradeType;
+        webservice String  MachineParts;
+        webservice String  SalesChannel;
+        webservice Decimal CostPrice;
+        webservice String  EffectiveDateFrom;
+        webservice String  EffectiveDateTo;
+        webservice String  PurposeOfAdvice;
+        webservice String  Other1;
+        webservice String  Other2;
+        webservice String  Other3;
+    }
+    webservice static void SBG004(GeDatas geDatas) {
+        if (geDatas == null) {
+            return;
+        }
+        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG004', GeDatas.GeData);
+        if (GeDatas.GeData == null || GeDatas.GeData.size() == 0) {
+            return;
+        }
+        rowData.retry_cnt__c = 1;
+        update rowData;
+        //SBG004WebService u = new SBG004WebService(rowData.Id, 0, GeDatas.GeData.size());
+        //Database.executeBatch(u, 1);
+        if (Test.isRunningTest()) {
+            Id execBTId = Database.executeBatch(new LogAutoSendBatchProduct(), 4);
+        }else{
+            LogAutoSendScheduleProduct.assignOneMinute();
+        }
+        
+    }
+
+    global static void execute(Database.BatchableContext BC, List<BatchIF_Log__c> scope) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = scope[0];
+        //String logstr = rowData.MessageGroupNumber__c + ' ' + startIndex + '/' + dataLength + ' start\n';
+        String logstr = '';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG004';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        //iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> purchasePriceList2 = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (purchasePriceList2 == null || purchasePriceList2.size() == 0) {
+            return;
+        }
+        List<String> productCodeList = new List<String>();
+        List<String> prekeys = new List<String>();
+        for (Integer i = 0; i <purchasePriceList2.size(); i++) 
+        {    GeData data = purchasePriceList2[i];
+            if (data.SalesChannel == '99') {
+                prekeys.add(data.ProductSegment + '_' + data.TradeType + '_dealer_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x);
+                prekeys.add(data.ProductSegment + '_' + data.TradeType + '_direct_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x);
+            } else {
+                String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+                prekeys.add(data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x);
+            }
+            productCodeList.add(purchasePriceList2.get(i).ProductCode);
+        }
+
+        Map <String,PricebookEntry > premap = new Map<String,PricebookEntry >();
+        for(PricebookEntry pre : [Select Id,Name,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,UnitPrice,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry where KEY__c in:prekeys])
+        {
+            premap.put(pre.KEY__c,pre);
+        }
+
+        Map <String,Pricebook2 > prebookmap = new Map<String,Pricebook2 >();
+        for(Pricebook2 pre : [Select Id,Name,MachineParts__c,ProductSegment__c,SalesChannel__c,TradeType__c,isActive
+                                 from Pricebook2 where IsStandard = false])
+        {
+            prebookmap.put(pre.ProductSegment__c + '_' + pre.TradeType__c + '_' + pre.SalesChannel__c + '_' + pre.MachineParts__c,pre);
+        }
+        System.debug('prebookis' + prebookmap);
+
+
+        Map<String, Product2> prdsMap = new Map<String, Product2>();
+        for (Product2 prd : [select Id, ProductCode, Product_ECCode__c,
+                                         EffectiveDateTo__c,
+                                         ProductModels__c,
+                                         ProductStatus__c
+                                    from Product2
+                                   where ProductModels__c = false and ProductCode in :productCodeList]
+        ) {
+            prdsMap.put(prd.ProductCode, prd);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            List<PricebookEntry> pres = new List<PricebookEntry>();
+            Set<String> updPresSet = new Set<String>();
+
+            for (Integer i = 0; i < purchasePriceList2.size(); i++) {
+                //purchasePriceList.add(purchasePriceList2.get(i));
+                GeData data = purchasePriceList2.get(i);
+                if (data.PurposeOfAdvice == '1') {
+                        data.EffectiveDateTo = NFMUtil.formatDate2Str(Date.today().addDays(-1));
+                }
+                if (String.isBlank(purchasePriceList2.get(i).ProductCode) == false) {
+                    if (data.ProductCode == null || data.ProductCode == '') {
+                        iflog.ErrorLog__c += 'ProductCode is required\n';
+                        continue;
+                    }
+                    if (data.ProductSegment == null || data.ProductSegment == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']PriceType is required\n';
+                        continue;
+                    }
+                    if (data.Currency_x == null || data.Currency_x == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']Currency is required\n';
+                        continue;
+                    }
+                    if (data.EffectiveDateFrom == null || data.EffectiveDateFrom == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateFrom is required\n';
+                        continue;
+                    }
+                    if (data.EffectiveDateTo == null || data.EffectiveDateTo == '') {
+                        iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateTo is required\n';
+                        continue;
+                    }
+                    if(prdsMap.get(data.ProductCode) == null)
+                    {
+                        iflog.ErrorLog__c += 'Product[' + data.ProductCode + ']NotExist\n';
+                        continue;
+                    }
+
+                    if(data.SalesChannel == '99')
+                    {
+                        String pdedikey = data.ProductSegment + '_' + data.TradeType + '_' + 'direct' + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                        String pbedekey = data.ProductSegment + '_' + data.TradeType + '_' + 'dealer' + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                        String pddikey = data.ProductSegment + '_' + data.TradeType + '_' + 'direct' + '_' + data.MachineParts;
+                        String pddekey = data.ProductSegment + '_' + data.TradeType + '_' + 'dealer' + '_' + data.MachineParts;
+                        PricebookEntry pre1 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pddikey),pdedikey,updPresSet);
+                        PricebookEntry pre2 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pddekey),pbedekey,updPresSet);
+
+                        pres.add(pre1);
+                        pres.add(pre2);
+
+                    }
+                    else {
+                        String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+                        String pbekey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                        String pbkey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts;
+                        System.debug(prdsMap.get(data.ProductCode));
+                        System.debug(pbekey);
+                        System.debug(prebookmap);
+
+                        PricebookEntry pre1 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pbkey),pbekey,updPresSet);
+                        pres.add(pre1);
+                    }
+
+                }
+            }
+      
+            System.debug(logstr);
+            logstr += 'Execute Record:' + pres.size() + '\n';
+            if(pres.size()>0) {
+                upsert(pres);
+            }
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(ex);
+            System.debug(Logginglevel.ERROR, 'SBG004_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG004_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                LogAutoSendScheduleProduct.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+
+    global static PricebookEntry setpricebookec(GeData data,Map<String,PricebookEntry> premap,String productid,Pricebook2 pricebook2,String pbekey, Set<String> updPresSet) {
+        System.debug('setpricebookec start productid=' + productid);
+        System.debug('setpricebookec start Pricebook2id=' + pricebook2.Id);
+        Date dateFrom = NFMUtil.parseStr2Date(data.EffectiveDateFrom, false);
+        Date dateTo = NFMUtil.parseStr2Date(data.EffectiveDateTo, true);
+        System.debug('fram' + dateFrom);
+        System.debug('to' + dateTo);
+        String curr = data.Currency_x == 'RMB' ? 'CNY' : data.Currency_x;
+        System.debug('Currency_x is ' + curr);
+        if (updPresSet.contains(pbekey))
+        {
+            throw new SBG004WebServiceException(pbekey + ' is doubled in message file.');
+        }
+
+        PricebookEntry pre = premap.get(pbekey);
+        if(pre != null){
+            System.debug('fram111' + pre.EffectiveDateFrom1__c);
+            System.debug('to111' + pre.EffectiveDateTo1__c);
+        }
+
+        // TODO CurrencyIsoCode 绛�
+        // UnitPrice = 0
+        if (pre == null) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     CostPrice1__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom1__c = dateFrom,
+                                     EffectiveDateTo1__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else if (pre.EffectiveDateFrom1__c == null || pre.EffectiveDateTo1__c < Date.today() || pre.EffectiveDateFrom1__c == dateFrom) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice1__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom1__c = dateFrom,
+                                     EffectiveDateTo1__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else if(pre.EffectiveDateFrom2__c == null || pre.EffectiveDateTo2__c < Date.today() || pre.EffectiveDateFrom2__c == dateFrom) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice2__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom2__c = dateFrom,
+                                     EffectiveDateTo2__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else if(pre.EffectiveDateFrom1__c < pre.EffectiveDateFrom2__c) {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice1__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom1__c = dateFrom,
+                                     EffectiveDateTo1__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        else {
+            pre = new PricebookEntry(KEY__c =  pbekey,
+                                     Id = pre.Id,
+                                     CostPrice2__c = data.CostPrice,
+                                     CurrencyIsoCode = curr,
+                                     EffectiveDateFrom2__c = dateFrom,
+                                     EffectiveDateTo2__c = dateTo,
+                                     UnitPrice = 0,
+                                     Product2Id = productid,
+                                     Pricebook2id = pricebook2.Id,
+                                     isActive = pricebook2.isActive,
+                                     UseStandardPrice = false);
+        }
+        updPresSet.add(pbekey);
+        return pre;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG004WebService.cls-meta.xml b/scr/classes/SBG004WebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG004WebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG004WebServiceTest.cls b/scr/classes/SBG004WebServiceTest.cls
new file mode 100644
index 0000000..d7ff675
--- /dev/null
+++ b/scr/classes/SBG004WebServiceTest.cls
@@ -0,0 +1,612 @@
+@isTest
+private class SBG004WebServiceTest {
+    static Product2 testSBG004Init() {
+        // 銉嗐偣銉堛儑銉笺偪
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG004';
+        prd.ProductCode            = 'testSBG004';
+        prd.Name                   = 'testSBG004';
+        prd.IsActive               = true;
+        insert prd;  
+        //Pricebook2 prdbook     = new Pricebook2();
+
+        Pricebook2 prdbook1 = new Pricebook2( 
+            Name = 'testSBG004',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2( 
+            Name = 'testSBG004',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+        return prd;
+        
+    }
+
+
+    @isTest
+    static void testSBG004_void() {
+        testSBG004Init();
+        // null
+        SBG004WebService.SBG004(null);
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        // Monitoring銈掋偦銉冦儓銇椼仾銇�
+        SBG004WebService.SBG004(GeDatas);
+        
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        // 蹇呴爤闋呯洰銈掋偦銉冦儓銇椼仾銇�
+        SBG004WebService.SBG004(GeDatas);
+
+        // 鍟嗗搧銈炽兗銉夈亴瀛樺湪銇椼仾銇�
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.ProductCode  = 'testSBG004X';
+
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        System.Test.stopTest();
+        
+        Product2[] rslts = [select Id from Product2 where Product_ECCode__c = :GeData.ProductCode];
+        System.assertEquals(0, rslts.size());
+    }
+
+
+
+
+
+
+
+    @isTest
+    static void testSBG004_update() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+         GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = '99';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+
+        List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+        
+        List<PricebookEntry>  pres = [Select Id,Name,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD' OR KEY__c = 'BS_Taxation_dealer_Machine_testSBG004_USD'];
+        System.debug(pres.size());
+        System.assertEquals(2, pres.size());
+    }
+
+    @isTest
+    static void testSBG004_delete() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+        GeData.Currency_x         = 'RMB';
+
+
+
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+                List<PricebookEntry>  pres1 = [Select Id,Name,KEY__c from PricebookEntry ];
+                System.debug(pres1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_RMB'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_RMB');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+
+
+    @isTest
+    static void testSBG004_delete0() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20131203';
+        GeData.EffectiveDateTo    = '20191204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD';
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        //GeData.Currency_x         = 'RMB';
+        //SBG004WebService.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20131202';
+        //GeData.EffectiveDateTo    = '20131202';
+        //SBG004WebService.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20141203';
+        //GeData.EffectiveDateTo    = '29121204';
+        //SBG004WebService.SBG004(GeDatas);
+
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+        System.debug(key1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_USD');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+   
+    @isTest
+    static void testSBG004_delete1() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20131203';
+        GeData.EffectiveDateTo    = '20191204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom2 = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo2 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.EffectiveDateFrom2__c = dateFrom2;
+        pbe.EffectiveDateTo2__c = dateTo2;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        //GeData.Currency_x         = 'RMB';
+        //SBG004WebService.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20131202';
+        //GeData.EffectiveDateTo    = '20131202';
+        //SBG004WebService.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20141203';
+        //GeData.EffectiveDateTo    = '29121204';
+        //SBG004WebService.SBG004(GeDatas);
+
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+        System.debug(key1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_USD');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+
+    @isTest
+    static void testSBG004_delete2() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20131202';
+        GeData.EffectiveDateTo    = '20191204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        //GeData.Currency_x         = 'RMB';
+        //SBG004WebService.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20131202';
+        //GeData.EffectiveDateTo    = '20131202';
+        //SBG004WebService.SBG004(GeDatas);
+        //GeData.EffectiveDateFrom  = '20141203';
+        //GeData.EffectiveDateTo    = '29121204';
+        //SBG004WebService.SBG004(GeDatas);
+
+        System.Test.stopTest();
+
+
+         List<BatchIF_Log__c> log = [Select ErrorLog__c,Id,Name,MessageGroupNumber__c,Log__c From BatchIF_Log__c];
+        System.debug(log);
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        String key1 = GeData.ProductSegment + '_' + GeData.TradeType + '_' + GeData.SalesChannel + '_' + GeData.MachineParts + '_' + GeData.ProductCode;
+        System.debug(key1);
+
+
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG004_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];                 
+        System.debug(pres.size());
+        System.debug(pr);
+        System.assertEquals(1, pres.size());
+        System.debug(pres[0].KEY__c);
+        System.assertEquals(pres[0].KEY__c,'BS_Taxation_direct_Machine_testSBG004_USD');
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+        
+    
+    }
+
+    @isTest
+    static void testSBG004_resend() {
+        Product2 prd = testSBG004Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG004WebService.GeData GeData = new SBG004WebService.GeData();
+        SBG004WebService.GeDatas GeDatas = new SBG004WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG004WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG004';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = '99';
+        GeData.TradeType          = 'Taxation';
+        GeData.CostPrice          = 100;
+
+        System.Test.startTest();
+        SBG004WebService.SBG004(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                            ErrorLog__c
+                                        from BatchIF_Log__c
+                                        where RowDataFlg__c = true
+                                        and Type__c = 'SBG004'
+                                        order by CreatedDate desc];
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        SBGITMWebService.execute(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                Type__c, Log__c, ErrorLog__c,retry_cnt__c
+                from BatchIF_Log__c
+                where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        System.assertEquals(0, bl[0].retry_cnt__c);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG004WebServiceTest.cls-meta.xml b/scr/classes/SBG004WebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG004WebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG005Rest.cls b/scr/classes/SBG005Rest.cls
new file mode 100644
index 0000000..89cb7ae
--- /dev/null
+++ b/scr/classes/SBG005Rest.cls
@@ -0,0 +1,399 @@
+@RestResource(urlMapping='/SBG005/*')
+global with sharing class SBG005Rest  {
+	public class SBG005ResrException extends Exception {}
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public SBG005Rest.GeData[] GeData;
+    }
+    global class GeData {
+        public String  ProductCode;
+        public String  Currency_x;
+        public String  ProductSegment;
+        public String  TradeType;
+        public String  MachineParts;
+        public String  SalesChannel;
+        public Decimal SalesPrice;
+        public String  DealerDistinguish;
+        public String  EffectiveDateFrom;
+        public String  EffectiveDateTo;
+        public String  PurposeOfAdvice;
+        public String  Other1;
+        public String  Other2;
+        public String  Other3;
+    }
+
+    @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG005', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        // BatchIF_Log__c rowData = scope[0];
+        //String logstr = rowData.MessageGroupNumber__c + ' ' + startIndex + '/' + dataLength + ' start\n';
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = '';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG005';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        //iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> purchasePriceList2 = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (purchasePriceList2 == null || purchasePriceList2.size() == 0) {
+            return;
+        }
+        List<GeData> purchasePriceList = new List<GeData>();
+        List<String> productCodeList = new List<String>();
+        for (Integer i = 0; i < purchasePriceList2.size(); i++) {
+            purchasePriceList.add(purchasePriceList2.get(i));
+            if (String.isBlank(purchasePriceList2.get(i).ProductCode) == false) {
+                productCodeList.add(purchasePriceList2.get(i).ProductCode);
+            }
+        }
+
+        Map<String, Product2> prdsMap = new Map<String, Product2>();
+        for (Product2 prd : [select Id, ProductCode, Product_ECCode__c,
+                                         EffectiveDateTo__c,
+                                         ProductModels__c,
+                                         ProductStatus__c
+                                    from Product2
+                                   where ProductModels__c = false and ProductCode in :productCodeList]
+        ) {
+            prdsMap.put(prd.ProductCode, prd);
+        }
+
+        Map <String,Pricebook2 > prebookmap = new Map<String,Pricebook2 >();
+
+        for(Pricebook2 pre : [Select Id,Name,MachineParts__c,ProductSegment__c,SalesChannel__c,TradeType__c,isActive
+                                 from Pricebook2 where IsStandard = false])
+        {
+            prebookmap.put(pre.ProductSegment__c + '_' + pre.TradeType__c + '_' + pre.SalesChannel__c + '_' + pre.MachineParts__c,pre);
+        }
+
+
+        List<String> prekeys = new List<String>();
+        for(GeData data : purchasePriceList2)
+        {
+            String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+            String key = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+            prekeys.add(key);
+        }
+        system.debug('=====0:' + prekeys);
+        Map <String,PricebookEntry > premap = new Map<String,PricebookEntry >();
+        for(PricebookEntry pre : [Select Id,Name,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,EffectiveDateTo1__c,EffectiveDateTo2__c,
+                                        EffectiveDateFrom1_sales__c,EffectiveDateFrom1_sales_A__c,EffectiveDateFrom1_sales_B__c,EffectiveDateFrom1_sales_C__c,
+                                        EffectiveDateFrom2_sales__c,EffectiveDateFrom2_sales_A__c,EffectiveDateFrom2_sales_B__c,EffectiveDateFrom2_sales_C__c,
+                                        EffectiveDateTo1_sales__c,EffectiveDateTo1_sales_A__c,EffectiveDateTo1_sales_B__c,EffectiveDateTo1_sales_C__c,
+                                        EffectiveDateTo2_sales__c,EffectiveDateTo2_sales_A__c,EffectiveDateTo2_sales_B__c,EffectiveDateTo2_sales_C__c,
+                                        CostPrice1__c,CostPrice2__c,
+                                        SalesPrice1__c,SalesPrice1A__c,SalesPrice1B__c,SalesPrice1C__c,
+                                        SalesPrice2__c,SalesPrice2A__c,SalesPrice2B__c,SalesPrice2C__c
+                                 from PricebookEntry where KEY__c in:prekeys])
+        {
+            premap.put(pre.KEY__c,pre);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+    try {
+        Map<String,PricebookEntry> updPresMap = new Map<String,PricebookEntry>();
+        Boolean retrycntFlag = false;
+        for (Integer i = 0; i < purchasePriceList2.size(); i++) 
+        {
+            //purchasePriceList.add(purchasePriceList2.get(i));
+            GeData data = purchasePriceList2.get(i);
+            if (data.PurposeOfAdvice == '1') {
+                    data.EffectiveDateTo = NFMUtil.formatDate2Str(Date.today().addDays(-1));
+                }
+            if (String.isBlank(purchasePriceList2.get(i).ProductCode) == false) 
+            {
+                //productCodeList.add(purchasePriceList2.get(i).ProductCode);
+                if (data.ProductCode == null || data.ProductCode == '') {
+                    iflog.ErrorLog__c += 'ProductCode is required\n';
+                    continue;
+                }
+                if (data.ProductSegment == null || data.ProductSegment == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']PriceType is required\n';
+                    continue;
+                }
+                if (data.Currency_x == null || data.Currency_x == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']Currency is required\n';
+                    continue;
+                }
+                if (data.EffectiveDateFrom == null || data.EffectiveDateFrom == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateFrom is required\n';
+                    continue;
+                }
+                if (data.EffectiveDateTo == null || data.EffectiveDateTo == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateTo is required\n';
+                    continue;
+                }
+                if(prdsMap.get(data.ProductCode) == null){
+                    iflog.ErrorLog__c += 'Product[' + data.ProductCode + ']NotExist\n';
+                    retrycntFlag = true;
+                    continue;
+                }
+
+                String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+                String pbekey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                String pbkey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts;
+                System.debug(prdsMap.get(data.ProductCode));
+                System.debug(prebookmap);
+                if(!prebookmap.keyset().contains(pbkey)){
+                     iflog.ErrorLog__c += 'Pricebook2[' + pbkey + ']NotExist\n';
+                    continue;
+                }
+                if(String.isBlank(prebookmap.get(pbkey).Id))
+                {
+                    iflog.ErrorLog__c += 'Pricebook2[' + pbkey + ']NotExist\n';
+                    continue;
+                }
+                System.debug('=====1:' + premap);
+                PricebookEntry pre1 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pbkey),pbekey,updPresMap);
+                System.debug('=====2:' + pre1);
+
+
+            }
+        }
+        logstr += 'Execute Record:' + updPresMap.keySet().size() + '\n';
+        upsert(updPresMap.Values());
+
+            logstr += '\nend';
+            if (retrycntFlag) {
+                LogAutoSend(rowData,batch_retry_max_cnt,iflog);
+            } else {
+               rowData.retry_cnt__c = 0; 
+            }
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG005_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG005_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            Database.rollback(sp);
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                LogAutoSendScheduleProduct.assignOneMinute();
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+
+    global static void LogAutoSend (BatchIF_Log__c rowData,Integer batch_retry_max_cnt,BatchIF_Log__c iflog) {
+        system.debug('LogAutoSend---Start');
+        if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+        
+        if (rowData.retry_cnt__c < batch_retry_max_cnt){
+            rowData.retry_cnt__c++;
+            LogAutoSendScheduleProduct.assignOneMinute();
+        }
+        if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+            rowData.ErrorLog__c = iflog.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+        }
+
+        update rowData;
+
+    }
+    
+    global static PricebookEntry setpricebookec(GeData data,Map<String,PricebookEntry> premap,String productid,Pricebook2 pricebook2,String pbekey,Map<String,PricebookEntry> updPresMap)
+    {   System.debug(productid);
+        Date dateFrom = NFMUtil.parseStr2Date(data.EffectiveDateFrom, false);
+        Date dateTo = NFMUtil.parseStr2Date(data.EffectiveDateTo, true);
+        String curr = data.Currency_x == 'RMB' ? 'CNY' : data.Currency_x;
+        
+        PricebookEntry pre = premap.get(pbekey);
+        if(updPresMap.containsKey(pbekey))
+        {
+           pre = updPresMap.get(pbekey);
+        }
+        System.debug('=====3' + pre);
+        String dea = String.isBlank(data.DealerDistinguish) ? '' : '_' + data.DealerDistinguish;
+            if (pre == null){
+                pre = new PricebookEntry(KEY__c =  pbekey,
+                                         //SalesPrice1__c = data.SalesPrice,
+                                         DealerDistinguish_del__c = data.DealerDistinguish,
+                                         CurrencyIsoCode = curr,
+                                         //EffectiveDateFrom1_sales__c = dateFrom,
+                                         //EffectiveDateTo1_sales__c = dateTo,
+                                         UnitPrice = 0,
+                                         Product2Id = productid,
+                                         Pricebook2id = pricebook2.Id,
+                                         isActive = pricebook2.isActive,
+                                         UseStandardPrice = false);   
+                if(String.isNotBlank(data.DealerDistinguish)){
+                    pre.put('SalesPrice1' + data.DealerDistinguish + '__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom1_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                    pre.put('EffectiveDateTo1_sales_' + data.DealerDistinguish + '__c',dateTo);
+                }
+                else{
+                    pre.put('SalesPrice1__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom1_sales__c' , dateFrom);
+                    pre.put('EffectiveDateTo1_sales__c',dateTo);
+                }
+
+            }
+            else if((Date)pre.get('EffectiveDateFrom1_sales' + dea + '__c') == null || (Date)pre.get('EffectiveDateTo1_sales' + dea + '__c') < Date.today() || (Date)pre.get('EffectiveDateFrom1_sales'+ dea + '__c') == dateFrom){
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice1__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom1_sales__c = dateFrom,
+                    //                         //EffectiveDateTo1_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false); 
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice1' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                        pre.put('SalesPrice1__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales__c',dateTo);
+                    }
+            }
+            else if((Date)pre.get('EffectiveDateFrom2_sales' + dea + '__c') == null || (Date)pre.get('EffectiveDateTo2_sales' + dea + '__c') < Date.today() || (Date)pre.get('EffectiveDateFrom2_sales' + dea + '__c') == dateFrom){
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice2__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom2_sales__c = dateFrom,
+                    //                         //EffectiveDateTo2_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);   
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false);  
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice2' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom2_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo2_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                    pre.put('SalesPrice2__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom2_sales__c' , dateFrom);
+                    pre.put('EffectiveDateTo2_sales__c',dateTo);
+                    }
+            }
+            else if((Date)pre.get('EffectiveDateFrom1_sales' + dea + '__c') < (Date)pre.get('EffectiveDateFrom2_sales' + dea + '__c')){
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice1__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom1_sales__c = dateFrom,
+                    //                         //EffectiveDateTo1_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);  
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false); 
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice1' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                        pre.put('SalesPrice1__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales__c',dateTo);
+                    }
+            }
+            else{
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice2__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom2_sales__c = dateFrom,
+                    //                         //EffectiveDateTo2_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);  
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false); 
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice2' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom2_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo2_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                    pre.put('SalesPrice2__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom2_sales__c' , dateFrom);
+                    pre.put('EffectiveDateTo2_sales__c',dateTo);
+                    }
+                }
+            updPresMap.put(pbekey,pre);
+            return pre;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG005Rest.cls-meta.xml b/scr/classes/SBG005Rest.cls-meta.xml
new file mode 100644
index 0000000..e3d1b51
--- /dev/null
+++ b/scr/classes/SBG005Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG005RestTest.cls b/scr/classes/SBG005RestTest.cls
new file mode 100644
index 0000000..addb3cb
--- /dev/null
+++ b/scr/classes/SBG005RestTest.cls
@@ -0,0 +1,1113 @@
+@isTest
+private class SBG005RestTest {
+
+	static Product2 testSBG005Init() {
+
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG005';
+        prd.ProductCode            = 'testSBG005';
+        prd.Name                   = 'testSBG005';
+        prd.IsActive               = true;
+        insert prd;
+        //Pricebook2 prdbook     = new Pricebook2();
+
+        Pricebook2 prdbook1 = new Pricebook2(
+            Name = 'testSBG005',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2(
+            Name = 'testSBG005',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+        return prd;
+
+    }
+
+	@isTest
+	static void testSBG005_void(){
+		testSBG005Init();
+
+		// null
+        // SBG005Rest.SBG005(null);
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        // Monitoring銈掋偦銉冦儓銇椼仾銇�
+        // SBG005Rest.SBG005(GeDatas);
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        // 蹇呴爤闋呯洰銈掋偦銉冦儓銇椼仾銇�
+        // SBG005Rest.SBG005(GeDatas);
+
+        // 鍟嗗搧銈炽兗銉夈亴瀛樺湪銇椼仾銇�
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.ProductCode  = 'testSBG005X';
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        // BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        // SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        Product2[] rslts = [select Id from Product2 where Product_ECCode__c = :GeData.ProductCode];
+        System.assertEquals(0, rslts.size());
+	}
+
+    @isTest
+	static void testSBG005_update() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+	                                 EffectiveDateTo__c,
+	                                 ProductModels__c,
+	                                 ProductStatus__c
+	                            from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+    }
+
+    @isTest
+	static void testSBG005_date() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+	                                 EffectiveDateTo__c,
+	                                 ProductModels__c,
+	                                 ProductStatus__c
+	                            from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+    @isTest
+    static void testSBG005_dateA() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish   = 'A';
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_date0() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_date1() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121203';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom2 = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo2 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.EffectiveDateFrom2__c = dateFrom2;
+        pbe.EffectiveDateTo2__c = dateTo2;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_date2() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121202';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+
+
+
+
+      @isTest
+    static void testSBG005_dateA0() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_dateA1() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121203';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom2 = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo2 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo1_sales_A__c = dateTo;
+        pbe.EffectiveDateFrom2_sales_A__c = dateFrom2;
+        pbe.EffectiveDateTo2_sales_A__c = dateTo2;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_dateA2() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121202';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo1_sales_A__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+     @isTest
+    static void testSBG005_date3() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121202';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.EffectiveDateFrom2__c = dateFrom;
+        pbe.EffectiveDateTo2__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+     @isTest
+    static void testSBG005_dateA3() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121203';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom1 = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo1 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo1_sales_A__c = dateTo;
+        pbe.EffectiveDateFrom2_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo2_sales_A__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+
+
+
+    @isTest
+    static void testSBG005_resend() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005Rest.GeData GeData = new SBG005Rest.GeData();
+        SBG005Rest.GeDatas GeDatas = new SBG005Rest.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005Rest.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+
+        System.Test.startTest();
+        // SBG005Rest.SBG005(GeDatas);
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG005', GeDatas.GeData);
+        SBG005Rest.main(rowData.Id);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                            ErrorLog__c
+                                        from BatchIF_Log__c
+                                        where RowDataFlg__c = true
+                                        and Type__c = 'SBG005'
+                                        order by CreatedDate desc];
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        // SBGITMWebService.execute(rowbl[0].id);
+        SBGITMRest.main(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                Type__c, Log__c, ErrorLog__c,retry_cnt__c
+                from BatchIF_Log__c
+                where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        System.assertEquals(0, bl[0].retry_cnt__c);
+    }
+
+    @isTest static void test_method_Send() {
+
+    Test.startTest();
+
+    RestRequest req = new RestRequest();
+    RestResponse res = new RestResponse();
+
+    // String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG004","MessageGroupNumber": 331591,"NumberOfRecord": 1,"TransmissionDateTime": 201908081115},"GeData": [{"TradeType": "Taxation","SalesChannel": "99","PurposeOfAdvice": "3","ProductSegment": "IE","ProductCode": "N5702700","Other3": "","Other2": "","Other1": "","MachineParts": "Machine","EffectiveDateTo": "99991231","EffectiveDateFrom": "20190801","Currency_x": "RMB","CostPrice": 12241.00}]}}';
+    String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH"},"GeData": [{"TradeType": "Taxation"}]}}';
+    req.requestURI = 'services/apexrest/SBG005/execute';
+    req.httpMethod = 'POST';
+    req.requestBody = Blob.valueof(JsonMsg);
+    RestContext.request = req;
+    RestContext.response= res;
+
+    SBG005Rest.execute();
+
+    Test.stopTest();
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG005RestTest.cls-meta.xml b/scr/classes/SBG005RestTest.cls-meta.xml
new file mode 100644
index 0000000..e3d1b51
--- /dev/null
+++ b/scr/classes/SBG005RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG005WebService.cls b/scr/classes/SBG005WebService.cls
new file mode 100644
index 0000000..d6efa90
--- /dev/null
+++ b/scr/classes/SBG005WebService.cls
@@ -0,0 +1,366 @@
+global class SBG005WebService {
+    public class SBG005WebServiceException extends Exception {}
+    private final Id rowData_Id;
+
+    global class GeDatas {
+        webservice NFMUtil.Monitoring Monitoring;
+        webservice SBG005WebService.GeData[] GeData;
+    }
+    global class GeData {
+        webservice String  ProductCode;
+        webservice String  Currency_x;
+        webservice String  ProductSegment;
+        webservice String  TradeType;
+        webservice String  MachineParts;
+        webservice String  SalesChannel;
+        webservice Decimal SalesPrice;
+        webservice String  DealerDistinguish;
+        webservice String  EffectiveDateFrom;
+        webservice String  EffectiveDateTo;
+        webservice String  PurposeOfAdvice;
+        webservice String  Other1;
+        webservice String  Other2;
+        webservice String  Other3;
+    }
+    webservice static void SBG005(GeDatas geDatas) {
+        if (geDatas == null) {
+            return;
+        }
+        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG005', GeDatas.GeData);
+        if (GeDatas.GeData == null || GeDatas.GeData.size() == 0) {
+            return;
+        }
+        rowData.retry_cnt__c = 1;
+        update rowData;
+        //SBG005WebService u = new SBG005WebService(rowData.Id, 0, GeDatas.GeData.size());
+        //Database.executeBatch(u, 1);
+        if (Test.isRunningTest()) {
+            Id execBTId = Database.executeBatch(new LogAutoSendBatchProduct(), 4);
+        }
+        else{
+            LogAutoSendScheduleProduct.assignOneMinute();
+        }
+    }
+
+    /**
+     * batch銈炽兂銈广偪銉炽儓銆併儜銉┿儭銉笺偪銈掑彈銇戝彇銈�
+     */
+
+
+    global static void execute(Database.BatchableContext BC, List<BatchIF_Log__c> scope) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = scope[0];
+        //String logstr = rowData.MessageGroupNumber__c + ' ' + startIndex + '/' + dataLength + ' start\n';
+        String logstr = '';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG005';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        //iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> purchasePriceList2 = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (purchasePriceList2 == null || purchasePriceList2.size() == 0) {
+            return;
+        }
+        List<GeData> purchasePriceList = new List<GeData>();
+        List<String> productCodeList = new List<String>();
+        for (Integer i = 0; i < purchasePriceList2.size(); i++) {
+            purchasePriceList.add(purchasePriceList2.get(i));
+            if (String.isBlank(purchasePriceList2.get(i).ProductCode) == false) {
+                productCodeList.add(purchasePriceList2.get(i).ProductCode);
+            }
+        }
+
+        Map<String, Product2> prdsMap = new Map<String, Product2>();
+        for (Product2 prd : [select Id, ProductCode, Product_ECCode__c,
+                                         EffectiveDateTo__c,
+                                         ProductModels__c,
+                                         ProductStatus__c
+                                    from Product2
+                                   where ProductModels__c = false and ProductCode in :productCodeList]
+        ) {
+            prdsMap.put(prd.ProductCode, prd);
+        }
+
+        Map <String,Pricebook2 > prebookmap = new Map<String,Pricebook2 >();
+
+        for(Pricebook2 pre : [Select Id,Name,MachineParts__c,ProductSegment__c,SalesChannel__c,TradeType__c,isActive
+                                 from Pricebook2 where IsStandard = false])
+        {
+            prebookmap.put(pre.ProductSegment__c + '_' + pre.TradeType__c + '_' + pre.SalesChannel__c + '_' + pre.MachineParts__c,pre);
+        }
+
+
+        List<String> prekeys = new List<String>();
+        for(GeData data : purchasePriceList2)
+        {
+            String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+            String key = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+            prekeys.add(key);
+        }
+        system.debug('=====0:' + prekeys);
+        Map <String,PricebookEntry > premap = new Map<String,PricebookEntry >();
+        for(PricebookEntry pre : [Select Id,Name,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,EffectiveDateTo1__c,EffectiveDateTo2__c,
+                                        EffectiveDateFrom1_sales__c,EffectiveDateFrom1_sales_A__c,EffectiveDateFrom1_sales_B__c,EffectiveDateFrom1_sales_C__c,
+                                        EffectiveDateFrom2_sales__c,EffectiveDateFrom2_sales_A__c,EffectiveDateFrom2_sales_B__c,EffectiveDateFrom2_sales_C__c,
+                                        EffectiveDateTo1_sales__c,EffectiveDateTo1_sales_A__c,EffectiveDateTo1_sales_B__c,EffectiveDateTo1_sales_C__c,
+                                        EffectiveDateTo2_sales__c,EffectiveDateTo2_sales_A__c,EffectiveDateTo2_sales_B__c,EffectiveDateTo2_sales_C__c,
+                                        CostPrice1__c,CostPrice2__c,
+                                        SalesPrice1__c,SalesPrice1A__c,SalesPrice1B__c,SalesPrice1C__c,
+                                        SalesPrice2__c,SalesPrice2A__c,SalesPrice2B__c,SalesPrice2C__c
+                                 from PricebookEntry where KEY__c in:prekeys])
+        {
+            premap.put(pre.KEY__c,pre);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+    try {
+        Map<String,PricebookEntry> updPresMap = new Map<String,PricebookEntry>();
+        for (Integer i = 0; i < purchasePriceList2.size(); i++) 
+        {
+            //purchasePriceList.add(purchasePriceList2.get(i));
+            GeData data = purchasePriceList2.get(i);
+            if (data.PurposeOfAdvice == '1') {
+                    data.EffectiveDateTo = NFMUtil.formatDate2Str(Date.today().addDays(-1));
+                }
+            if (String.isBlank(purchasePriceList2.get(i).ProductCode) == false) 
+            {
+                //productCodeList.add(purchasePriceList2.get(i).ProductCode);
+                if (data.ProductCode == null || data.ProductCode == '') {
+                    iflog.ErrorLog__c += 'ProductCode is required\n';
+                    continue;
+                }
+                if (data.ProductSegment == null || data.ProductSegment == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']PriceType is required\n';
+                    continue;
+                }
+                if (data.Currency_x == null || data.Currency_x == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']Currency is required\n';
+                    continue;
+                }
+                if (data.EffectiveDateFrom == null || data.EffectiveDateFrom == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateFrom is required\n';
+                    continue;
+                }
+                if (data.EffectiveDateTo == null || data.EffectiveDateTo == '') {
+                    iflog.ErrorLog__c += '[' + data.ProductCode + ']EffectiveDateTo is required\n';
+                    continue;
+                }
+                if(prdsMap.get(data.ProductCode) == null){
+                    iflog.ErrorLog__c += 'Product[' + data.ProductCode + ']NotExist\n';
+                    continue;
+                }
+
+                String salesChannel = data.SalesChannel == '41' ? 'dealer' : 'direct';
+                String pbekey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts + '_' + data.ProductCode + '_' + data.Currency_x;
+                String pbkey = data.ProductSegment + '_' + data.TradeType + '_' + salesChannel + '_' + data.MachineParts;
+                System.debug(prdsMap.get(data.ProductCode));
+                System.debug(prebookmap);
+                if(!prebookmap.keyset().contains(pbkey)){
+                     iflog.ErrorLog__c += 'Pricebook2[' + pbkey + ']NotExist\n';
+                    continue;
+                }
+                if(String.isBlank(prebookmap.get(pbkey).Id))
+                {
+                    iflog.ErrorLog__c += 'Pricebook2[' + pbkey + ']NotExist\n';
+                    continue;
+                }
+                System.debug('=====1:' + premap);
+                PricebookEntry pre1 = setpricebookec(data,premap,prdsMap.get(data.ProductCode).Id,prebookmap.get(pbkey),pbekey,updPresMap);
+                System.debug('=====2:' + pre1);
+
+
+            }
+        }
+        logstr += 'Execute Record:' + updPresMap.keySet().size() + '\n';
+        upsert(updPresMap.Values());
+
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG005_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG005_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            Database.rollback(sp);
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                LogAutoSendScheduleProduct.assignOneMinute();
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+
+    global static PricebookEntry setpricebookec(GeData data,Map<String,PricebookEntry> premap,String productid,Pricebook2 pricebook2,String pbekey,Map<String,PricebookEntry> updPresMap)
+    {   System.debug(productid);
+        Date dateFrom = NFMUtil.parseStr2Date(data.EffectiveDateFrom, false);
+        Date dateTo = NFMUtil.parseStr2Date(data.EffectiveDateTo, true);
+        String curr = data.Currency_x == 'RMB' ? 'CNY' : data.Currency_x;
+        
+        PricebookEntry pre = premap.get(pbekey);
+        if(updPresMap.containsKey(pbekey))
+        {
+           pre = updPresMap.get(pbekey);
+        }
+        System.debug('=====3' + pre);
+        String dea = String.isBlank(data.DealerDistinguish) ? '' : '_' + data.DealerDistinguish;
+            if (pre == null){
+                pre = new PricebookEntry(KEY__c =  pbekey,
+                                         //SalesPrice1__c = data.SalesPrice,
+                                         DealerDistinguish_del__c = data.DealerDistinguish,
+                                         CurrencyIsoCode = curr,
+                                         //EffectiveDateFrom1_sales__c = dateFrom,
+                                         //EffectiveDateTo1_sales__c = dateTo,
+                                         UnitPrice = 0,
+                                         Product2Id = productid,
+                                         Pricebook2id = pricebook2.Id,
+                                         isActive = pricebook2.isActive,
+                                         UseStandardPrice = false);   
+                if(String.isNotBlank(data.DealerDistinguish)){
+                    pre.put('SalesPrice1' + data.DealerDistinguish + '__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom1_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                    pre.put('EffectiveDateTo1_sales_' + data.DealerDistinguish + '__c',dateTo);
+                }
+                else{
+                    pre.put('SalesPrice1__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom1_sales__c' , dateFrom);
+                    pre.put('EffectiveDateTo1_sales__c',dateTo);
+                }
+
+            }
+            else if((Date)pre.get('EffectiveDateFrom1_sales' + dea + '__c') == null || (Date)pre.get('EffectiveDateTo1_sales' + dea + '__c') < Date.today() || (Date)pre.get('EffectiveDateFrom1_sales'+ dea + '__c') == dateFrom){
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice1__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom1_sales__c = dateFrom,
+                    //                         //EffectiveDateTo1_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false); 
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice1' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                        pre.put('SalesPrice1__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales__c',dateTo);
+                    }
+            }
+            else if((Date)pre.get('EffectiveDateFrom2_sales' + dea + '__c') == null || (Date)pre.get('EffectiveDateTo2_sales' + dea + '__c') < Date.today() || (Date)pre.get('EffectiveDateFrom2_sales' + dea + '__c') == dateFrom){
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice2__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom2_sales__c = dateFrom,
+                    //                         //EffectiveDateTo2_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);   
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false);  
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice2' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom2_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo2_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                    pre.put('SalesPrice2__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom2_sales__c' , dateFrom);
+                    pre.put('EffectiveDateTo2_sales__c',dateTo);
+                    }
+            }
+            else if((Date)pre.get('EffectiveDateFrom1_sales' + dea + '__c') < (Date)pre.get('EffectiveDateFrom2_sales' + dea + '__c')){
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice1__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom1_sales__c = dateFrom,
+                    //                         //EffectiveDateTo1_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);  
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false); 
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice1' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                        pre.put('SalesPrice1__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom1_sales__c' , dateFrom);
+                        pre.put('EffectiveDateTo1_sales__c',dateTo);
+                    }
+            }
+            else{
+                    //pre = new PricebookEntry(KEY__c =  pbekey,
+                    //                         Id = pre.Id,
+                    //                         //SalesPrice2__c = data.SalesPrice,
+                    //                         DealerDistinguish_del__c = data.DealerDistinguish,
+                    //                         CurrencyIsoCode = curr,
+                    //                         //EffectiveDateFrom2_sales__c = dateFrom,
+                    //                         //EffectiveDateTo2_sales__c = dateTo,
+                    //                         UnitPrice = 0,
+                    //                         Product2Id = productid,
+                    //                         Pricebook2id = pricebook2.Id,
+                    //                         isActive = pricebook2.isActive,
+                    //                         UseStandardPrice = false);  
+                        pre.put('Id' , pre.Id);
+                        pre.put('DealerDistinguish_del__c',data.DealerDistinguish);
+                        pre.put('UnitPrice',0);
+                        pre.put('isActive',pricebook2.isActive);
+                        pre.put('UseStandardPrice',false); 
+                    if(String.isNotBlank(data.DealerDistinguish)){
+                        pre.put('SalesPrice2' + data.DealerDistinguish + '__c',data.SalesPrice);
+                        pre.put('EffectiveDateFrom2_sales_' + data.DealerDistinguish + '__c' , dateFrom);
+                        pre.put('EffectiveDateTo2_sales_' + data.DealerDistinguish + '__c',dateTo);
+                    }
+                    else{
+                    pre.put('SalesPrice2__c',data.SalesPrice);
+                    pre.put('EffectiveDateFrom2_sales__c' , dateFrom);
+                    pre.put('EffectiveDateTo2_sales__c',dateTo);
+                    }
+                }
+            updPresMap.put(pbekey,pre);
+            return pre;
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG005WebService.cls-meta.xml b/scr/classes/SBG005WebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG005WebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG005WebServiceTest.cls b/scr/classes/SBG005WebServiceTest.cls
new file mode 100644
index 0000000..2d65086
--- /dev/null
+++ b/scr/classes/SBG005WebServiceTest.cls
@@ -0,0 +1,1065 @@
+@isTest
+private class SBG005WebServiceTest
+{
+       static Product2 testSBG005Init() {
+
+         Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG005';
+        prd.ProductCode            = 'testSBG005';
+        prd.Name                   = 'testSBG005';
+        prd.IsActive               = true;
+        insert prd;  
+        //Pricebook2 prdbook     = new Pricebook2();
+
+        Pricebook2 prdbook1 = new Pricebook2( 
+            Name = 'testSBG005',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2( 
+            Name = 'testSBG005',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+        return prd;
+        
+    }
+
+	@isTest
+	static void testSBG005_void(){
+		testSBG005Init();
+
+		// null
+        SBG005WebService.SBG005(null);
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        // Monitoring銈掋偦銉冦儓銇椼仾銇�
+        SBG005WebService.SBG005(GeDatas);
+        
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        // 蹇呴爤闋呯洰銈掋偦銉冦儓銇椼仾銇�
+        SBG005WebService.SBG005(GeDatas);
+
+        // 鍟嗗搧銈炽兗銉夈亴瀛樺湪銇椼仾銇�
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.ProductCode  = 'testSBG005X';
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+        
+        Product2[] rslts = [select Id from Product2 where Product_ECCode__c = :GeData.ProductCode];
+        System.assertEquals(0, rslts.size());
+	}
+
+    @isTest
+	static void testSBG005_update() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+	                                 EffectiveDateTo__c,
+	                                 ProductModels__c,
+	                                 ProductStatus__c
+	                            from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+    }
+
+    @isTest
+	static void testSBG005_date() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+	                                 EffectiveDateTo__c,
+	                                 ProductModels__c,
+	                                 ProductStatus__c
+	                            from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+    @isTest
+    static void testSBG005_dateA() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish   = 'A';
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_date0() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+        
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_date1() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121203';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom2 = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo2 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.EffectiveDateFrom2__c = dateFrom2;
+        pbe.EffectiveDateTo2__c = dateTo2;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_date2() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121202';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+
+
+
+
+      @isTest
+    static void testSBG005_dateA0() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+        
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_dateA1() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121203';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom2 = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo2 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo1_sales_A__c = dateTo;
+        pbe.EffectiveDateFrom2_sales_A__c = dateFrom2;
+        pbe.EffectiveDateTo2_sales_A__c = dateTo2;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+     @isTest
+    static void testSBG005_dateA2() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121202';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo1_sales_A__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+     @isTest
+    static void testSBG005_date3() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121202';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1__c = dateFrom;
+        pbe.EffectiveDateTo1__c = dateTo;
+        pbe.EffectiveDateFrom2__c = dateFrom;
+        pbe.EffectiveDateTo2__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+     @isTest
+    static void testSBG005_dateA3() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121203';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+        GeData.ProductSegment     = 'BS';
+        GeData.MachineParts       = 'Machine';
+        GeData.SalesChannel       = 'direct';
+        GeData.TradeType          = 'Taxation';
+        GeData.SalesPrice          = 100;
+        GeData.DealerDistinguish = 'A';
+
+
+        List<Product2> rslts1 = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2];
+        System.debug(rslts1);
+
+
+
+
+        Pricebook2 p2 = [Select Id,Name From Pricebook2 Where SalesChannel__c = 'direct'];
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = p2.Id;
+        pbe.Product2Id      = rslts1[0].Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        pbe.KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD';
+        Date dateFrom = NFMUtil.parseStr2Date('20131202', false);
+        Date dateTo = NFMUtil.parseStr2Date('20191204', true);
+        Date dateFrom1 = NFMUtil.parseStr2Date('20131201', false);
+        Date dateTo1 = NFMUtil.parseStr2Date('20191204', true);
+        pbe.EffectiveDateFrom1_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo1_sales_A__c = dateTo;
+        pbe.EffectiveDateFrom2_sales_A__c = dateFrom;
+        pbe.EffectiveDateTo2_sales_A__c = dateTo;
+        pbe.UseStandardPrice = false;
+
+
+
+
+
+
+        insert pbe;
+
+
+
+
+
+
+
+
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        List<PricebookEntry>  pres = [Select Id,Name,Pricebook2Id,Product2Id,KEY__c,EffectiveDateFrom1__c,EffectiveDateFrom2__c,
+                                 EffectiveDateTo1__c,EffectiveDateTo2__c,CostPrice1__c,CostPrice2__c,SalesPrice1__c,SalesPrice2__c
+                                 from PricebookEntry Where KEY__c = 'BS_Taxation_direct_Machine_testSBG005_USD'];
+        List<Pricebook2> pr =   [Select Id,Name,ProductSegment__c,TradeType__c,SalesChannel__c,MachineParts__c
+                                 from Pricebook2 Where Id = :pres[0].Pricebook2Id];   
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+        System.assertEquals(pr[0].ProductSegment__c,'BS');
+        System.assertEquals(pr[0].TradeType__c,'Taxation');
+        System.assertEquals(pr[0].SalesChannel__c,'direct');
+        System.assertEquals(pr[0].MachineParts__c,'Machine');
+    }
+
+
+
+
+
+
+    @isTest
+    static void testSBG005_resend() {
+        Product2 prd = testSBG005Init();
+        prd.EffectiveDateTo__c = date.newinstance(2012, 12, 1);
+        update prd;
+
+        SBG005WebService.GeData GeData = new SBG005WebService.GeData();
+        SBG005WebService.GeDatas GeDatas = new SBG005WebService.GeDatas();
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+
+
+        GeDatas.GeData = new SBG005WebService.GeData[] { GeData };
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '32';
+        GeData.ProductCode  = 'testSBG005';
+        GeData.Currency_x         = 'USD';
+        GeData.EffectiveDateFrom  = '20121201';
+        GeData.EffectiveDateTo    = '29121204';
+        GeData.PurposeOfAdvice    = '2';
+
+        System.Test.startTest();
+        SBG005WebService.SBG005(GeDatas);
+        System.Test.stopTest();
+
+        List<Product2> rslts = [select Id, ProductCode, Product_ECCode__c,
+                                     EffectiveDateTo__c,
+                                     ProductModels__c,
+                                     ProductStatus__c
+                                from Product2
+                                where Product_ECCode__c = :GeData.ProductCode];
+        // delete銇牬鍚堛�丒ffectiveDateTo 銇屽墠鏃�
+        System.assertEquals(1, rslts.size());
+        System.assertEquals(date.newinstance(2012, 12, 01), rslts[0].EffectiveDateTo__c);
+
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                            ErrorLog__c
+                                        from BatchIF_Log__c
+                                        where RowDataFlg__c = true
+                                        and Type__c = 'SBG005'
+                                        order by CreatedDate desc];
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        SBGITMWebService.execute(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                Type__c, Log__c, ErrorLog__c,retry_cnt__c
+                from BatchIF_Log__c
+                where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        System.assertEquals(0, bl[0].retry_cnt__c);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG005WebServiceTest.cls-meta.xml b/scr/classes/SBG005WebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG005WebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG007TriggerHandler.cls b/scr/classes/SBG007TriggerHandler.cls
new file mode 100644
index 0000000..ed41915
--- /dev/null
+++ b/scr/classes/SBG007TriggerHandler.cls
@@ -0,0 +1,375 @@
+public class SBG007TriggerHandler {
+    public static boolean isRunning = false;
+    public static String debug_msg = '';
+    public static Set<Id> SBG007_Ids = new Set<Id>();
+    //007淇敼Rest gwy start 2021-04-06
+    public static String status;
+    public class SBG007 {
+        public GeDatas_element GeDatas;
+    }
+
+    public class GeDatas_element {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData_element[] GeData;
+    }
+
+    public class GeData_element {
+        public String SalesAccountCode;
+        public String DealerCode;
+        public String OpportunityCode;
+        public String ProductSegment;
+        public String TradeType;
+        public String MachineParts;
+        public String SalesChannel;
+        public String ExpectedDeliveryDate;
+        public String DealerSalesStaffName;  
+        public String ForeignTradeCompany;   
+        public String SpecialDeliveryAddress;
+        public String Other1;
+        public String Other2;
+        public String Other3;
+        public GeDataDetails_element[] GeDataDetails;
+        
+    }
+    public class GeDataDetails_element {
+        public Integer DetailLine;
+        public String ItemCode;
+        public Integer ItemQuantity;
+    }
+    //007淇敼Rest gwy end 2021-04-06
+    public static void SBG007OpportunityTrigger(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
+    if (!(Trigger.isBefore && Trigger.isUpdate)) {
+            return;
+        }   
+System.debug('-----SBG007OpportunityTrigger start');
+        Map<Id, Id> accIds = new Map<Id, Id>();
+                List<String> strlist = new List<String>();
+                for (Opportunity newOpp : newList) {
+                    strlist.add(newOpp.id);
+                }
+
+                for (Opportunity newOpp : newList) {
+                     Opportunity oldOpp = oldMap.get(newOpp.Id);
+                     if (newOpp.the_Upload_of_quotation_number__c != oldOpp.the_Upload_of_quotation_number__c 
+                             && String.isblank(newOpp.the_Upload_of_quotation_number__c) == false){
+                        SBG007TriggerHandler.SBG007_Ids.add(newOpp.Id);
+                        BatchIF_Log__c iflog = new BatchIF_Log__c();
+                        iflog.Type__c = 'SBG007';
+                        iflog.Log__c  = 'callout start\n';
+                        insert iflog;
+                        iflog = [Select Id, Name from BatchIF_Log__c where Id = :iflog.Id];
+                        SBG007TriggerHandler.callout(iflog.id,strlist,new Map<String,String>());
+            }
+        }
+    } 
+
+
+
+    /**
+     * SBG007銇�佷俊鍑︾悊s
+     *
+     * @param iflog_Id           銉偘銉嗐兗銉栥儷銇甀d
+     * @param oppIds             閫佷俊瀵捐薄鍟嗚珖(璜栫悊涓�1浠躲伄銇裤仹銇�)
+     * @param purposeOfAdviceMap 1:Delete 2:Add(Insert) 3:Change(Update)
+     */
+    @future (callout=true)
+    public static void callout(String iflog_Id, List<String> oppIds, Map<String, String> purposeOfAdviceMap) {
+        if (oppIds == null || oppIds.size() == 0) {
+            return;
+        }
+        /*Sbg007Sync.HTTPS_Port stub = new Sbg007Sync.HTTPS_Port();
+        stub.timeout_x = 100000; // timeout in milliseconds
+        stub.endpoint_x = NFMUtil.SBG007_ENDPOINT;
+        stub.inputHttpHeaders_x = new Map<String, String>();
+        stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+        if (NFMUtil.CLIENT_CERT_NAME != null) {
+            stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+        }*/
+
+        // MessageGroupNumber 銇彇寰�
+        List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog_Id];
+        BatchIF_Log__c iflog = null;
+        if (iflogList.size() > 0) {
+            iflog = iflogList.get(0);
+            iflog.ErrorLog__c = '';
+        } else {
+            // 銉囥兗銈垮彇銈屻仯銇︺仾銇勩仺銇�乺ollback銇曘倢銇︺亜銈嬨亾銇ㄣ仹銇�
+            return;
+        }
+        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + oppIds.size() + '\n';
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        //007淇敼Rest gwy start 2021-04-06
+        //Sbg007Sync.GeDatas_element quotations = new Sbg007Sync.GeDatas_element();
+        //quotations.Monitoring = new OlympusCoJpCommonMessage.Monitoring();
+        GeDatas_element quotations = new GeDatas_element();
+        quotations.Monitoring = new NFMUtil.Monitoring();
+        //007淇敼Rest gwy end 2021-04-06
+        quotations.Monitoring.Tag                  = 'MSGH';
+        quotations.Monitoring.Sender               = '8402';
+        quotations.Monitoring.Receiver             = '1330';
+        quotations.Monitoring.MessageType          = 'SBG007';
+        quotations.Monitoring.MessageGroupNumber   = iflog.Name;
+        quotations.Monitoring.NumberOfRecord       = '' + oppIds.size();
+        quotations.Monitoring.TransmissionDateTime = nowStr;
+        quotations.Monitoring.Text = '';
+
+        BatchIF_Log__c rowData = null;
+        try {
+            // 杌㈤�併儑銉笺偪銈掑彇寰椼�佸弬鐓у厛銇儑銉笺偪銇屻亗銈嬨伄銇с�併亾銇撱仹妞滅储蹇呰銇с仚銆�
+            List<Opportunity> oppList = [select Id, Name, CurrencyIsoCode,
+                                                Owner.Name,AccountId__c,Account.ManagementCode_F__c,Dealer__r.DummyDealer__c,InquiryNumber__c,
+                                                ProductSegment__c, TradeType__c,
+                                                EndUser__c, Machine_Parts__c,
+                                                SalesChannel__c, ExpectedDeliveryDate__c, DealerId__c,Dealer__r.ManagementCode_F__c,Dealer__r.ManagementCode_Ext__c,DealerSalesStaffName__c,
+                                                ForeignTradeCompany__c, SpecialDeliveryAddress__c,
+                                                SyncedQuoteId
+                                           from Opportunity where Id IN :oppIds];
+System.debug('11111 oppList='+oppList);
+            
+            //XHL-20190510-AddStart
+            List<String> syncedQuoteIdList = new List<String>();
+            //Map<String,String> appMap = new Map<String,String>();
+            for (Opportunity opp : oppList) {
+                syncedQuoteIdList.add(opp.SyncedQuoteId);
+                system.debug('SyncedQuoteId__20190528__' + opp.SyncedQuoteId);
+                //appMap.put(opp.Id,opp.SyncedQuoteId);
+            }
+            List<DecideQuoteProductSet__c> decideQuoteProductSetList = [
+                                select Id,Name,DecideProductSet__c,DecideProductSetCount__c,
+                                    DecideOpportunity__c,DecideProductSet__r.Code__c,
+                                    DecideQuote__c,DecideProductSet__r.Name
+                                from DecideQuoteProductSet__c
+                                where DecideQuote__c In :syncedQuoteIdList
+                                ];
+            //Map<String,String> bppMap = new Map<String,String>();
+            Map<String,String> dqpsNameAndCountMap = new Map<String,String>();
+            String name ; String count;
+            String value; String bppMapGetValue;
+
+            for (DecideQuoteProductSet__c dqps :decideQuoteProductSetList) {
+                name = dqps.DecideProductSet__r.Code__c;
+                count = String.valueOf(dqps.DecideProductSetCount__c);
+                value = name +','+ count;
+                if (dqpsNameAndCountMap.containsKey(dqps.DecideQuote__c)) {
+
+                    bppMapGetValue = dqpsNameAndCountMap.get(dqps.DecideQuote__c) +';'+ value ;
+                    dqpsNameAndCountMap.put(dqps.DecideQuote__c, bppMapGetValue);
+                } else {
+                    dqpsNameAndCountMap.put(dqps.DecideQuote__c, value);
+                }
+                //bppMap.put(dqps.DecideQuote__c+','+,count+','+code )  
+            }
+            //XHL-20190510-AddEnd
+
+            // Quotation銇儑銉笺偪銇ō瀹�
+            //007淇敼Rest gwy start 2021-04-06
+            //quotations.GeData = new List<Sbg007Sync.GeData_element>();
+            quotations.GeData = new List<GeData_element>();
+            //007淇敼Rest gwy end 2021-04-06
+            for (Opportunity opp : oppList) { 
+                // 鍟嗚珖鍟嗗搧鎯呭牨銈掑彇寰� 
+                List<OpportunityLineItem> oppLiList = 
+                                        [select Id, Quantity, PricebookEntry.ProductCode, 
+                                            OpportunityId,OLISingleProduct__c
+                                         from OpportunityLineItem 
+                                         where Opportunity.Id = :opp.Id 
+                                         order by OLISingleProduct__c desc];
+
+                system.debug('oppLiList_20190528_' +oppLiList);
+                //007淇敼Rest gwy start 2021-04-06
+                //Sbg007Sync.GeData_element quotation = new Sbg007Sync.GeData_element();
+                GeData_element quotation = new GeData_element();
+                //007淇敼Rest gwy end 2021-04-06
+                if (opp.Dealer__r.DummyDealer__c == true){
+                quotation.SalesAccountCode                   = opp.Account.ManagementCode_F__c;
+                quotation.DealerCode          = opp.Account.ManagementCode_F__c;
+                }
+                else{
+                quotation.SalesAccountCode                   = opp.Dealer__r.ManagementCode_F__c;
+                quotation.DealerCode          = opp.Dealer__r.ManagementCode_Ext__c;
+                }
+                quotations.GeData.add(quotation);
+                quotation.OpportunityCode                = opp.InquiryNumber__c;
+//                quotation.SalesAccountCode                   = opp.Dealer__r.ManagementCode_F__c;
+                quotation.ProductSegment              = opp.ProductSegment__c;
+                quotation.TradeType              = opp.TradeType__c;
+                quotation.MachineParts                   = opp.Machine_Parts__c;
+                quotation.SalesChannel   = opp.Machine_Parts__c == 'Parts' ? '40' : opp.SalesChannel__c == 'dealer' ?  '41' : '42';
+                quotation.ExpectedDeliveryDate          = NFMUtil.formatDate2Str(opp.ExpectedDeliveryDate__c);
+//                quotation.DealerCode          = opp.Dealer__r.ManagementCode_Ext__c;
+                quotation.DealerSalesStaffName         = opp.DealerSalesStaffName__c;
+                quotation.ForeignTradeCompany                   = opp.ForeignTradeCompany__c;
+                quotation.SpecialDeliveryAddress                   = opp.SpecialDeliveryAddress__c;
+                
+                //007淇敼Rest gwy start 2021-04-06
+                quotation.GeDataDetails = new List<GeDataDetails_element>();
+                //007淇敼Rest gwy end 2021-04-06
+                Integer m = 0 ;
+                for (Integer i = 0; i < oppLiList.size(); i++) {
+                    //XHL-20190510-AddStart
+                    if (!oppLiList.get(i).OLISingleProduct__c) {
+                        continue;
+                    } 
+                    m++;
+                    //XHL-20190510-AddEnd
+                    //007淇敼Rest gwy start 2021-04-06
+                    GeDataDetails_element detail = new GeDataDetails_element();
+                    //007淇敼Rest gwy end 2021-04-06
+                    quotation.GeDataDetails.add(detail);
+                    detail.DetailLine                  = (i + 1) * 10;
+                    detail.ItemCode                    = oppLiList.get(i).PricebookEntry.ProductCode;
+                    detail.ItemQuantity                = Integer.valueOf(oppLiList.get(i).Quantity);
+                }
+
+                //XHL-20190510-AddStart
+                if (dqpsNameAndCountMap.containsKey(opp.SyncedQuoteId)) {
+                    value = dqpsNameAndCountMap.get(opp.SyncedQuoteId);
+                    List<String> nameCountList = new List<String>();
+                    for (String str: value.split(';')){
+                        nameCountList.add(str);
+                    }
+                    if (nameCountList.size() > 0 ){
+                        for (String  namCount :nameCountList) {
+                            //007淇敼Rest gwy start 2021-04-06
+                            //Sbg007Sync.GeDataDetails_element detail = new Sbg007Sync.GeDataDetails_element();
+                            GeDataDetails_element detail = new GeDataDetails_element();
+                            //007淇敼Rest gwy end 2021-04-06
+                            quotation.GeDataDetails.add(detail);
+                            detail.DetailLine                  = (m + 1) * 10;
+                            detail.ItemCode                    = namCount.split(',')[0];
+                            detail.ItemQuantity                = Integer.valueOf(namCount.split(',')[1]);
+                            m++;
+                        }
+                    }
+
+                }
+                //XHL-20190510-AddEnd
+
+                logstr += quotation.OpportunityCode + '\n';
+
+            }
+
+            if (quotations.GeData.size() > 0) {
+                //Sbg007Sync.Quotations_element[] pQuotations = new Sbg007Sync.Quotations_element[] { quotations };
+                logstr += '\ncallout count=' + quotations.GeData.size();
+                //OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG007_Sync_BC2GPI(pQuotations);
+                // 鍘熷墖闈炲悓鏈熴仹銇欍伄銇с�乴ogs銈掔⒑瑾嶃仚銈嬪繀瑕併亴銇亜銇с仐銈囥亞銆�
+                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+                Monitoring.Tag                  = quotations.Monitoring.Tag;
+                Monitoring.Sender               = quotations.Monitoring.Sender;
+                Monitoring.Receiver             = quotations.Monitoring.Receiver;
+                Monitoring.MessageType          = quotations.Monitoring.MessageType;
+                Monitoring.MessageGroupNumber   = quotations.Monitoring.MessageGroupNumber;
+                Monitoring.NumberOfRecord       = quotations.Monitoring.NumberOfRecord;
+                Monitoring.TransmissionDateTime = quotations.Monitoring.TransmissionDateTime;
+                Monitoring.Text = '';
+                //007淇敼Rest gwy start 2021-04-07
+                SBG007 sBG007 = new SBG007();
+                sBG007.GeDatas =  quotations;
+                rowData = NFMUtil.makeRowData(Monitoring, 'SBG007', sBG007);
+                //007淇敼Rest gwy end 2021-04-07
+                execute(rowData, iflog);
+            }
+            Set<String> inquiryNoList = new Set<String>();
+
+            Map<String, Opportunity> oppUpsertMap = new Map<String, Opportunity>();
+            logstr += '\nend';
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG007_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG007_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+        }
+        if (rowData != null) {
+            insert rowData;
+        }
+
+        System.debug(Logginglevel.DEBUG, 'SBG007_' + iflog.Name + ' end');
+        iflog.Log__c = logstr;
+        update iflog;
+    }
+
+    public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {
+        //gaozw
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        SBG007 sBG007 = (SBG007) JSON.deserialize(rowDataStr, SBG007.class);
+
+        //007淇敼Rest gwy start 2021-04-07
+        String logstr = sBG007.GeDatas.Monitoring.MessageGroupNumber + ' start\n';
+        //007淇敼Rest gwy end 2021-04-07
+        Boolean needUpdateIflog = false;
+        if  (iflog == null) {
+            needUpdateIflog = true;
+            iflog = new BatchIF_Log__c();
+            iflog.Type__c = 'SBG007';
+            //007淇敼Rest gwy start 2021-04-07
+            iflog.MessageGroupNumber__c = sBG007.GeDatas.Monitoring.MessageGroupNumber;
+            //007淇敼Rest gwy end 2021-04-07
+            iflog.Log__c = logstr;
+            iflog.ErrorLog__c = '';
+            insert iflog;
+            iflog = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog.Id];
+        } else {
+            logstr = iflog.Log__c;
+        }
+        try{
+            //gaozw
+            /*Sbg007Sync.HTTPS_Port stub = new Sbg007Sync.HTTPS_Port();
+            stub.timeout_x = 100000; // timeout in milliseconds
+            stub.endpoint_x = NFMUtil.SBG007_ENDPOINT;
+            stub.inputHttpHeaders_x = new Map<String, String>();
+            stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+            if (NFMUtil.CLIENT_CERT_NAME != null) {
+                stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+            }*/
+            //007淇敼Rest gwy start 2021-04-12
+            status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.SBG007_ENDPOINT); 
+            if (status == 'OK') {
+                logstr += '\n' + status;
+                rowData.retry_cnt__c = 0;
+            } else {
+                if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+                if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                    rowData.retry_cnt__c++;
+                    LogAutoSendSchedule.assignOneMinute();
+                }
+                if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                    rowData.ErrorLog__c = 'status:' + status +
+                                          '\n閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+                }
+            }
+            //007淇敼Rest gwy end 2021-04-12
+            //Sbg007Sync.GeDatas_element[] pQuotations = new Sbg007Sync.GeDatas_element[] { quotations };
+            //OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG007_Sync_BC2GPI(pQuotations);
+            rowData.retry_cnt__c=0;
+        }catch(Exception ex) {
+            // TODO IOException
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG007_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG007_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+
+            //---xiongyl---add
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+            }
+        }
+        iflog.Log__c = logstr;
+        if (needUpdateIflog) {
+            update iflog;
+            update rowData;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG007TriggerHandler.cls-meta.xml b/scr/classes/SBG007TriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..4935896
--- /dev/null
+++ b/scr/classes/SBG007TriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>37.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG007TriggerHandlerTest.cls b/scr/classes/SBG007TriggerHandlerTest.cls
new file mode 100644
index 0000000..946dcd9
--- /dev/null
+++ b/scr/classes/SBG007TriggerHandlerTest.cls
@@ -0,0 +1,238 @@
+@isTest
+private class SBG007TriggerHandlerTest
+{
+//	static testMethod void itShould(){
+//		List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+//        Account accIE = new Account(
+//        	Name = '*',
+//        	RecordTypeId = rectIE[0].Id,
+//        	OwnerId = UserInfo.getUserId(),
+//        	DivisionName__c='Customer IE',
+//        	FacilityName__c='abc',
+//            PostCode__c = '123456'
+//        );
+//        insert accIE;
+//PriceBook2 pricebook =new PriceBook2(
+//        	Name = 'IE',
+//            ProductSegment__c = 'IE',
+//            TradeType__c = 'Taxation',
+//            SalesChannel__c = 'direct',
+//            MachineParts__c = 'Machine'
+//        );
+//        insert pricebook;
+
+//        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+//        Opportunity opp = new Opportunity(
+//            Name = 'test opp',
+//            the_Upload_of_quotation_number__c = 'test1',
+//            AccountId = accIE.Id,
+//            RecordTypeId = rectOpp[0].Id,
+//            OwnerId = UserInfo.getUserId(),
+//            StageName = 'Prospect Created',
+//            CancelReason__c = 'Inquiry repeat',
+//            Cancel_reason_D__c = 'Inquiry repeat',
+//            CurrencyIsoCode = 'CNY',
+//            ProductSegment__c = 'IE',
+//            CloseDate = Date.today(),
+//            NewInquiryDate__c = Date.today().addDays(-2),
+//            ExpectedOrderDate__c = Date.today().addDays(2),
+//            TradeType__c = 'Taxation',
+//            SalesChannel__c = 'direct',
+//            Machine_Parts__c = 'Machine'
+//        );
+//        insert opp;                
+//         List<OpportunityLineItem> oppLiList = [select Id, Quantity, PricebookEntry.ProductCode, OpportunityId
+//                                           from OpportunityLineItem where Opportunity.Id = :opp.Id ];
+//        OpportunityLineItem oppLineItem = new OpportunityLineItem(
+            
+//            Quantity = 1,
+//            //PricebookEntry.ProductCode='11',
+//            OpportunityId= opp.Id
+//        );
+        
+        
+//        opp.the_Upload_of_quotation_number__c = 'test2';
+//        upsert opp;
+        
+
+        
+        
+
+//        // SBG007銈堛倞銆侀�佷俊銇椼仾銇勩亾銇�
+//           System.assertEquals('', SBG007TriggerHandler.debug_msg);
+
+//	}
+
+    static testMethod void itShould2(){
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+
+        insert accIE;
+        //PriceBook2 pricebook =new PriceBook2(
+        //    Name = 'IE',
+        //    ProductSegment__c = 'IE',
+        //    TradeType__c = 'Taxation',
+        //    SalesChannel__c = 'direct',
+        //    MachineParts__c = 'Machine'
+        //);
+        //insert pricebook;
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            the_Upload_of_quotation_number__c = 'test1',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Prospect Created',
+            CancelReason__c = 'Inquiry repeat',
+            Cancel_reason_D__c = 'Inquiry repeat',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+         Quote quo = new Quote(
+            //Name = 'quo',
+            //OpportunityId = opp.Id,
+            //SetName1__c = 'setname01',
+            //SetQty1__c = 1,
+            //Pricebook2Id = pricebook.Id
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname1',
+            SetQty1__c = 1,
+            SetName2__c = 'setname2',
+            SetQty2__c = 2,
+            Custom_Price_Total_Text__c = 1000
+            //IsSyncing = true
+        );
+        insert quo;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        List<productSet__c>  insertproductSets = new  List<productSet__c>();
+        productSet__c proSet1 = new productSet__c();
+        proSet1.Code__c = 'IXP-7P2';
+        proSet1.Name = 'IXP-7P2';
+        proSet1.IsValid__c = true;
+        proSet1.Name = 'IXP-7P2';
+        insertproductSets.add(proSet1);
+        productSet__c proSet2 = new productSet__c();
+        proSet2.Code__c = 'IXP-7P1SC';
+        proSet2.Name = 'IXP-7P1SC';
+        proSet2.IsValid__c = true;
+        proSet2.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet2);
+        productSet__c proSet3 = new productSet__c();
+        proSet3.Code__c = 'IXSP-T7LED';
+        proSet3.Name = 'IXSP-T7LED';
+        proSet3.IsValid__c = true;
+        proSet3.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet3);
+
+
+        insert insertproductSets;
+
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.ProductCode = 'product3';
+        product3.Product_ECCode__c = 'product3';
+        product3.IsActive = true;
+
+        insert product3;
+
+        PricebookEntry entry1 = new PricebookEntry(
+            Pricebook2Id = pricebook.Id,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            UseStandardPrice = false
+            //CurrencyIsoCode = 'CNY'
+        );
+
+        DecideQuoteProductSet__c dqps = new DecideQuoteProductSet__c();
+
+        dqps.DecideProductSet__c = proSet1.Id ;
+        dqps.DecideProductSetCount__c = 4;
+        dqps.DecideOpportunity__c = opp.Id;
+        dqps.DecideQuote__c = quo.Id;
+
+        insert dqps;
+                
+         List<OpportunityLineItem> oppLiList = [select Id, Quantity, PricebookEntry.ProductCode, OpportunityId
+                                           from OpportunityLineItem where Opportunity.Id = :opp.Id ];
+        //OpportunityLineItem oppLineItem = new OpportunityLineItem(
+            
+        //    Quantity = 1,
+        //    //PricebookEntry.ProductCode='11',
+        //    OpportunityId= opp.Id,
+        //    PricebookEntryId = entry1.Id,
+        //     UnitPrice = 10
+        //     //,
+        //     //PricebookEntryId = entry1.Id,
+        //);
+        //OpportunityLineItem oppLineItem1 = new OpportunityLineItem(
+            
+        //    Quantity = 1,
+        //    //PricebookEntry.ProductCode='11',
+        //    OpportunityId= opp.Id,
+        //    OLISingleProduct__c = true,
+        //    PricebookEntryId = entry1.Id,
+        //    UnitPrice = 10
+        //);
+        //insert new OpportunityLineItem[] {oppLineItem,oppLineItem1};
+        
+
+        OpportunityLineItem oli1 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            //PricebookEntryId = entry1.Id,
+            Quantity = 10,
+            UnitPrice = 10,
+            Product2Id = product3.Id 
+        );
+        OpportunityLineItem oli2 = new OpportunityLineItem(
+            OpportunityId = opp.Id,
+            //PricebookEntryId = entry1.Id,
+            Quantity = 20,
+            UnitPrice = 20,
+            Product2Id = product3.Id 
+        );
+        //insert new OpportunityLineItem[] {oli1, oli2};
+        opp.the_Upload_of_quotation_number__c = 'test2';
+        upsert opp;
+        
+
+        
+        
+
+        // SBG007銈堛倞銆侀�佷俊銇椼仾銇勩亾銇�
+           System.assertEquals('', SBG007TriggerHandler.debug_msg);
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG007TriggerHandlerTest.cls-meta.xml b/scr/classes/SBG007TriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/SBG007TriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG010Rest.cls b/scr/classes/SBG010Rest.cls
new file mode 100644
index 0000000..a2c9a40
--- /dev/null
+++ b/scr/classes/SBG010Rest.cls
@@ -0,0 +1,235 @@
+@RestResource(urlMapping='/SBG010/*')
+global with sharing class SBG010Rest {
+	public class SBG010ResrException extends Exception {}
+	global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public SBG010Rest.GeData[] GeData;
+    }
+    global class GeData {
+        public String  OrderCode;
+        public String  SoNo;
+        public String  SoShippingStatus;
+        public String  SoDate;
+        public String  DeliveryDate;
+        public String  Other1;
+        public String  Other2;
+        public String  Other3;
+    }
+
+     @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG010', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+
+    	Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c,retry_cnt__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG010';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> GeDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (GeDataList == null || GeDataList.size() == 0) {
+            return;
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+            List<String> soNoList = new List<String>();
+            List<String> soNoList1 = new List<String>();
+            for (SBG010Rest.GeData GeData : GeDataList) {
+                if (GeData.SoNo == null || GeData.SoNo == '' ||
+                    GeData.OrderCode == null || GeData.OrderCode == '' ||
+                    GeData.SoShippingStatus == null
+                ) {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    continue;
+                }
+                soNoList.add(GeData.OrderCode);
+                if(String.isNotBlank(GeData.DeliveryDate))
+                {
+                    soNoList1.add(GeData.SoNo+GeData.DeliveryDate);
+                }else
+                {
+                    soNoList1.add(GeData.SoNo);
+                }
+               
+            }
+
+
+            List<String> orderid = new List<String>();
+            List<Delivery__c> soList = [select Id, SSBD_Contract__c, Delivery_Money__c,
+                                                Delivery_Date__c, SAP_CreatDate__c,
+                                                Delivery_Status__c,SONO__c
+                                           from Delivery__c
+                                          where SONO__c in :soNoList1];
+            Map<String, Delivery__c> soMap = new Map<String, Delivery__c>();
+            for (Delivery__c so : soList) {
+                orderid.add(so.SSBD_Contract__c);
+                soMap.put(so.SSBD_Contract__c, so);
+            }
+
+             List<String> oids = new List<String>();
+            Map<String,Order> ordermap = new Map<String,Order>();
+            for(Order o : [Select Id,OrderNumber,SAP_Contract__c,DeliveryDate__c,ShippedDate__c From Order Where OrderNumber in :soNoList])
+            {
+                oids.add(o.Id);
+                ordermap.put(o.OrderNumber,o);
+            }
+
+         
+                        
+            // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+            Map<String, Delivery__c> soUpdateMap = new Map<String, Delivery__c>();
+            List<Order> orders = new List<Order>();
+            for (SBG010Rest.GeData GeData : GeDataList) {
+                if (GeData.SoNo == null || GeData.SoNo == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'SoNo is required\n';
+                    continue;
+                }
+                if (GeData.OrderCode == null || GeData.OrderCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'OrderCode is required\n';
+                    continue;
+                }
+                if (GeData.SoShippingStatus == null) {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'SoShippingStatus is required\n';
+                    continue;
+                }
+                Order so = ordermap.get(GeData.OrderCode);
+                if (so == null) {
+                    // 鏇存柊瀵捐薄鍟嗚珖銇屻仾銇勫牬鍚�
+                    iflog.ErrorLog__c += '[' + GeData.SoNo + ']Order[' + GeData.OrderCode + ']NotExist\n';
+                    continue;
+                }
+                //if(String.isBlank(GeData.DeliveryDate))
+                //{
+                //    iflog.ErrorLog__c += '[' + GeData.SoNo + ']Delivery[' + GeData.SoShippingStatus + ']NotExist\n';
+                //    continue;
+                //}
+                // 
+                Delivery__c deliv = new Delivery__c();
+                if(soMap.get(ordermap.get(GeData.OrderCode).Id) != null)
+                {
+                    deliv.Id = soMap.get(ordermap.get(GeData.OrderCode).Id).Id;
+                }
+                if(String.isNotBlank(GeData.DeliveryDate))
+                {
+                    deliv.SONO__c = GeData.SoNo + GeData.DeliveryDate;
+                }else
+                {
+                    deliv.SONO__c = GeData.SoNo;
+                }
+                if(String.isBlank(deliv.Id)){
+                    deliv.SSBD_Contract__c            = ordermap.get(GeData.OrderCode).Id;
+                }
+                List<string> Datesplit = GeData.SoDate.split(',');
+                deliv.Delivery_Status__c             = GeData.SoShippingStatus ;
+                deliv.Delivery_Date__c         = NFMUtil.parseStr2Date(GeData.DeliveryDate, true);
+                deliv.SAP_CreatDate__c   = NFMUtil.parseStr2Date(Datesplit[0], true);
+                System.debug('idis' + ordermap.get(GeData.OrderCode).Id);
+                System.debug('dateis' + ordermap.get(GeData.OrderCode).DeliveryDate__c);
+                soUpdateMap.put(deliv.SONO__c, deliv);
+               
+                if(String.isNotBlank(GeData.SoNo)){
+                    if((NFMUtil.parseStr2Date(GeData.DeliveryDate, true) > ordermap.get(GeData.OrderCode).DeliveryDate__c) || (ordermap.get(GeData.OrderCode).DeliveryDate__c == null)
+                    || (NFMUtil.parseStr2Date(Datesplit[1], true) <> ordermap.get(GeData.OrderCode).ShippedDate__c))
+                    {
+                        if(Datesplit[1] <> '00000000'){
+                        orders.add(new Order(id = ordermap.get(GeData.OrderCode).Id
+                               , SAP_Contract__c = GeData.SoNo , DeliveryDate__c = NFMUtil.parseStr2Date(GeData.DeliveryDate, true),
+                                OrderDate__c = NFMUtil.parseStr2Date(Datesplit[0], true), ShippedDate__c = NFMUtil.parseStr2Date(Datesplit[1], true)));
+                        }
+                        else if(Datesplit[1] == '00000000'){
+                        orders.add(new Order(id = ordermap.get(GeData.OrderCode).Id
+                               , SAP_Contract__c = GeData.SoNo , DeliveryDate__c = NFMUtil.parseStr2Date(GeData.DeliveryDate, true),
+                                OrderDate__c = NFMUtil.parseStr2Date(Datesplit[0], true)));
+                        }
+                    }
+                }
+            }
+            System.debug('ordersize' + orders.size());
+       
+            if (soUpdateMap.size() > 0) {
+                System.debug(soUpdateMap.values());
+                upsert soUpdateMap.values();
+            }
+            if(orders.size()>0)
+            {
+                update orders;
+            }
+//ToDo绗竴娆¤繘鏉ョ殑鏃跺�欐湁鍙兘娌℃湁DeliveryDate锛屽綋绗竴娆℃病鏈塂eliveryDate绗簩娆℃湁鐨勬儏鍐典細娣诲姞涓ゆ潯鍙戣揣璁板綍
+            logstr += '\nend';
+            rowData.retry_cnt__c=0;
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG010_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG010_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                 rowData.retry_cnt__c++;
+                 LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG010Rest.cls-meta.xml b/scr/classes/SBG010Rest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG010Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG010TRestTest.cls b/scr/classes/SBG010TRestTest.cls
new file mode 100644
index 0000000..b4daa85
--- /dev/null
+++ b/scr/classes/SBG010TRestTest.cls
@@ -0,0 +1,263 @@
+@isTest
+private class SBG010TRestTest {
+    static String  setdata(){
+        Id pricebookId = Test.getStandardPricebookId();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            isActive = true
+        );
+        insert pricebook;
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        insert new Product2[] {product1,product2,product3};
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+
+
+        Date day1 = Date.today();
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Prospect Created';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'Sales_Channel_D__c';
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Trade_Type_D__c';
+        //opp.Machine_Parts__c = 'Machine_Parts_D__c';
+        //opp.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress_D__c';
+        //opp.ForeignTradeCompany__c = 'ForeignTradeCompany_D__c';
+        insert opp;
+        OpportunityLineItem oli = new OpportunityLineItem();
+        oli.OpportunityId = opp.Id;
+        oli.Quantity = 2;
+        oli.UnitPrice = 111;
+        oli.Description = 'test';
+        oli.PricebookEntryId = entry1.Id;
+        insert oli;
+        List<RecordType> rectOrder = [select id from RecordType where IsActive = true and SobjectType = 'Order'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            CurrencyIsoCode = 'CNY',
+            RecordTypeId = '01228000000NJt6'
+        );
+        insert odr;
+
+        Delivery__c de1 = new Delivery__c();
+        de1.SSBD_Contract__c = odr.Id;
+
+        insert de1;
+        Order ordd = [Select OrderNumber,Id,Name From Order];
+      return ordd.OrderNumber;
+
+    }
+    @isTest static void test_method_one() {
+   
+    
+        SBG010Rest.GeData GeData = new SBG010Rest.GeData();
+        SBG010Rest.GeDatas GeDatas = new SBG010Rest.GeDatas();
+        GeDatas.GeData = new SBG010Rest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+
+        String ocode = setdata();
+        GeData.OrderCode = ocode;
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+
+        SBG010Rest.main(rowData.Id);
+    }
+
+    @isTest static void test_method2() {
+   
+    
+        SBG010Rest.GeData GeData = new SBG010Rest.GeData();
+        SBG010Rest.GeDatas GeDatas = new SBG010Rest.GeDatas();
+        GeDatas.GeData = new SBG010Rest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+
+        String ocode = setdata();
+        GeData.OrderCode = ocode;
+        GeData.SoNo = '123131';
+        GeData.SoShippingStatus = '鏈彂璐�';
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+
+        SBG010Rest.main(rowData.Id);
+    }
+        @isTest static void test_method3() {
+   
+    
+        SBG010Rest.GeData GeData = new SBG010Rest.GeData();
+        SBG010Rest.GeDatas GeDatas = new SBG010Rest.GeDatas();
+        GeDatas.GeData = new SBG010Rest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+
+        String ocode = setdata();
+  		GeData.OrderCode = ocode;
+        GeData.SoNo = '123131';
+        
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+
+        SBG010Rest.main(rowData.Id);
+    }
+     @isTest static void test_method4() {
+   
+    
+        SBG010Rest.GeData GeData = new SBG010Rest.GeData();
+        SBG010Rest.GeDatas GeDatas = new SBG010Rest.GeDatas();
+        GeDatas.GeData = new SBG010Rest.GeData[] { GeData };
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+
+        String ocode = setdata();
+  
+        GeData.SoNo = '123131';
+        GeData.SoShippingStatus = '鏈彂璐�';
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG004', GeDatas.GeData);
+
+        SBG010Rest.main(rowData.Id);
+    }
+
+
+     @isTest static void test_method_Send() {
+
+    Test.startTest();
+
+    RestRequest req = new RestRequest();
+    RestResponse res = new RestResponse();
+
+    // String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG004","MessageGroupNumber": 331591,"NumberOfRecord": 1,"TransmissionDateTime": 201908081115},"GeData": [{"TradeType": "Taxation","SalesChannel": "99","PurposeOfAdvice": "3","ProductSegment": "IE","ProductCode": "N5702700","Other3": "","Other2": "","Other1": "","MachineParts": "Machine","EffectiveDateTo": "99991231","EffectiveDateFrom": "20190801","Currency_x": "RMB","CostPrice": 12241.00}]}}';
+    String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH"},"GeData":[{"SoShippingStatus": "鍏ㄩ儴鍙戣揣"}]}}';
+    req.requestURI = 'services/apexrest/SBG004/execute';
+    req.httpMethod = 'POST';
+    req.requestBody = Blob.valueof(JsonMsg);
+    RestContext.request = req;
+    RestContext.response= res;
+
+    SBG010Rest.execute();
+
+    Test.stopTest();
+
+   // { "GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG017", "MessageGroupNumber": 331591, "NumberOfRecord": 1, "TransmissionDateTime": 201903251115 },"GeData": [{ "StockAnswer": "OK111","SAPQuotationCode": "20022780  ", "Other3": "", "Other2": "", "Other1": "",  "OpportunityCode": "O-2018-067607"}]}}
+
+    //Test.setMock(HttpCalloutMock.class, new NFM205RestCalloutMock());
+    //NFM205Rest.execute1('{"Monitoring":{"TransmissionDateTime":"201812201320","Text":"","Tag":"MSGH","Sender":"SFDC","Receiver":"SPO","NumberOfRecord":"1","MessageType":"NFM205","MessageGroupNumber":"20180001722190"},"GeData":[{"Opportunity_Code":"HKBJ-GI-BJ0588881","Bidding_No":"as123121","Bidding_Content":"鎷涙爣鍐呭","Bid_Project_Name":"鎷涙爣椤圭洰鍚�","Bid_Date":"20181203","Authorized_Status":"1","Authorized_Finish_Sales":"30033","Authorized_DB_No":"MGZWESQHN201812001","Authorized_Date":"20190316","Autholization_Activated_Date":"20190415"}]}');
+}
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG010TRestTest.cls-meta.xml b/scr/classes/SBG010TRestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG010TRestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG010WebService.cls b/scr/classes/SBG010WebService.cls
new file mode 100644
index 0000000..d33911e
--- /dev/null
+++ b/scr/classes/SBG010WebService.cls
@@ -0,0 +1,201 @@
+global class SBG010WebService {
+
+    global class GeDatas {
+        webservice NFMUtil.Monitoring Monitoring;
+        webservice SBG010WebService.GeData[] GeData;
+    }
+    global class GeData {
+        webservice String  OrderCode;
+        webservice String  SoNo;
+        webservice String  SoShippingStatus;
+        webservice String  SoDate;
+        webservice String  DeliveryDate;
+        webservice String  Other1;
+        webservice String  Other2;
+        webservice String  Other3;
+    }
+    webservice static void SBG010(GeDatas geDatas) {
+        if (geDatas == null) {
+            return;
+        }
+        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG010', GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) execute(rowData.Id);
+    }
+global static void execute(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c,retry_cnt__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG010';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> GeDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (GeDataList == null || GeDataList.size() == 0) {
+            return;
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+            List<String> soNoList = new List<String>();
+            List<String> soNoList1 = new List<String>();
+            for (SBG010WebService.GeData GeData : GeDataList) {
+                if (GeData.SoNo == null || GeData.SoNo == '' ||
+                    GeData.OrderCode == null || GeData.OrderCode == '' ||
+                    GeData.SoShippingStatus == null
+                ) {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    continue;
+                }
+                soNoList.add(GeData.OrderCode);
+                if(String.isNotBlank(GeData.DeliveryDate))
+                {
+                    soNoList1.add(GeData.SoNo+GeData.DeliveryDate);
+                }else
+                {
+                    soNoList1.add(GeData.SoNo);
+                }
+               
+            }
+
+
+            List<String> orderid = new List<String>();
+            List<Delivery__c> soList = [select Id, SSBD_Contract__c, Delivery_Money__c,
+                                                Delivery_Date__c, SAP_CreatDate__c,
+                                                Delivery_Status__c,SONO__c
+                                           from Delivery__c
+                                          where SONO__c in :soNoList1];
+            Map<String, Delivery__c> soMap = new Map<String, Delivery__c>();
+            for (Delivery__c so : soList) {
+                orderid.add(so.SSBD_Contract__c);
+                soMap.put(so.SSBD_Contract__c, so);
+            }
+
+             List<String> oids = new List<String>();
+            Map<String,Order> ordermap = new Map<String,Order>();
+            for(Order o : [Select Id,OrderNumber,SAP_Contract__c,DeliveryDate__c,ShippedDate__c From Order Where OrderNumber in :soNoList])
+            {
+                oids.add(o.Id);
+                ordermap.put(o.OrderNumber,o);
+            }
+
+         
+                        
+            // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+            Map<String, Delivery__c> soUpdateMap = new Map<String, Delivery__c>();
+            List<Order> orders = new List<Order>();
+            for (SBG010WebService.GeData GeData : GeDataList) {
+                if (GeData.SoNo == null || GeData.SoNo == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'SoNo is required\n';
+                    continue;
+                }
+                if (GeData.OrderCode == null || GeData.OrderCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'OrderCode is required\n';
+                    continue;
+                }
+                if (GeData.SoShippingStatus == null) {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'SoShippingStatus is required\n';
+                    continue;
+                }
+                Order so = ordermap.get(GeData.OrderCode);
+                if (so == null) {
+                    // 鏇存柊瀵捐薄鍟嗚珖銇屻仾銇勫牬鍚�
+                    iflog.ErrorLog__c += '[' + GeData.SoNo + ']Order[' + GeData.OrderCode + ']NotExist\n';
+                    continue;
+                }
+                //if(String.isBlank(GeData.DeliveryDate))
+                //{
+                //    iflog.ErrorLog__c += '[' + GeData.SoNo + ']Delivery[' + GeData.SoShippingStatus + ']NotExist\n';
+                //    continue;
+                //}
+                // 
+                Delivery__c deliv = new Delivery__c();
+                if(soMap.get(ordermap.get(GeData.OrderCode).Id) != null)
+                {
+                    deliv.Id = soMap.get(ordermap.get(GeData.OrderCode).Id).Id;
+                }
+                if(String.isNotBlank(GeData.DeliveryDate))
+                {
+                    deliv.SONO__c = GeData.SoNo + GeData.DeliveryDate;
+                }else
+                {
+                    deliv.SONO__c = GeData.SoNo;
+                }
+                if(String.isBlank(deliv.Id)){
+                    deliv.SSBD_Contract__c            = ordermap.get(GeData.OrderCode).Id;
+                }
+                List<string> Datesplit = GeData.SoDate.split(',');
+                deliv.Delivery_Status__c             = GeData.SoShippingStatus ;
+                deliv.Delivery_Date__c         = NFMUtil.parseStr2Date(GeData.DeliveryDate, true);
+                deliv.SAP_CreatDate__c   = NFMUtil.parseStr2Date(Datesplit[0], true);
+                System.debug('idis' + ordermap.get(GeData.OrderCode).Id);
+                System.debug('dateis' + ordermap.get(GeData.OrderCode).DeliveryDate__c);
+                soUpdateMap.put(deliv.SONO__c, deliv);
+               
+                if(String.isNotBlank(GeData.SoNo)){
+                    if((NFMUtil.parseStr2Date(GeData.DeliveryDate, true) > ordermap.get(GeData.OrderCode).DeliveryDate__c) || (ordermap.get(GeData.OrderCode).DeliveryDate__c == null)
+                    || (NFMUtil.parseStr2Date(Datesplit[1], true) <> ordermap.get(GeData.OrderCode).ShippedDate__c))
+                    {
+                        if(Datesplit[1] <> '00000000'){
+                        orders.add(new Order(id = ordermap.get(GeData.OrderCode).Id
+                               , SAP_Contract__c = GeData.SoNo , DeliveryDate__c = NFMUtil.parseStr2Date(GeData.DeliveryDate, true),
+                                OrderDate__c = NFMUtil.parseStr2Date(Datesplit[0], true), ShippedDate__c = NFMUtil.parseStr2Date(Datesplit[1], true)));
+                        }
+                        else if(Datesplit[1] == '00000000'){
+                        orders.add(new Order(id = ordermap.get(GeData.OrderCode).Id
+                               , SAP_Contract__c = GeData.SoNo , DeliveryDate__c = NFMUtil.parseStr2Date(GeData.DeliveryDate, true),
+                                OrderDate__c = NFMUtil.parseStr2Date(Datesplit[0], true)));
+                        }
+                    }
+                }
+            }
+            System.debug('ordersize' + orders.size());
+       
+            if (soUpdateMap.size() > 0) {
+                System.debug(soUpdateMap.values());
+                upsert soUpdateMap.values();
+            }
+            if(orders.size()>0)
+            {
+                update orders;
+            }
+//ToDo绗竴娆¤繘鏉ョ殑鏃跺�欐湁鍙兘娌℃湁DeliveryDate锛屽綋绗竴娆℃病鏈塂eliveryDate绗簩娆℃湁鐨勬儏鍐典細娣诲姞涓ゆ潯鍙戣揣璁板綍
+            logstr += '\nend';
+            rowData.retry_cnt__c=0;
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG010_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG010_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                 rowData.retry_cnt__c++;
+                 LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG010WebService.cls-meta.xml b/scr/classes/SBG010WebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG010WebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG010WebServiceTest.cls b/scr/classes/SBG010WebServiceTest.cls
new file mode 100644
index 0000000..2c63855
--- /dev/null
+++ b/scr/classes/SBG010WebServiceTest.cls
@@ -0,0 +1,174 @@
+@isTest
+private class SBG010WebServiceTest {
+    static String  setdata(){
+        Id pricebookId = Test.getStandardPricebookId();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            isActive = true
+        );
+        insert pricebook;
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        insert new Product2[] {product1,product2,product3};
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+
+         PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+
+
+        Date day1 = Date.today();
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Prospect Created';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'Sales_Channel_D__c';
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Trade_Type_D__c';
+        //opp.Machine_Parts__c = 'Machine_Parts_D__c';
+        //opp.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress_D__c';
+        //opp.ForeignTradeCompany__c = 'ForeignTradeCompany_D__c';
+        insert opp;
+        OpportunityLineItem oli = new OpportunityLineItem();
+        oli.OpportunityId = opp.Id;
+        oli.Quantity = 2;
+        oli.UnitPrice = 111;
+        oli.Description = 'test';
+        oli.PricebookEntryId = entry1.Id;
+        insert oli;
+        List<RecordType> rectOrder = [select id from RecordType where IsActive = true and SobjectType = 'Order'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = '01228000000NJt6'
+        );
+        insert odr;
+
+        Delivery__c de1 = new Delivery__c();
+        de1.SSBD_Contract__c = odr.Id;
+
+        insert de1;
+        Order ordd = [Select OrderNumber,Id,Name From Order];
+      return ordd.OrderNumber;
+
+    }
+    @isTest static void test_method_one() {
+        String ocode = setdata();
+        SBG010WebService.GeData GeData = new SBG010WebService.GeData();
+        GeData.OrderCode = ocode;
+        SBG010WebService.GeDatas datas = new SBG010WebService.GeDatas();
+        datas.GeData = new List<SBG010WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG010WebService.SBG010(datas);
+    }
+
+    @isTest static void test_method_two() {
+        String ocode = setdata();
+        System.debug(ocode);
+        SBG010WebService.GeData GeData = new SBG010WebService.GeData();
+        GeData.OrderCode = ocode;
+        GeData.SoNo = '123';
+        GeData.SoShippingStatus = '123';
+        SBG010WebService.GeDatas datas = new SBG010WebService.GeDatas();
+        datas.GeData = new List<SBG010WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG010WebService.SBG010(datas);
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG010WebServiceTest.cls-meta.xml b/scr/classes/SBG010WebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG010WebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG017Rest.cls b/scr/classes/SBG017Rest.cls
new file mode 100644
index 0000000..074401b
--- /dev/null
+++ b/scr/classes/SBG017Rest.cls
@@ -0,0 +1,157 @@
+@RestResource(urlMapping='/SBG017/*')
+global with sharing class SBG017Rest  {
+
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public SBG017Rest.GeData[] GeData;
+    }
+    global class GeData {
+        public String  OpportunityCode;
+        public String  SAPQuotationCode;
+        public String  StockAnswer;
+        public String  Other1;
+        public String  Other2;
+        public String  Other3;
+    }
+    
+    @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG017', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG017';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> achievementList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (achievementList == null || achievementList.size() == 0) {
+            return;
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+            List<String> oppNoList = new List<String>();
+            for (GeData GeData : achievementList) {
+                if (GeData.OpportunityCode == null || GeData.OpportunityCode == '' ||
+                    GeData.SAPQuotationCode == null || GeData.SAPQuotationCode == '' ||
+                    GeData.StockAnswer == null || GeData.StockAnswer == ''
+                ) {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    continue;
+                }
+                oppNoList.add(GeData.OpportunityCode);
+            }
+            List<Opportunity> oppList = [select Id, SAP_QuotationCode__c,InquiryNumber__c,Stock_Answer__c
+                                           from Opportunity
+                                          where InquiryNumber__c in :oppNoList];
+            Map<String, Opportunity> oppsMap = new Map<String, Opportunity>();
+            for (Opportunity opp : oppList) {
+                oppsMap.put(opp.InquiryNumber__c, opp);
+            }
+
+            // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+            Map<Id, Opportunity> oppUpdateMap = new Map<Id, Opportunity>();
+            for (GeData GeData : achievementList) {
+                if (GeData.OpportunityCode == null || GeData.OpportunityCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'OpportunityCode is required\n';
+                    continue;
+                }
+                if (GeData.SAPQuotationCode == null || GeData.SAPQuotationCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'SAPQuotationCode is required\n';
+                    continue;
+                }
+                if (GeData.StockAnswer == null || GeData.StockAnswer == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'StockAnswer is required\n';
+                    continue;
+                }
+                Opportunity opp = oppsMap.get(GeData.OpportunityCode);
+                if (opp == null) {
+                    // 鏇存柊瀵捐薄鍟嗚珖銇屻仾銇勫牬鍚�
+                    iflog.ErrorLog__c += '[' + GeData.OpportunityCode + ']Opportunity[' + GeData.SAPQuotationCode + ']NotExist\n';
+                    continue;
+                }
+                // 闋呯洰銈汇儍銉�
+                //opp.InquiryNumber__c = GeData.OpportunityCode;
+                opp.SAP_QuotationCode__c = GeData.SAPQuotationCode;
+                opp.Stock_Answer__c            = GeData.StockAnswer;
+
+                oppUpdateMap.put(opp.Id, opp);
+            }
+            if (oppUpdateMap.size() > 0) {
+                update oppUpdateMap.values();
+            }
+            logstr += '\nend';
+            rowData.retry_cnt__c=0;
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG017_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG017_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                 rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG017Rest.cls-meta.xml b/scr/classes/SBG017Rest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SBG017Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG017RestTest.cls b/scr/classes/SBG017RestTest.cls
new file mode 100644
index 0000000..69f0d82
--- /dev/null
+++ b/scr/classes/SBG017RestTest.cls
@@ -0,0 +1,247 @@
+@isTest
+private class SBG017RestTest {
+	 static String  setdata(){
+        Id pricebookId = Test.getStandardPricebookId();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            isActive = true
+        );
+        insert pricebook;
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        insert new Product2[] {product1,product2,product3};
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        Date day1 = Date.today();
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Prospect Created';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'Sales_Channel_D__c';
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Trade_Type_D__c';
+        //opp.Machine_Parts__c = 'Machine_Parts_D__c';
+        //opp.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress_D__c';
+        //opp.ForeignTradeCompany__c = 'ForeignTradeCompany_D__c';
+        insert opp;
+        OpportunityLineItem oli = new OpportunityLineItem();
+        oli.OpportunityId = opp.Id;
+        oli.Quantity = 2;
+        oli.UnitPrice = 111;
+        oli.Description = 'test';
+        oli.PricebookEntryId = entry1.Id;
+        insert oli;
+        List<RecordType> rectOrder = [select id from RecordType where IsActive = true and SobjectType = 'Order'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = '01228000000NJt6'
+        );
+        insert odr;
+        Delivery__c de1 = new Delivery__c();
+        de1.SSBD_Contract__c = odr.Id;
+        insert de1;
+        Opportunity ordd = [Select InquiryNumber__c,Id,Name From Opportunity];
+        return ordd.InquiryNumber__c;
+    }
+
+
+    @isTest static void test_method_1() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017Rest.GeData GeData = new SBG017Rest.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = SAP;
+        GeData.StockAnswer = '123';
+        SBG017Rest.GeDatas datas = new SBG017Rest.GeDatas();
+        datas.GeData = new List<SBG017Rest.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        BatchIF_Log__c rowData =  NFMUtil.saveRowData(datas.Monitoring, 'SBG017', datas.GeData);
+        SBG017Rest.executefuture(rowData.Id);
+        
+    }
+
+    @isTest static void test_method_2() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017Rest.GeData GeData = new SBG017Rest.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = '';
+        GeData.StockAnswer = '123';
+        SBG017Rest.GeDatas datas = new SBG017Rest.GeDatas();
+        datas.GeData = new List<SBG017Rest.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        BatchIF_Log__c rowData =  NFMUtil.saveRowData(datas.Monitoring, 'SBG017', datas.GeData);
+        SBG017Rest.executefuture(rowData.Id);
+    }
+
+    @isTest static void test_method_3() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017Rest.GeData GeData = new SBG017Rest.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = SAP;
+        GeData.StockAnswer = '';
+        SBG017Rest.GeDatas datas = new SBG017Rest.GeDatas();
+        datas.GeData = new List<SBG017Rest.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        BatchIF_Log__c rowData =  NFMUtil.saveRowData(datas.Monitoring, 'SBG017', datas.GeData);
+        SBG017Rest.executefuture(rowData.Id);
+    }
+
+    @isTest static void test_method_4() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017Rest.GeData GeData = new SBG017Rest.GeData();
+        GeData.SAPQuotationCode = '';
+        GeData.OpportunityCode = SAP;
+        GeData.StockAnswer = '123';
+        SBG017Rest.GeDatas datas = new SBG017Rest.GeDatas();
+        datas.GeData = new List<SBG017Rest.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        BatchIF_Log__c rowData =  NFMUtil.saveRowData(datas.Monitoring, 'SBG017', datas.GeData);
+        SBG017Rest.executefuture(rowData.Id);
+    }
+
+
+    @isTest static void test_method_5() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017Rest.GeData GeData = new SBG017Rest.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = '123';
+        GeData.StockAnswer = '123';
+        SBG017Rest.GeDatas datas = new SBG017Rest.GeDatas();
+        datas.GeData = new List<SBG017Rest.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        BatchIF_Log__c rowData =  NFMUtil.saveRowData(datas.Monitoring, 'SBG017', datas.GeData);
+        SBG017Rest.executefuture(rowData.Id);
+    }
+
+    @isTest static void test_method_Seven() {
+
+    Test.startTest();
+    
+    RestRequest req = new RestRequest();
+    RestResponse res = new RestResponse();
+
+    String JsonMsg = ' { "GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG017", "MessageGroupNumber": 331591, "NumberOfRecord": 1, "TransmissionDateTime": 201903251115 },"GeData": [{ "StockAnswer": "OK111","SAPQuotationCode": "20022780  ", "Other3": "", "Other2": "", "Other1": "",  "OpportunityCode": "O-2018-067607"}]}}';
+    req.requestURI = 'services/apexrest/SBG017/execute';
+    req.httpMethod = 'POST';
+    req.requestBody = Blob.valueof(JsonMsg);
+    RestContext.request = req;
+    RestContext.response= res;
+
+    SBG017Rest.execute();
+
+    Test.stopTest();
+
+   // { "GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG017", "MessageGroupNumber": 331591, "NumberOfRecord": 1, "TransmissionDateTime": 201903251115 },"GeData": [{ "StockAnswer": "OK111","SAPQuotationCode": "20022780  ", "Other3": "", "Other2": "", "Other1": "",  "OpportunityCode": "O-2018-067607"}]}}
+
+    //Test.setMock(HttpCalloutMock.class, new NFM205RestCalloutMock());
+    //NFM205Rest.execute1('{"Monitoring":{"TransmissionDateTime":"201812201320","Text":"","Tag":"MSGH","Sender":"SFDC","Receiver":"SPO","NumberOfRecord":"1","MessageType":"NFM205","MessageGroupNumber":"20180001722190"},"GeData":[{"Opportunity_Code":"HKBJ-GI-BJ0588881","Bidding_No":"as123121","Bidding_Content":"鎷涙爣鍐呭","Bid_Project_Name":"鎷涙爣椤圭洰鍚�","Bid_Date":"20181203","Authorized_Status":"1","Authorized_Finish_Sales":"30033","Authorized_DB_No":"MGZWESQHN201812001","Authorized_Date":"20190316","Autholization_Activated_Date":"20190415"}]}');
+}
+
+	
+}
\ No newline at end of file
diff --git a/scr/classes/SBG017RestTest.cls-meta.xml b/scr/classes/SBG017RestTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SBG017RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG017WebService.cls b/scr/classes/SBG017WebService.cls
new file mode 100644
index 0000000..6097c6e
--- /dev/null
+++ b/scr/classes/SBG017WebService.cls
@@ -0,0 +1,127 @@
+global class SBG017WebService {
+
+    global class GeDatas {
+        webservice NFMUtil.Monitoring Monitoring;
+        webservice SBG017WebService.GeData[] GeData;
+    }
+    global class GeData {
+        webservice String  OpportunityCode;
+        webservice String  SAPQuotationCode;
+        webservice String  StockAnswer;
+        webservice String  Other1;
+        webservice String  Other2;
+        webservice String  Other3;
+    }
+    webservice static void SBG017(GeDatas geDatas) {
+    	if (geDatas == null) {
+            return;
+        }
+        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG017', GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) execute(rowData.Id);
+    }
+
+    global static void execute(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG017';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> achievementList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (achievementList == null || achievementList.size() == 0) {
+            return;
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+            List<String> oppNoList = new List<String>();
+            for (SBG017WebService.GeData GeData : achievementList) {
+                if (GeData.OpportunityCode == null || GeData.OpportunityCode == '' ||
+                    GeData.SAPQuotationCode == null || GeData.SAPQuotationCode == '' ||
+                    GeData.StockAnswer == null || GeData.StockAnswer == ''
+                ) {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    continue;
+                }
+                oppNoList.add(GeData.OpportunityCode);
+            }
+            List<Opportunity> oppList = [select Id, SAP_QuotationCode__c,InquiryNumber__c,Stock_Answer__c
+                                           from Opportunity
+                                          where InquiryNumber__c in :oppNoList];
+            Map<String, Opportunity> oppsMap = new Map<String, Opportunity>();
+            for (Opportunity opp : oppList) {
+                oppsMap.put(opp.InquiryNumber__c, opp);
+            }
+
+            // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+            Map<Id, Opportunity> oppUpdateMap = new Map<Id, Opportunity>();
+            for (SBG017WebService.GeData GeData : achievementList) {
+                if (GeData.OpportunityCode == null || GeData.OpportunityCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'OpportunityCode is required\n';
+                    continue;
+                }
+                if (GeData.SAPQuotationCode == null || GeData.SAPQuotationCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'SAPQuotationCode is required\n';
+                    continue;
+                }
+                if (GeData.StockAnswer == null || GeData.StockAnswer == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'StockAnswer is required\n';
+                    continue;
+                }
+                Opportunity opp = oppsMap.get(GeData.OpportunityCode);
+                if (opp == null) {
+                    // 鏇存柊瀵捐薄鍟嗚珖銇屻仾銇勫牬鍚�
+                    iflog.ErrorLog__c += '[' + GeData.OpportunityCode + ']Opportunity[' + GeData.SAPQuotationCode + ']NotExist\n';
+                    continue;
+                }
+                // 闋呯洰銈汇儍銉�
+                //opp.InquiryNumber__c = GeData.OpportunityCode;
+                opp.SAP_QuotationCode__c = GeData.SAPQuotationCode;
+                opp.Stock_Answer__c            = GeData.StockAnswer;
+
+                oppUpdateMap.put(opp.Id, opp);
+            }
+            if (oppUpdateMap.size() > 0) {
+                update oppUpdateMap.values();
+            }
+            logstr += '\nend';
+            rowData.retry_cnt__c=0;
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG017_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG017_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                 rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG017WebService.cls-meta.xml b/scr/classes/SBG017WebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG017WebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG017WebServiceTest.cls b/scr/classes/SBG017WebServiceTest.cls
new file mode 100644
index 0000000..a774f3a
--- /dev/null
+++ b/scr/classes/SBG017WebServiceTest.cls
@@ -0,0 +1,216 @@
+@isTest
+private class SBG017WebServiceTest {
+    static String  setdata(){
+        Id pricebookId = Test.getStandardPricebookId();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            isActive = true
+        );
+        insert pricebook;
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        insert new Product2[] {product1,product2,product3};
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+        Date day1 = Date.today();
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Prospect Created';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'Sales_Channel_D__c';
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Trade_Type_D__c';
+        //opp.Machine_Parts__c = 'Machine_Parts_D__c';
+        //opp.SpecialDeliveryAddress__c = 'SpecialDeliveryAddress_D__c';
+        //opp.ForeignTradeCompany__c = 'ForeignTradeCompany_D__c';
+        insert opp;
+        OpportunityLineItem oli = new OpportunityLineItem();
+        oli.OpportunityId = opp.Id;
+        oli.Quantity = 2;
+        oli.UnitPrice = 111;
+        oli.Description = 'test';
+        oli.PricebookEntryId = entry1.Id;
+        insert oli;
+        List<RecordType> rectOrder = [select id from RecordType where IsActive = true and SobjectType = 'Order'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = '01228000000NJt6'
+        );
+        insert odr;
+        Delivery__c de1 = new Delivery__c();
+        de1.SSBD_Contract__c = odr.Id;
+        insert de1;
+        Opportunity ordd = [Select InquiryNumber__c,Id,Name From Opportunity];
+        return ordd.InquiryNumber__c;
+    }
+
+
+    @isTest static void test_method_1() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017WebService.GeData GeData = new SBG017WebService.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = SAP;
+        GeData.StockAnswer = '123';
+        SBG017WebService.GeDatas datas = new SBG017WebService.GeDatas();
+        datas.GeData = new List<SBG017WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG017WebService.SBG017(datas);
+    }
+
+    @isTest static void test_method_2() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017WebService.GeData GeData = new SBG017WebService.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = '';
+        GeData.StockAnswer = '123';
+        SBG017WebService.GeDatas datas = new SBG017WebService.GeDatas();
+        datas.GeData = new List<SBG017WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG017WebService.SBG017(datas);
+    }
+
+    @isTest static void test_method_3() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017WebService.GeData GeData = new SBG017WebService.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = SAP;
+        GeData.StockAnswer = '';
+        SBG017WebService.GeDatas datas = new SBG017WebService.GeDatas();
+        datas.GeData = new List<SBG017WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG017WebService.SBG017(datas);
+    }
+
+    @isTest static void test_method_4() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017WebService.GeData GeData = new SBG017WebService.GeData();
+        GeData.SAPQuotationCode = '';
+        GeData.OpportunityCode = SAP;
+        GeData.StockAnswer = '123';
+        SBG017WebService.GeDatas datas = new SBG017WebService.GeDatas();
+        datas.GeData = new List<SBG017WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG017WebService.SBG017(datas);
+    }
+
+
+    @isTest static void test_method_5() {
+        String SAP = setdata();
+        System.debug(SAP);
+        SBG017WebService.GeData GeData = new SBG017WebService.GeData();
+        GeData.SAPQuotationCode = '123';
+        GeData.OpportunityCode = '123';
+        GeData.StockAnswer = '123';
+        SBG017WebService.GeDatas datas = new SBG017WebService.GeDatas();
+        datas.GeData = new List<SBG017WebService.GeData>();
+        datas.GeData.add(GeData);
+        datas.Monitoring = new NFMUtil.Monitoring();
+        SBG017WebService.SBG017(datas);
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG017WebServiceTest.cls-meta.xml b/scr/classes/SBG017WebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBG017WebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG018Rest.cls b/scr/classes/SBG018Rest.cls
new file mode 100644
index 0000000..e08608c
--- /dev/null
+++ b/scr/classes/SBG018Rest.cls
@@ -0,0 +1,314 @@
+/**********************************************************************
+ 浜у搧 棣栬惀鐘舵�乑5
+ 淇敼浜哃ogAutoSendBatch
+ 鏂板锛氫骇鍝佸簱瀛樺璞�
+ 缁� OT-GPI绠�妗f潈闄�
+*************************************************************************/
+@RestResource(urlMapping = '/SBG018/*')
+global with sharing class SBG018Rest {
+
+    public transient static String globaltransforDate;
+
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData[] GeData;
+    }
+
+    global class GeData {
+
+        public GeDataDetails[] GeDataDetails;
+
+        public String Status; //棣栬惀鐘舵��
+        public String TransforDate; //浼犺緭鏃ユ湡
+    }
+
+    global class GeDataDetails {
+
+        public String ProductCode;//鐗╂枡
+        public String Plant;//宸ュ巶
+        public String Department;//鍒嗛噹
+        public String FGSP;//鏁存満/闆朵欢(FG=鏁存満锛孲P=闆朵欢)
+        public String Qty;//鍙垎閰嶅簱瀛樻暟閲�
+        public String TradeType;//鍐�/澶栬锤(Tax Exemption=澶栬锤锛孴axation=鍐呰锤)
+
+    }
+
+    @HttpPost
+    global static void execute() {
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG018', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG018';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (geDataList == null || geDataList.size() == 0) {
+            return;
+        }
+
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            globaltransforDate = '';
+            // 绗﹀悎鐨勬槑缁�
+            Map<String, GeDataDetails> satisfyGeDataDetailMap = RequiredFieldValidator(geDataList, iflog);
+
+            if (satisfyGeDataDetailMap != null && satisfyGeDataDetailMap.size() > 0) {
+                upsertProductInventory(satisfyGeDataDetailMap, iflog);
+            }
+
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+
+
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG018_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG018_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+
+    }
+    // 淇濆瓨浜у搧搴撳瓨
+    public static void upsertProductInventory(Map<String, GeDataDetails> satisfyGeDataDetailMap, BatchIF_Log__c iflog) {
+
+        // 鑾峰彇浜у搧搴撳瓨 Start
+        Map<String, ProductInventory__c> productInventoryMap = new Map<String, ProductInventory__c>();
+        List<ProductInventory__c> getProductInventoryList = [SELECT Id, Name,TransforDate__c, ProductCode__c, Plant__c, ProductSegment__c, ProductType__c, InventoryQuantity__c, ManagementCode__c,InventoryCode__c,TradeType__c FROM ProductInventory__c WHERE InventoryCode__c IN :satisfyGeDataDetailMap.keySet()];
+        if (getProductInventoryList.size() > 0) {
+            for (ProductInventory__c productInventory : getProductInventoryList) {
+                productInventoryMap.put(productInventory.InventoryCode__c, productInventory);
+            }
+        }
+        // 鑾峰彇浜у搧搴撳瓨 End
+
+        // 鑾峰彇浜у搧 Start
+        List<String> productCodeList = new List<String>();
+        Map<String, Product2> productMap = new Map<String, Product2>();
+
+        for (String managementCode : satisfyGeDataDetailMap.keySet()) {
+            GeDataDetails geDataDetails = satisfyGeDataDetailMap.get(managementCode);
+            productCodeList.add(ZeroPadding(geDataDetails.ProductCode));
+        }
+
+        List<Product2> getProductList = [SELECT Id, Name, ProductCode FROM Product2 WHERE ProductCode IN:productCodeList ];
+
+        if (getProductList.size() > 0) {
+
+            for (Product2 product : getProductList) {
+                productMap.put(product.ProductCode, product);
+            }
+
+        }
+        // 鑾峰彇浜у搧 End
+
+        // 淇濆瓨 浜у搧搴撳瓨Start
+        List<ProductInventory__c> upsertProductInventoryList = new List<ProductInventory__c>();
+        for (String inventoryCode : satisfyGeDataDetailMap.keySet()) {
+            GeDataDetails geDataDetails = satisfyGeDataDetailMap.get(inventoryCode);
+            String  productCode = ZeroPadding(geDataDetails.ProductCode);
+            String productId = '';
+
+            if (productMap.containsKey(productCode)) {
+                productId = productMap.get(productCode).Id;
+            } else {
+                iflog.ErrorLog__c += 'productCode [ ' + productCode + ' ] is Nonexistent,This data is skipped.\n';
+                continue;
+            }
+            Date transforDate = NFMUtil.parseStr2Date(globaltransforDate, false);
+            Boolean continueFlag = false;
+            ProductInventory__c productInventory = new ProductInventory__c();
+            if (productInventoryMap.containsKey(inventoryCode)) {
+                productInventory = productInventoryMap.get(inventoryCode);
+                // 鑻ヤ紶杈撴棩鏈熷皬浜庣瓑浜庡綋鍓嶅簱瀛樻棩鏈燂紝鏁版嵁璺宠繃涓嶆墽琛�
+                if (transforDate < productInventory.TransforDate__c) {
+                    continueFlag = true;
+                } else if(transforDate == productInventory.TransforDate__c) {
+                    // 鎺ュ彛鏁版嵁澶т簬搴撳瓨鏁伴噺锛屾暟鎹烦杩�(闃叉涓�澶╀袱娆℃墽琛屾帴鍙c�佸绯荤粺鏁版嵁鐨勮鐩�)
+                    if ( Decimal.valueOf(geDataDetails.Qty) > productInventory.InventoryQuantity__c) {
+                        continueFlag = true;
+                    }
+                }
+                
+            } else {
+                // 浜у搧搴撳瓨鐨刱ey(浜у搧缂栫爜_鍒嗛噹_鏁存満/闆朵欢_宸ュ巶_鍐�/澶栬锤)
+                productInventory.InventoryCode__c = inventoryCode;
+
+                String managementCode = ZeroPadding(geDataDetails.ProductCode) + '_' + geDataDetails.Department + '_' + geDataDetails.FGSP;
+                // 浜у搧搴撳瓨楠岃瘉鐨刱ey(浜у搧缂栫爜_鍒嗛噹_鏁存満/闆朵欢)
+                productInventory.ManagementCode__c = managementCode;
+                productInventory.Name = inventoryCode;
+            }
+            if (continueFlag) {
+                iflog.ErrorLog__c += '浜у搧搴撳瓨 [ ' + inventoryCode + ' ] not the latest data,This data is skipped.\n';
+                continue;
+            }
+            
+            productInventory.TransforDate__c = transforDate ;
+            productInventory.ProductCode__c = productId;
+            productInventory.Plant__c = geDataDetails.Plant ;
+            productInventory.ProductSegment__c = geDataDetails.Department ;
+            productInventory.ProductType__c = geDataDetails.FGSP ;
+            productInventory.InventoryQuantity__c = Decimal.valueOf(geDataDetails.Qty);
+            productInventory.TradeType__c = geDataDetails.TradeType;
+
+            upsertProductInventoryList.add(productInventory);
+        }
+
+        if (upsertProductInventoryList.size() > 0) {
+            upsert upsertProductInventoryList;
+        }
+        // 淇濆瓨 浜у搧搴撳瓨End
+    }
+
+    // 瀛楁楠岃瘉
+    public static Map<String, GeDataDetails> RequiredFieldValidator(List<GeData> geDataList, BatchIF_Log__c iflog) {
+        Map<String, GeDataDetails> result = new Map<String, GeDataDetails>();
+        for (GeData gda : geDataList) {
+            // 浼犺緭鏃ユ湡
+            if (String.isBlank(gda.TransforDate)) {
+                iflog.ErrorLog__c += 'TransforDate is required,This data is skipped.\n';
+                continue;
+            }
+            globaltransforDate =  gda.TransforDate;
+
+            for (GeDataDetails  geDataDetail : gda.GeDataDetails) {
+                // 浜у搧OTCode
+                if (String.isBlank(geDataDetail.ProductCode)) {
+                    iflog.ErrorLog__c += 'ProductCode is required,This data is skipped.\n';
+                    continue;
+                }
+                // 鍒嗛噹
+                if (String.isBlank(geDataDetail.Department)) {
+                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductCode + ' ] of Department is required,This data is skipped.\n';
+                    continue;
+                }
+                // 宸ュ巶
+                if (String.isBlank(geDataDetail.Plant)) {
+                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductCode + ' ] of Plant is required,This data is skipped.\n';
+                    continue;
+                }
+                // 鏁存満/闆朵欢
+                if (String.isBlank(geDataDetail.FGSP)) {
+                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductCode + ' ] of FGSP is required,This data is skipped.\n';
+                    continue;
+                }
+                // 鍐�/澶栬锤
+                if (String.isBlank(geDataDetail.TradeType)) {
+                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductCode + ' ] of TradeType is required,This data is skipped.\n';
+                    continue;
+                }
+
+                if ('Tax Exemption'.equals(geDataDetail.TradeType)) {
+                    iflog.Log2__c += 'Tax Exemption, [ ProductCode:' + geDataDetail.ProductCode +',宸ュ巶锛�'+geDataDetail.Plant+',鍒嗛噹锛�'+geDataDetail.Department+', 鏁伴噺:'+geDataDetail.Qty+ ' ].\n';     
+                }
+
+                // 搴撳瓨鏁伴噺
+                Boolean isContinue = false;
+                if (String.isBlank(geDataDetail.Qty)) {
+                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductCode + ' ] of Qty is required,This data is skipped.\n';
+                    continue;
+                } else {
+                    
+                    Pattern pattern = Pattern.compile('^[0-9]\\d{0,13}(\\.\\d{0,4})?$');
+                    Matcher isNum = pattern.matcher(geDataDetail.Qty);
+                    if (!isNum.matches()) {
+                        //鍐�/澶栬锤(Tax Exemption=澶栬锤锛孴axation=鍐呰锤)
+                        if ('Tax Exemption'.equals(geDataDetail.TradeType)) {
+                            // 澶栬锤搴撳瓨鍑虹幇璐熸暟锛岄粯璁ゅ瓨涓�0搴撳瓨
+                            geDataDetail.Qty = '0.000';    
+                        } else if ('Taxation'.equals(geDataDetail.TradeType)) {
+                            // 鎶ラ敊骞跺彂閫侀偖浠堕�氱煡缁欑郴缁熺鐞嗗憳
+                            iflog.ErrorLog__c += '[ ProductCode:' + geDataDetail.ProductCode +',宸ュ巶锛�'+geDataDetail.Plant+',鍒嗛噹锛�'+geDataDetail.Department+', 鏁伴噺:'+geDataDetail.Qty+ ' ] has to be a Nonnegative number,This data is skipped.\n';
+                            isContinue = true;
+                        }
+                        
+                    }
+                }
+                if (isContinue) {
+                    continue;    
+                }
+                // 浜у搧缂栫爜_鍒嗛噹_鏁存満/闆朵欢_宸ュ巶_鍐�/澶栬锤
+                String inventoryCode = ZeroPadding(geDataDetail.ProductCode) + '_' + geDataDetail.Department + '_' + geDataDetail.FGSP + '_'+geDataDetail.Plant + '_'+geDataDetail.TradeType;
+                result.put(inventoryCode, geDataDetail);
+
+            }
+        }
+
+        return result;
+    }
+    // 绾暟瀛椾骇鍝佺紪鐮佽繘琛岃ˉ闆�
+    public static String ZeroPadding(String productCode) {
+        Pattern pattern = Pattern.compile('^[0-9]*$');
+        Matcher isNum = pattern.matcher(productCode);
+        if (isNum.matches()) {
+            productCode = productCode.leftPad(18, '0');
+        }
+
+        return productCode;
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG018Rest.cls-meta.xml b/scr/classes/SBG018Rest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG018Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG018RestTest.cls b/scr/classes/SBG018RestTest.cls
new file mode 100644
index 0000000..8aadb51
--- /dev/null
+++ b/scr/classes/SBG018RestTest.cls
@@ -0,0 +1,175 @@
+@isTest
+private class SBG018RestTest {
+
+    public static ProductInventory__c productInventory;
+    public static void init() {
+        Product2 prd1 = testSBG018Init();
+        productInventory = new ProductInventory__c();
+        productInventory.TransforDate__c = Date.today() ;
+        productInventory.ProductCode__c = prd1.Id;
+        productInventory.Plant__c = 'CCTV' ;
+        productInventory.ProductSegment__c = 'LS' ;
+        productInventory.ProductType__c = 'SP';
+        productInventory.InventoryQuantity__c = 22;
+        productInventory.TradeType__c = 'Taxation';
+        productInventory.ManagementCode__c = prd1.ProductCode +'_LS_SP';
+        productInventory.InventoryCode__c =prd1.ProductCode +'_LS_SP_CCTV_Taxation';
+
+        insert productInventory;
+
+    }
+    static Product2 testSBG018Init() {
+
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG018';
+        prd.ProductCode            = 'testSBG018';
+        prd.Name                   = 'testSBG018';
+        prd.IsActive               = true;
+        insert prd;
+        Pricebook2 prdbook1 = new Pricebook2(
+            Name = 'testSBG018',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2(
+            Name = 'testSBG018',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+        return prd;
+
+    }
+    // 娴嬭瘯涓氬姟閫昏緫
+    @isTest static void testSBG018_void() {
+
+        init();
+
+        SBG018Rest.GeData GeData = new SBG018Rest.GeData();
+        SBG018Rest.GeDatas GeDatas = new SBG018Rest.GeDatas();
+        GeDatas.GeData = new SBG018Rest.GeData[] { GeData };
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        SBG018Rest.GeDataDetails GeDataDetail01 = new  SBG018Rest.GeDataDetails();
+        SBG018Rest.GeDataDetails GeDataDetail02 = new  SBG018Rest.GeDataDetails();
+        GeData.GeDataDetails = new  SBG018Rest.GeDataDetails[] {GeDataDetail01, GeDataDetail02};
+        GeData.Status = 'Z5';
+        GeData.TransforDate = String.valueOf(Date.today());//'20210113';
+        GeDataDetail01.ProductCode = 'testSBG018';
+        GeDataDetail01.Plant = 'CCTV';
+        GeDataDetail01.Department = 'LS';
+        GeDataDetail01.FGSP = 'SP';
+        GeDataDetail01.Qty = '11';
+        GeDataDetail01.TradeType = 'Taxation';
+        GeDataDetail02.ProductCode = 'testSBG018';
+        // 鐢ㄤ簬瑙﹀彂寮傚父 杩涘叆Catch
+        GeDataDetail02.Plant = 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.Plant += 'CCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTVCCTV';
+        GeDataDetail02.TradeType = 'Taxation';
+
+        GeDataDetail02.Department = 'LS';
+        GeDataDetail02.FGSP = 'FG';
+        GeDataDetail02.Qty = '11';
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG018', GeDatas.GeData);
+        SBG018Rest.main(rowData.Id);
+
+        System.Test.stopTest();
+
+    }
+
+
+    @isTest static void testSBG018_void2() {
+
+        init();
+
+        SBG018Rest.GeData GeData = new SBG018Rest.GeData();
+        SBG018Rest.GeDatas GeDatas = new SBG018Rest.GeDatas();
+        GeDatas.GeData = new SBG018Rest.GeData[] { GeData };
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        SBG018Rest.GeDataDetails GeDataDetail01 = new  SBG018Rest.GeDataDetails();
+        SBG018Rest.GeDataDetails GeDataDetail02 = new  SBG018Rest.GeDataDetails();
+        GeData.GeDataDetails = new  SBG018Rest.GeDataDetails[] {GeDataDetail01, GeDataDetail02};
+        GeData.Status = 'Z5';
+        GeData.TransforDate = String.valueOf(Date.today());//'20210113';
+        GeDataDetail01.ProductCode = 'testSBG018';
+        GeDataDetail01.Plant = 'CCTV';
+        GeDataDetail01.Department = 'LS';
+        GeDataDetail01.FGSP = 'SP';
+        GeDataDetail01.Qty = '11';
+        GeDataDetail01.TradeType = 'Taxation';
+        GeDataDetail02.ProductCode = 'testSBG018';
+        // 鐢ㄤ簬瑙﹀彂寮傚父 杩涘叆Catch
+        GeDataDetail02.Plant = 'CC31';
+
+        GeDataDetail02.Department = 'LS';
+        GeDataDetail02.FGSP = 'FG';
+        GeDataDetail02.Qty = '11';
+        GeDataDetail02.TradeType = 'Taxation';
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBG018', GeDatas.GeData);
+        SBG018Rest.main(rowData.Id);
+
+        System.Test.stopTest();
+
+    }
+    // 娴嬭瘯SBG018Rest execute閮ㄥ垎 浠ュ強蹇呭~瀛楁鐨勯獙璇佽鐩�
+    @isTest static void test_execute() {
+        testSBG018Init();
+        Test.startTest();
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+
+        String JsonMsg = '{"GeDatas":{"Monitoring":{"Tag":"MSGH","Sender":1330,"Receiver":1592,"MessageType":"SBG018","MessageGroupNumber":570968,"NumberOfRecord":18,"TransmissionDateTime":202101131323},"GeData":[{"Status":"Z5","TransforDate":20210203,"GeDataDetails":[{"ProductCode":"","Plant":"CC20","Department":"IE","FGSP":"FG","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000001100500","Plant":"CC40","Department":"","FGSP":"FG","Qty":"0.000"},{"ProductCode":"000000000001100500","Plant":"","Department":"IE","FGSP":"SP","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC19","Department":"LS","FGSP":"","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC20","Department":"IE","FGSP":"FG","Qty":"1.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC40","Department":"IE","FGSP":"FG","Qty":"","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC41","Department":"LS","FGSP":"FG","Qty":"Test","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC42","Department":"IE","FGSP":"SP","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC46","Department":"LS","FGSP":"SP","Qty":"6.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003914083","Plant":"CC54","Department":"LS","FGSP":"FG","Qty":"11.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003980500","Plant":"CC19","Department":"LS","FGSP":"FG","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003980500","Plant":"CC20","Department":"IE","FGSP":"FG","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003980500","Plant":"CC40","Department":"IE","FGSP":"FG","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003980500","Plant":"CC41","Department":"LS","FGSP":"FG","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003980500","Plant":"CC42","Department":"IE","FGSP":"SP","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"000000000003980500","Plant":"CC54","Department":"LS","FGSP":"FG","Qty":"0.000","TradeType":"Tax Exemption"},{"ProductCode":"Q0500040","Plant":"CC22","Department":"NDT","FGSP":"FG","Qty":"0.000","TradeType":"Taxation"},{"ProductCode":"Q0500040","Plant":"CC45","Department":"NDT","FGSP":"FG","Qty":"0.000","TradeType":""}]}]}}';
+        req.requestURI = 'services/apexrest/SBG018/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response = res;
+
+        SBG018Rest.execute();
+
+        Test.stopTest();
+    }
+    // static testMethod void testMethod1() {
+
+    // }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG018RestTest.cls-meta.xml b/scr/classes/SBG018RestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG018RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG019Rest.cls b/scr/classes/SBG019Rest.cls
new file mode 100644
index 0000000..95b0e69
--- /dev/null
+++ b/scr/classes/SBG019Rest.cls
@@ -0,0 +1,211 @@
+/**********************************************************************
+ 
+*************************************************************************/
+@RestResource(urlMapping = '/SBG019/*')
+global with sharing class SBG019Rest {
+	global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+	global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData[] GeData;
+    }
+
+    global class GeData {
+    	public String TransforDate; //浼犺緭鏃ユ湡
+        public GeDataDetails[] GeDataDetails;
+
+        
+    }
+
+    global class GeDataDetails {
+
+        public String ProductCode;//鐗╂枡
+        public String ProductDate;//鐩戠浜у搧鏈�鏃╃敓浜ф棩鏈�
+
+    }
+
+
+
+
+    @HttpPost
+    global static void execute() {
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG019', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+    	Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG019';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (geDataList == null || geDataList.size() == 0) {
+            return;
+        }
+
+
+        Savepoint sp = Database.setSavepoint();
+        String result = '';
+        try {
+        	// 绗﹀悎鐨勬槑缁�
+            Map<String, GeDataDetails> satisfyGeDataDetailMap = RequiredFieldValidator(geDataList, iflog);
+            if (satisfyGeDataDetailMap.size() > 0) {
+               result = updateProduct(satisfyGeDataDetailMap,iflog);
+            }
+            logstr += result;
+            logstr += '\n End';
+            rowData.retry_cnt__c = 0;
+            if(Test.isRunningTest()){
+                Integer num = Integer.valueOf('TestError');
+            }
+        }catch (Exception ex) {
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG019_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG019_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        iflog.Log__c = logstr;
+        upsert iflog;
+        upsert rowData;
+    }
+    /**
+     * 蹇呭~瀛楁鐨勯獙璇�
+     * @Author   XHL
+     * @DateTime 2021-07-22
+     * @param    geDataList [鎺ュ彛浼犺緭鏁版嵁]
+     * @param    iflog      [BatchLog鏃ュ織]
+     * @return              [绗﹀悎鐨勬暟鎹甝
+     */
+    public static Map<String, GeDataDetails> RequiredFieldValidator(List<GeData> geDataList, BatchIF_Log__c iflog) {
+        Map<String, GeDataDetails> result = new Map<String, GeDataDetails>();
+        for (GeData gda : geDataList) {
+            // 浼犺緭鏃ユ湡
+            if (String.isNotBlank(gda.TransforDate)) {
+                
+            }
+
+            for (GeDataDetails  geDataDetail : gda.GeDataDetails) {
+            	//浜у搧缂栫爜
+            	if (String.isBlank(geDataDetail.ProductCode)) {
+                    iflog.ErrorLog__c += 'ProductCode is required,This data is skipped.\n';
+                    continue;
+                }
+                //鐩戠浜у搧鏈�鏃╃敓浜ф棩鏈�
+                if (String.isBlank(geDataDetail.ProductDate)) {
+                    iflog.ErrorLog__c += 'ProductCode[ ' + geDataDetail.ProductDate + ' ] of ProductDate is required,This data is skipped.\n';
+                    continue;
+                }
+                String productCode = ZeroPadding(geDataDetail.ProductCode);
+                result.put(productCode,geDataDetail);
+            }
+        }
+
+        return result;
+    }
+
+    // 淇濆瓨浜у搧
+    public static String updateProduct(Map<String, GeDataDetails> satisfyGeDataDetailMap, BatchIF_Log__c iflog) {
+        String result = '';
+    	//鏍规嵁浜у搧Code鏌ヨ浜у搧淇℃伅
+    	List<Product2> getProductList = 
+    				[SELECT Id, Name, ProductCode,demoteer_Sap__c 
+    				FROM Product2 
+    				WHERE ProductCode 
+    				IN:satisfyGeDataDetailMap.keyset() 
+    				];
+    	Map<String, Product2> productMap = new Map<String, Product2>();
+    	for(Product2 product:getProductList){
+    		productMap.put(product.ProductCode, product);
+    	}
+
+        Integer nonexisQuantity = 0;
+    	for (String ProductCode : satisfyGeDataDetailMap.keySet()) {
+			if (productMap.containsKey(productCode)) {
+				GeDataDetails geDataDetails = satisfyGeDataDetailMap.get(productCode);
+				Date demoteer_Sap = NFMUtil.parseStr2Date(geDataDetails.ProductDate, false);
+            	Product2  product = productMap.get(productCode);
+            	product.demoteer_Sap__c = demoteer_Sap;
+
+            	productMap.put(productCode,product);
+                result += 'productCode [ ' + productCode + ' ]\n';  
+            } else {
+                nonexisQuantity +=1;
+                iflog.ErrorLog__c += 'productCode [ ' + productCode + ' ] is Nonexistent,This data is skipped.\n';
+                continue;
+            }	
+    	}
+        Integer repeatTheNumber = satisfyGeDataDetailMap.size() - productMap.size() -nonexisQuantity;
+        result += '鍏变紶杈� ' + satisfyGeDataDetailMap.size() +'鏉℃暟鎹甛n';
+    	if (productMap.size() > 0) {
+    	    update productMap.values();
+            result += '鏇存柊鎴愬姛 ' + productMap.size() +'鏉℃暟鎹甛n';
+    	}
+        if (repeatTheNumber > 0) {
+            result += '閲嶅 ' + repeatTheNumber +'鏉℃暟鎹甛n';
+        }
+        if (nonexisQuantity >0) {
+            result += '浜у搧涓嶅瓨鍦� ' + nonexisQuantity +'鏉℃暟鎹甛n';
+        }
+
+
+        
+
+        return result;
+    }
+
+    // 绾暟瀛椾骇鍝佺紪鐮佽繘琛岃ˉ闆�
+    public static String ZeroPadding(String productCode) {
+        Pattern pattern = Pattern.compile('^[0-9]*$');
+        Matcher isNum = pattern.matcher(productCode);
+        if (isNum.matches()) {
+            productCode = productCode.leftPad(18, '0');
+        }
+
+        return productCode;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG019Rest.cls-meta.xml b/scr/classes/SBG019Rest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG019Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG019RestTest.cls b/scr/classes/SBG019RestTest.cls
new file mode 100644
index 0000000..3a22de5
--- /dev/null
+++ b/scr/classes/SBG019RestTest.cls
@@ -0,0 +1,94 @@
+@isTest
+private class SBG019RestTest {
+
+    @testSetup
+    static void testSBG019RestInit() {
+
+        Product2 prd = new Product2();
+        prd.Product_ECCode__c     = 'testSBG019';
+        prd.ProductCode            = 'testSBG019';
+        prd.Name                   = 'testSBG019';
+        prd.IsActive               = true;
+        insert prd;
+        Pricebook2 prdbook1 = new Pricebook2(
+            Name = 'testSBG019',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook1;
+        Pricebook2 prdbook2 = new Pricebook2(
+            Name = 'testSBG019',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook2;
+
+        Product2 prd3 = new Product2();
+        prd3.Product_ECCode__c     = 'testSBG01901';
+        prd3.ProductCode            = 'testSBG01901';
+        prd3.Name                   = 'testSBG01901';
+        prd3.IsActive               = true;
+        insert prd3;
+        Pricebook2 prdbook3 = new Pricebook2(
+            Name = 'testSBG01901',
+            ProductSegment__c  = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'dealer',
+            MachineParts__c = 'Machine',
+            isActive = true);
+
+        insert prdbook3;
+
+        PricebookEntry pbe3 = new PricebookEntry();
+        pbe3.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe3.Product2Id      = prd3.Id;
+        pbe3.UnitPrice       = 0;
+        pbe3.CurrencyIsoCode = 'CNY';
+        pbe3.IsActive        = true;
+        insert pbe3;
+
+
+        PricebookEntry pbe = new PricebookEntry();
+        pbe.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe.Product2Id      = prd.Id;
+        pbe.UnitPrice       = 0;
+        pbe.CurrencyIsoCode = 'CNY';
+        pbe.IsActive        = true;
+        insert pbe;
+        PricebookEntry pbe1 = new PricebookEntry();
+        pbe1.Pricebook2Id = ControllerUtil.getStandardPricebook().Id;
+        pbe1.Product2Id      = prd.Id;
+        pbe1.UnitPrice       = 0;
+        pbe1.CurrencyIsoCode = 'USD';
+        pbe1.IsActive        = true;
+        insert pbe1;
+
+    }
+
+    //娴嬭瘯SBG019Rest execute閮ㄥ垎 浠ュ強蹇呭~瀛楁鐨勯獙璇佽鐩�
+    @isTest static void test_execute() {
+        // testSBG019RestInit();
+        Test.startTest();
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+
+        //String JsonMsg = '{"GeDatas":{"Monitoring":{"Tag":"MSGH","Sender":1330,"Receiver":1592,"MessageType":"SBG019","MessageGroupNumber":570985,"NumberOfRecord":2,"TransmissionDateTime":202102021106},"GeData":[{"TransforDate":20210202,"GeDataDetails":[{"ProductCode":"000000000001100500","ProductDate":"20210202"},{"ProductCode":"","ProductDate":""}]}]}}';
+        String JsonMsg = '{"GeDatas":{"Monitoring":{"Tag":"MSGH","Sender":1330,"Receiver":1592,"MessageType":"SBG019","MessageGroupNumber":570985,"NumberOfRecord":2,"TransmissionDateTime":202102021106},"GeData":[{"TransforDate":20210202,"GeDataDetails":[{"ProductCode":"testSBG01901","ProductDate":"20210202"},{"ProductCode":"testSBG019","ProductDate":"20210202"},{"ProductCode":"","ProductDate":""},{"ProductCode":"testSBG019","ProductDate":""},{"ProductCode":"testSBG019","ProductDate":"20210202"},{"ProductCode":"123456","ProductDate":"20210202"}]}]}}';
+        req.requestURI = 'services/apexrest/SBG019/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response = res;
+
+        SBG019Rest.execute();
+
+        Test.stopTest();
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG019RestTest.cls-meta.xml b/scr/classes/SBG019RestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG019RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG027Controller.cls b/scr/classes/SBG027Controller.cls
new file mode 100644
index 0000000..8ca0d67
--- /dev/null
+++ b/scr/classes/SBG027Controller.cls
@@ -0,0 +1,411 @@
+public without sharing class SBG027Controller {
+    
+    public class SBG027 {
+        public GeDatas_element GeDatas;
+    }
+    
+    public class GeDatas_element {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData_element[] GeData;
+    }
+
+    public class GeData_element {
+        //CBPR
+        public String ZNMPA;
+        //CBPR
+        public String OpportunityCode;
+        public String OrderCode;
+        public String SalesAccountCode;
+        public String EndUser;
+        public String ProductSegment;
+        public String TradeType;
+        public String MachineParts;
+        public String SalesChannel;
+        public String DealerCode;
+        public String DealerSalesStaffName;
+        public String DeliveryDate;
+        public String PaymentCondition;
+        public String SpecialWarranty;
+        public Decimal OlympusContractPrices;
+        public Decimal Discount;
+        public Decimal OlympusPriceBeforeDiscount;
+        public Decimal ServiceFee;
+        public String ForeignTradeCompany;
+        public String SpecialDeliveryAddress;
+        public String PurposeOfAdvice;
+        public String Other1;
+        public String Other2;
+        public String Other3;
+        // 璺ㄥ尯鍩熼攢鍞� XHL 20210831 Start
+        public String CoopAgent;//鍚堜綔鍖哄煙浠g悊鍟咰ode
+        public String CoopAgentPCT;//涓氱哗鎷嗗垎姣斾緥(鍙�:鍚庤竟鐨勫��*10) 
+        // 璺ㄥ尯鍩熼攢鍞� XHL 20210831 End 
+        public GeDataDetails_element[] GeDataDetails;
+        
+    }
+
+    public class GeDataDetails_element {
+        public Integer DetailLine;
+        public String ItemCode;
+        public Integer ItemQuantity;
+        
+    }
+    /**
+     * SBG027銇�佷俊鍑︾悊
+     *
+     * @param iflog_Id           銉偘銉嗐兗銉栥儷銇甀d
+     * @param ordIds             閫佷俊瀵捐薄鍟嗚珖(璜栫悊涓�1浠躲伄銇裤仹銇�)
+     * @param C1:Delete 2:Add(Insert) 3:Change(Update)
+     */
+    @future (callout=true)
+    public static void callout(String iflog_Id, List<String> ordIds, Map<String, String> purposeOfAdviceMap) {
+        if (ordIds == null || ordIds.size() == 0) {
+            return;
+        }
+        //SBG027Sync.HTTPS_Port stub = new SBG027Sync.HTTPS_Port();
+        //stub.timeout_x = 100000; // timeout in milliseconds
+        //stub.endpoint_x = NFMUtil.SBG027_ENDPOINT;
+        //stub.inputHttpHeaders_x = new Map<String, String>();
+        //stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+        //if (NFMUtil.CLIENT_CERT_NAME != null) {
+        //    stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+        //}
+
+        // MessageGroupNumber 銇彇寰�
+        List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog_Id];
+        BatchIF_Log__c iflog = null;
+        if (iflogList.size() > 0) {
+            iflog = iflogList.get(0);
+            iflog.ErrorLog__c = '';
+        } else {
+            // 銉囥兗銈垮彇銈屻仯銇︺仾銇勩仺銇�乺ollback銇曘倢銇︺亜銈嬨亾銇ㄣ仹銇�
+            return;
+        }
+        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + ordIds.size() + '\n';
+
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas_element quotations = new GeDatas_element();
+        NFMUtil.Monitoring  me = new NFMUtil.Monitoring();
+        me.Tag                  = 'MSGH';
+        me.Sender               = '8405';
+        me.Receiver             = '1330';
+        me.MessageType          = 'SBG027';
+        me.MessageGroupNumber   = iflog.Name;
+        me.NumberOfRecord       = '' + ordIds.size();
+        me.TransmissionDateTime = nowStr;
+        me.Text = '';
+        quotations.Monitoring = me;
+        BatchIF_Log__c rowData = null;
+        try {
+             //杌㈤�併儑銉笺偪銈掑彇寰椼�佸弬鐓у厛銇儑銉笺偪銇屻亗銈嬨伄銇с�併亾銇撱仹妞滅储蹇呰銇с仚銆侺evel_Category__c
+            List<order> ordList = [select Id,Name,Opportunity.Name, Opportunity.CurrencyIsoCode,OrderNumber,Opportunity.ForeignTradeCompany__r.ManagementCode_F__c,CustomerContractPriceD__c,SpecialCondition_text__c,SalesChannel__c,
+                                                Owner.Name,Opportunity.AccountId__c,Opportunity.InquiryNumber__c,Opportunity.SpecialDeliveryAddress__r.ManagementCode_F__c, ServiceFee_D__c,Opportunity.SpecialDeliveryAddress_D__c,Opportunity.SpecialDeliveryAddress_D__r.ManagementCode_F__c,
+                                                Opportunity.ProductSegment__c, Opportunity.TradeType__c,Opportunity.Dealer__r.ManagementCode_Ext__c,EndUserD__c,ExpDelDate__c,EndUserD__r.ManagementCode_F__c,Discount_D__c,
+                                                Opportunity.EndUser__c, Opportunity.Machine_Parts__c,Opportunity.Dealer__r.ManagementCode_F__c,Opportunity.Account.ManagementCode_F__c,Contract.Name,Shipment_Term_D__c,Shipment_Term2_D__c,
+                                                Opportunity.SalesChannel__c, Opportunity.ExpectedDeliveryDate__c, Opportunity.DealerId__c,Opportunity.DealerSalesStaffName__c,OlympusContractPricesD__c,SpecialDeliveryContact_D__c,Opportunity.SpecialDeliveryContact_D__r.ManagementCode_F__c,
+                                                Opportunity.ForeignTradeCompany__c, Opportunity.SpecialDeliveryAddress__c,PaymentTerms__c,SpecialDeliveryContact__c,PDF_Sp_Shipment_Term__c,PDF_Sp_ShippingTerms__c,
+                                                ForeignTradeCompany_D__r.ManagementCode_F__c, SpecialDeliveryAccount_D__r.ManagementCode_F__c, SpecialDeliveryContact2_D__r.ManagementCode_F__c,Opportunity.Dealer__r.DummyDealer__c,ContractPriceTotal__c,
+                                                If_Supervise__c,CrossCooperativeDealerCode__c,SplitRatio__c,CrossCooperativeProject__c,Level_Category__c,DealerSalesStaffNameA__c,Dealer_A__r.ManagementCode_Ext__c,Dealer_B__r.ManagementCode_F__c
+                                             from order where Id IN :ordIds ];
+            //List<order> ordList = [select Id,Name,Opportunity.Name, Opportunity.CurrencyIsoCode,OrderNumber,Opportunity.ForeignTradeCompany__r.ManagementCode_F__c,CustomerContractPriceD__c,SpecialCondition_text__c,SalesChannel__c,
+            //                                    Owner.Name,Opportunity.AccountId__c,Opportunity.InquiryNumber__c,Opportunity.SpecialDeliveryAddress__r.ManagementCode_F__c, ServiceFee_D__c,Opportunity.SpecialDeliveryAddress_D__c,Opportunity.SpecialDeliveryAddress_D__r.ManagementCode_F__c,
+            //                                    Opportunity.ProductSegment__c, Opportunity.TradeType__c,Opportunity.Dealer__r.ManagementCode_Ext__c,EndUserD__c,ExpDelDate__c,EndUserD__r.ManagementCode_F__c,Discount_D__c,
+            //                                    Opportunity.EndUser__c, Opportunity.Machine_Parts__c,Opportunity.Dealer__r.ManagementCode_F__c,Opportunity.Account.ManagementCode_F__c,Contract.Name,Shipment_Term_D__c,Shipment_Term2_D__c,
+            //                                    Opportunity.SalesChannel__c, Opportunity.ExpectedDeliveryDate__c, Opportunity.DealerId__c,Opportunity.DealerSalesStaffName__c,OlympusContractPricesD__c,SpecialDeliveryContact_D__c,Opportunity.SpecialDeliveryContact_D__r.ManagementCode_F__c,
+            //                                    Opportunity.ForeignTradeCompany__c, Opportunity.SpecialDeliveryAddress__c,PaymentTerms__c,SpecialDeliveryContact__c,PDF_Sp_Shipment_Term__c,PDF_Sp_ShippingTerms__c,
+            //                                    ForeignTradeCompany_D__r.ManagementCode_F__c, SpecialDeliveryAccount_D__r.ManagementCode_F__c, SpecialDeliveryContact2_D__r.ManagementCode_F__c,Opportunity.Dealer__r.DummyDealer__c,ContractPriceTotal__c
+            //                               from order where Id IN :ordIds ];
+System.debug('111111 ordList='+ordList);
+            // Quotation銇儑銉笺偪銇ō瀹�
+            
+            List<DecideQuoteProductSet__c> decideQuoteProductSetList = [
+                                select Id,Name,DecideProductSet__c,DecideProductSetCount__c,
+                                    DecideOpportunity__c,DecideProductSet__r.Code__c,
+                                    DecideQuote__c,DecideOrder__c,DecideProductSet__r.Name
+                                from DecideQuoteProductSet__c
+                                where DecideOrder__c In :ordIds
+                                ];
+           
+            Map<String,String> dqpsNameAndCountMap = new Map<String,String>();
+            String name ; String count;
+            String value; String bppMapGetValue;
+            for (DecideQuoteProductSet__c dqps :decideQuoteProductSetList) {
+                name = dqps.DecideProductSet__r.Code__c;
+                count = String.valueOf(dqps.DecideProductSetCount__c);
+                value = name +','+ count;
+                if (dqpsNameAndCountMap.containsKey(dqps.DecideOrder__c)) {
+
+                    bppMapGetValue = dqpsNameAndCountMap.get(dqps.DecideOrder__c) +';'+ value ;
+                    dqpsNameAndCountMap.put(dqps.DecideOrder__c, bppMapGetValue);
+                } else {
+                    dqpsNameAndCountMap.put(dqps.DecideOrder__c, value);
+                }
+            }
+            //XHL-20190510-AddEnd
+
+
+
+
+            quotations.GeData = new List<GeData_element>();
+            for (Order ord : ordList) { 
+                // 鍟嗚珖鍟嗗搧鎯呭牨銈掑彇寰�
+                List<OrderItem> ordLiList = 
+                                        [select Id, Quantity, PricebookEntry.ProductCode,QuoteLineItem.SingleProduct__c,
+                                            ODISingleProduct__c,Order.ProductSegment__c
+                                           from OrderItem where OrderId = :ord.Id 
+                                           order by ODISingleProduct__c desc,id];
+
+
+                GeData_element quotation = new GeData_element();
+
+                //CBPR
+                if(ord.Opportunity.ProductSegment__c == 'BS'){
+                    if(ord.If_Supervise__c){
+                        if (ord.Level_Category__c == '浜岀被') {
+                            quotation.ZNMPA = 'Y';
+                        } else if(ord.Level_Category__c == '涓�绫�'){
+                            quotation.ZNMPA = 'X';
+                        } else {
+                            quotation.ZNMPA = 'N';
+                        }
+                    } else {
+                        quotation.ZNMPA = null;
+                    }
+                } else {
+                    quotation.ZNMPA = null;
+                }
+                /*if(ord.Opportunity.ProductSegment__c == 'BS'){
+                    if (ord.If_Supervise__c) {
+                        quotation.ZNMPA = 'Y';
+                    } else {
+                        quotation.ZNMPA = 'N';
+                    }
+                }else{
+                    quotation.ZNMPA = null;
+                }*/
+                
+                
+                //CBPR
+                if (ord.Opportunity.Dealer__r.DummyDealer__c == true || ord.Opportunity.SalesChannel__c == 'direct'){
+                quotation.DealerCode          = ord.Opportunity.Account.ManagementCode_F__c;
+                quotation.SalesAccountCode                   = ord.SpecialDeliveryAccount_D__r.ManagementCode_F__c;
+                }
+                else{
+                quotation.DealerCode          = ord.Opportunity.Dealer__r.ManagementCode_Ext__c;
+                quotation.SalesAccountCode                   = ord.Opportunity.Account.ManagementCode_F__c;
+
+                }
+                quotations.GeData.add(quotation);
+                quotation.OrderCode                      = ord.OrderNumber;
+                quotation.OpportunityCode                = ord.Opportunity.InquiryNumber__c;
+//                //quotation.SalesAccountCode                   = ord.Opportunity.Account.ManagementCode_F__c;
+                quotation.ProductSegment              = ord.Opportunity.ProductSegment__c;
+                quotation.TradeType              = ord.Opportunity.TradeType__c;
+                quotation.MachineParts                   = ord.Opportunity.Machine_Parts__c;
+                quotation.SalesChannel   =                 ord.Opportunity.Machine_Parts__c == 'Parts' ? '40' : ord.Opportunity.SalesChannel__c == 'dealer' ?  '41' : '42';
+                quotation.DeliveryDate          = NFMUtil.formatDate2Str(ord.Opportunity.ExpectedDeliveryDate__c);
+//               // quotation.DealerCode          = ord.Opportunity.Dealer__r.ManagementCode_Ext__c;
+                quotation.DealerSalesStaffName         = ord.Opportunity.DealerSalesStaffName__c;
+                quotation.ForeignTradeCompany                   = ord.ForeignTradeCompany_D__r.ManagementCode_F__c;
+                quotation.PaymentCondition                  = ord.PaymentTerms__c;
+                quotation.EndUser            =  ord.EndUserD__r.ManagementCode_F__c;
+                quotation.DeliveryDate = NFMUtil.formatDate2Str(ord.ExpDelDate__c);
+                quotation.ServiceFee      =  ord.ServiceFee_D__c;
+                //2017/01/15杩藉姞
+                if(ord.Opportunity.SalesChannel__c == 'direct' && ord.Opportunity.Machine_Parts__c == 'Parts'){
+                     quotation.Discount         = 0;
+                     quotation.OlympusContractPrices = ord.CustomerContractPriceD__c;
+                }
+                else{
+                    quotation.Discount         = ord.Discount_D__c;
+                    quotation.OlympusContractPrices = ord.ContractPriceTotal__c;
+                }
+                quotation.SpecialDeliveryAddress                   = ord.SpecialDeliveryAccount_D__r.ManagementCode_F__c + ',' + ord.SpecialDeliveryContact2_D__r.ManagementCode_F__c;
+                //quotation.Other1            = ord.Name + ',' + ord.SalesChannel__c;
+
+                String  other1 = ord.Name + ',' + ord.SalesChannel__c;
+                if (String.isNotBlank(other1) && other1.indexof('%') != -1) {
+                    other1 = other1.replace('%','锛�');
+                }
+                quotation.Other1 = other1;
+                
+                String other2 = ord.SpecialCondition_text__c;
+                if (String.isNotBlank(other2) && other2.indexof('%') != -1) {
+                    other2 = other2.replace('%','锛�');
+                }
+                quotation.Other2            = other2;//ord.SpecialCondition_text__c;
+                quotation.Other3            = ord.Shipment_Term_D__c + ',' + ord.Shipment_Term2_D__c;
+                // 璺ㄥ尯鍩熼攢鍞� XHL 20210831 Start
+                quotation.CoopAgent = '';
+                quotation.CoopAgentPCT = '';
+                if (ord.CrossCooperativeProject__c) {//璺ㄧ渷浠藉悎浣滈」鐩�
+                    quotation.CoopAgent = ord.Dealer_B__r.ManagementCode_F__c;//鍚堜綔鍖哄煙浠g悊鍟咰ode
+                    quotation.DealerCode         = ord.Dealer_A__r.ManagementCode_Ext__c;
+                    quotation.DealerSalesStaffName = ord.DealerSalesStaffNameA__c;
+                    String splitRatio = ord.SplitRatio__c;
+                    if (String.isNotBlank(splitRatio) && splitRatio.indexof(':') > 0) {
+                        Integer pct = Integer.valueOf(splitRatio.split(':')[1].trim())*10;
+                        quotation.CoopAgentPCT = String.valueof(pct);//涓氱哗鎷嗗垎姣斾緥(鍙�:鍚庤竟鐨勫��*10)
+                    } 
+                } 
+                // 璺ㄥ尯鍩熼攢鍞� XHL 20210831 End
+                quotation.GeDataDetails = new List<GeDataDetails_element>();
+                //Detail_element
+                Integer m = 0;
+                for (Integer i = 0; i < ordLiList.size(); i++) {
+                    
+                    if (ordLiList.get(i).Order.ProductSegment__c == 'BS') {
+
+                        //XHL-20190510-AddStart
+                        if (!ordLiList.get(i).ODISingleProduct__c) {
+                            continue;
+                        }
+                        m++;
+                        //XHL-20190510-AddEnd
+                        GeDataDetails_element detail = new GeDataDetails_element();
+                        quotation.GeDataDetails.add(detail);
+                        detail.DetailLine                  = (i + 1) * 10;
+                        detail.ItemCode                    = ordLiList.get(i).PricebookEntry.ProductCode;
+                        detail.ItemQuantity                = Integer.valueOf(ordLiList.get(i).Quantity);
+                    } else {
+
+                        GeDataDetails_element detail = new GeDataDetails_element();
+                        quotation.GeDataDetails.add(detail);
+                        detail.DetailLine                  = (i + 1) * 10;
+                        detail.ItemCode                    = ordLiList.get(i).PricebookEntry.ProductCode;
+                        detail.ItemQuantity                = Integer.valueOf(ordLiList.get(i).Quantity);
+                    }
+                    
+                }
+
+                //XHL-20190510-AddStart
+                if (dqpsNameAndCountMap.containsKey(ord.Id)) {
+                    value = dqpsNameAndCountMap.get(ord.Id);
+                    List<String> nameCountList = new List<String>();
+                    for (String str: value.split(';')){
+                        nameCountList.add(str);
+                    }
+                    if (nameCountList.size() > 0 ){
+
+                        for (String  nameCount :nameCountList) {
+
+                            GeDataDetails_element detail = new GeDataDetails_element();
+                            quotation.GeDataDetails.add(detail);
+                            detail.DetailLine                  = (m + 1) * 10;
+                            detail.ItemCode                    = nameCount.split(',')[0];
+                            detail.ItemQuantity                = Integer.valueOf(nameCount.split(',')[1]);
+                            m++;
+                        }
+                    }
+
+                }
+                //XHL-20190510-AddEnd
+                logstr += quotation.OrderCode + '\n';
+            }
+
+            if (quotations.GeData.size() > 0) {
+                //SBG027Sync.Quotations_element[] pQuotations = new SBG027Sync.Quotations_element[] { quotations };
+                logstr += '\ncallout count=' + quotations.GeData.size();
+                //OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG027_Sync_BC2GPI(pQuotations);
+                // 鍘熷墖闈炲悓鏈熴仹銇欍伄銇с�乴ogs銈掔⒑瑾嶃仚銈嬪繀瑕併亴銇亜銇с仐銈囥亞銆�
+                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+                Monitoring.Tag                  = quotations.Monitoring.Tag;
+                Monitoring.Sender               = quotations.Monitoring.Sender;
+                Monitoring.Receiver             = quotations.Monitoring.Receiver;
+                Monitoring.MessageType          = quotations.Monitoring.MessageType;
+                Monitoring.MessageGroupNumber   = quotations.Monitoring.MessageGroupNumber;
+                Monitoring.NumberOfRecord       = quotations.Monitoring.NumberOfRecord;
+                Monitoring.TransmissionDateTime = quotations.Monitoring.TransmissionDateTime;
+                Monitoring.Text = '';
+                SBG027 sBG027 = new SBG027();
+                sBG027.GeDatas =  quotations;
+                rowData = NFMUtil.makeRowData(Monitoring, 'SBG027', sBG027);
+                execute(rowData, iflog);
+            }
+            Set<String> inquiryNoList = new Set<String>();
+
+            Map<String, Order> ordUpsertMap = new Map<String, Order>();
+            logstr += '\nend';
+        } catch(Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+        }
+        if (rowData != null) {
+            insert rowData;
+        }
+
+        System.debug(Logginglevel.DEBUG, 'SBG027_' + iflog.Name + ' end');
+        iflog.Log__c = logstr;
+        update iflog; 
+    } 
+
+    public static void execute2(String rowDataId) {
+        List<BatchIF_Log__c> row = [select id, name, MessageGroupNumber__c, retry_cnt__c,
+                                           RowDataFlg__c, ErrorLog__c, Type__c,
+                                           Log__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
+                                           Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c
+                                      from BatchIF_Log__c
+                                     where id = :rowDataId];
+        if (row.size() > 0) execute(row[0], null);
+    }
+
+    public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {
+        //gaozw
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        SBG027 sBG027 = (SBG027) JSON.deserialize(rowDataStr, SBG027.class);
+
+        String logstr = sBG027.GeDatas.Monitoring.MessageGroupNumber + ' start\n';
+        Boolean needUpdateIflog = false;
+        if  (iflog == null) {
+            needUpdateIflog = true;
+            iflog = new BatchIF_Log__c();
+            iflog.Type__c = 'SBG027';
+            iflog.MessageGroupNumber__c = sBG027.GeDatas.Monitoring.MessageGroupNumber;
+            iflog.Log__c = logstr;
+            iflog.ErrorLog__c = '';
+            //insert iflog;
+            //iflog = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog.Id];
+        } else {
+            logstr = iflog.Log__c;
+        } 
+        try{
+            
+            NFMUtil.sendToSap(rowDataStr, NFMUtil.SBG027_ENDPOINT); 
+            rowData.retry_cnt__c = 0;
+        }catch(Exception ex) {
+            // TODO IOException
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getStackTraceString());
+            logstr += ex.getMessage();
+            iflog.ErrorLog__c += ex.getMessage() + '\n';
+            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+
+            //---xiongyl---add
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                //---20200309鈫扻HL鈫扐dd鈫扴tart
+                LogAutoSendSchedule.assignOneMinute();
+                //---20200309鈫扻HL鈫扐dd鈫扙nd
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+            }
+        }
+        iflog.Log__c = logstr;
+        if (needUpdateIflog) {
+            upsert iflog;
+            update rowData;
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG027Controller.cls-meta.xml b/scr/classes/SBG027Controller.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG027Controller.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG027TriggerHandleTest.cls b/scr/classes/SBG027TriggerHandleTest.cls
new file mode 100644
index 0000000..25eef90
--- /dev/null
+++ b/scr/classes/SBG027TriggerHandleTest.cls
@@ -0,0 +1,617 @@
+@isTest
+public class SBG027TriggerHandleTest {
+    static String  setdata(){
+        Id pricebookId = Test.getStandardPricebookId();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        insert new Product2[] {product1,product2,product3};
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456',
+            DummyDealer__c = true
+        );
+        insert accIE; 
+         List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+    //    List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS',
+            DummyDealer__c = true
+        );
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+        Date day1 = Date.today();
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.Dealer__c = buyer.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Phase3';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'Sales_Channel_D__c';
+        //opp.SalesChannel__c = 'direct';
+        //opp.Machine_Parts__c = 'Parts';
+
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Trade_Type_D__c';
+        //opp.Pricebook2Id = pricebook.Id;
+
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+         Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            //Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname1',
+            SetQty1__c = 1,
+            SetName2__c = 'setname2',
+            SetQty2__c = 2,
+            Custom_Price_Total_Text__c = 1000
+            //IsSyncing = true
+        );
+        insert quo;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        List<productSet__c>  insertproductSets = new  List<productSet__c>();
+        productSet__c proSet1 = new productSet__c();
+        proSet1.Code__c = 'IXP-7P2';
+        proSet1.Name = 'IXP-7P2';
+        proSet1.IsValid__c = true;
+        proSet1.Name = 'IXP-7P2';
+        insertproductSets.add(proSet1);
+        productSet__c proSet2 = new productSet__c();
+        proSet2.Code__c = 'IXP-7P1SC';
+        proSet2.Name = 'IXP-7P1SC';
+        proSet2.IsValid__c = true;
+        proSet2.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet2);
+        productSet__c proSet3 = new productSet__c();
+        proSet3.Code__c = 'IXSP-T7LED';
+        proSet3.Name = 'IXSP-T7LED';
+        proSet3.IsValid__c = true;
+        proSet3.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet3);
+
+
+        insert insertproductSets;
+
+
+        List<RecordType> rectOrder = [select id from RecordType where IsActive = true and SobjectType = 'Order'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = '01228000000NJt6',
+            confirm__c = false,
+            SP_21__c = true,
+            EndUser__c = con.Id
+        );
+        insert odr;
+
+        DecideQuoteProductSet__c dqps = new DecideQuoteProductSet__c();
+
+        dqps.DecideProductSet__c = proSet1.Id ;
+        dqps.DecideProductSetCount__c = 4;
+        dqps.DecideOpportunity__c = opp.Id;
+        dqps.DecideQuote__c = quo.Id;
+        dqps.DecideOrder__c = odr.Id;
+
+        insert dqps;
+        Delivery__c de1 = new Delivery__c();
+        de1.SSBD_Contract__c = odr.Id;
+        insert de1;
+        Opportunity ordd = [Select InquiryNumber__c,Id,Name From Opportunity];
+        return ordd.InquiryNumber__c;
+    }
+
+
+    @isTest static void test_method_1() {
+        setdata();
+        Order o = [Select Id,Name From Order];
+        o.confirm__c = true;
+        o.CrossCooperativeProject__c = true;
+        o.SplitRatio__c = '5 : 5';
+        update o;
+    }
+
+    @isTest static void test_execute2() {
+
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Log__c = '{"GeDatas":{"Monitoring":{"TransmissionDateTime":"202108250938","Text":"","Tag":"MSGH","Sender":"8405","Receiver":"1330","NumberOfRecord":"1","MessageType":"SBG027","MessageGroupNumber":"20210000465499"},"GeData":[{"ZNMPA":"N","TradeType":"Taxation","SpecialWarranty":null,"SpecialDeliveryAddress":"3000002093,C-2018-72066","ServiceFee":null,"SalesChannel":"41","SalesAccountCode":"76002795","PurposeOfAdvice":null,"ProductSegment":"BS","PaymentCondition":"ZZTT","Other3":"null,null","Other2":"璺ㄧ渷浠藉悎浣滈」鐩�","Other1":"test,dealer","OrderCode":"00050193","OpportunityCode":"O-2021-115172","OlympusPriceBeforeDiscount":null,"OlympusContractPrices":729412.00,"MachineParts":"Machine","GeDataDetails":[{"ItemQuantity":20,"ItemCode":"000000000006498300","DetailLine":10},{"ItemQuantity":20,"ItemCode":"N2664900","DetailLine":20}],"ForeignTradeCompany":null,"EndUser":"C-2016-25119","Discount":49.00,"DeliveryDate":"20210825","DealerSalesStaffName":"a","DealerCode":"3000002093","CoopAgentPCT":"50","CoopAgent":"A-2021-120990"}]}}';
+        insert iflog;
+        SBG027Controller.execute2(iflog.Id);
+    }
+
+//     @isTest static void test_init1() {
+//         Id pricebookId = Test.getStandardPricebookId();
+
+//         Pricebook2 pricebook = new Pricebook2(
+//             Name = 'IE',
+//             ProductSegment__c = 'IE',
+//             TradeType__c = 'Taxation',
+//             SalesChannel__c = 'direct',
+//             MachineParts__c = 'Machine',
+//             isActive = true
+//         );
+//         insert pricebook;
+
+//         Product2 product1 = new Product2();
+//         product1.Name = 'product1';
+//         product1.ProductCode = 'product1';
+//         product1.Product_ECCode__c = 'product1';
+//         product1.IsActive = true;
+
+//         Product2 product2 = new Product2();
+//         product2.Name = 'product2';
+//         product2.ProductCode = 'product2';
+//         product2.Product_ECCode__c = 'product2';
+//         product2.IsActive = true;
+
+//         Product2 product3 = new Product2();
+//         product3.Name = 'product3';
+//         product3.ProductCode = 'product3';
+//         product3.Product_ECCode__c = 'product3';
+//         product3.IsActive = true;
+
+//         insert new Product2[] {product1, product2, product3};
+
+//         PricebookEntry standardPrice1 = new PricebookEntry(
+//             Pricebook2Id = pricebookId,
+//             Product2Id = product1.Id,
+//             UnitPrice = 0,
+//             IsActive = true,
+//             CurrencyIsoCode = 'CNY'
+//         );
+
+//         PricebookEntry standardPrice2 = new PricebookEntry(
+//             Pricebook2Id = pricebookId,
+//             Product2Id = product2.Id,
+//             UnitPrice = 0,
+//             IsActive = true,
+//             CurrencyIsoCode = 'CNY'
+//         );
+
+//         PricebookEntry standardPrice3 = new PricebookEntry(
+//             Pricebook2Id = pricebookId,
+//             Product2Id = product3.Id,
+//             UnitPrice = 0,
+//             IsActive = true,
+//             CurrencyIsoCode = 'CNY'
+//         );
+
+//         insert new PricebookEntry[] {standardPrice1, standardPrice2, standardPrice3};
+
+//         PricebookEntry entry1 = new PricebookEntry(
+//             Pricebook2Id = pricebook.Id,
+//             Product2Id = product1.Id,
+//             UnitPrice = 30,
+//             IsActive = true,
+//             UseStandardPrice = false,
+//             CurrencyIsoCode = 'CNY'
+//         );
+
+//         PricebookEntry entry2 = new PricebookEntry(
+//             Pricebook2Id = pricebook.Id,
+//             Product2Id = product2.Id,
+//             UnitPrice = 30,
+//             IsActive = true,
+//             UseStandardPrice = false,
+//             CurrencyIsoCode = 'CNY'
+//         );
+
+//         PricebookEntry entry3 = new PricebookEntry(
+//             Pricebook2Id = pricebook.Id,
+//             Product2Id = product3.Id,
+//             UnitPrice = 30,
+//             IsActive = true,
+//             UseStandardPrice = false,
+//             CurrencyIsoCode = 'CNY'
+//         );
+
+//         insert new PricebookEntry[] {entry1, entry2, entry3};
+
+//         List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+//         Account user = new Account(
+//             Name = '*',
+//             FacilityName__c = 'user',
+//             PostCode__c = '123456',
+//             RecordTypeId = rectIE[0].Id
+//         );
+//         insert user;
+
+//         Contact con = new Contact();
+//         con.LastName = 'test';
+//         con.AccountId = user.Id;
+//         con.MobilePhone = 'MobilePhoneD__c';
+//         con.OtherPhone = 'OtherPhoneD__c';
+//         con.Fax = 'FaxD__c';
+//         con.Email = 'EmailD__c@test.com';
+//         con.Phone = 'PhoneD__c';
+//         con.Title = 'TitleD__c';
+//         con.Address1__c = 'Address1D__c';
+//         con.Address2__c = 'Address2D__c';
+//         con.Address3__c = 'Address3D__c';
+//         con.Postcode__c = '100111';
+//         con.ContactStatus__c = 'ContactStatusD__c';
+//         con.CancelReason__c = 'CancelReasonD__c';
+//         con.StatusD__c = 'Pass';
+
+//         insert con;
+
+//         Opportunity opp = new Opportunity(
+//             Name = 'test opp',
+//             AccountId = user.Id,
+//             StageName = 'Phase3',
+//             CurrencyIsoCode = 'CNY',
+//             ProductSegment__c = 'IE',
+//             CloseDate = Date.today(),
+//             NewInquiryDate__c = Date.today().addDays(-2),
+//             ExpectedOrderDate__c = Date.today().addDays(2),
+//             TradeType__c = 'Taxation',
+//             SalesChannel__c = 'direct',
+//             Machine_Parts__c = 'Machine',
+//             Pricebook2Id = pricebook.Id
+//         );
+//         insert opp;
+
+//         OpportunityContactRole role = new OpportunityContactRole(
+//             Role  = 'End user',
+//             IsPrimary = true,
+//             OpportunityId = opp.Id,
+//             ContactId = con.Id
+//             );
+//         insert role;
+
+//         OpportunityLineItem oli1 = new OpportunityLineItem(
+//             OpportunityId = opp.Id,
+//             PricebookEntryId = entry1.Id,
+//             Quantity = 1,
+//             UnitPrice = 30
+//         );
+
+//         OpportunityLineItem oli2 = new OpportunityLineItem(
+//             OpportunityId = opp.Id,
+//             PricebookEntryId = entry2.Id,
+//             Quantity = 2,
+//             UnitPrice = 30
+//         );
+
+//         OpportunityLineItem oli3 = new OpportunityLineItem(
+//             OpportunityId = opp.Id,
+//             PricebookEntryId = entry3.Id,
+//             Quantity = 3,
+//             UnitPrice = 30
+//         );
+//              System.Test.StartTest();
+//         insert new OpportunityLineItem[] {oli1, oli2, oli3};
+
+//         PageReference page = new PageReference('/apex/NewQuoteService?oppid=' + opp.Id + '&openType=service');
+//         System.Test.setCurrentPage(page);
+//         NewQuoteEntryController controller = new NewQuoteEntryController();
+
+//         controller.init();
+
+//         controller.quo.Name = '鎶ヤ环1';
+//         controller.quo.PaymentTerms__c = 'Z0LC';
+//         controller.quo.Shipment_Term__c = 'CIP';
+//         controller.quo.Shipment_Term2__c = 'BEIJING';
+//         controller.quo.DeliveryLeadTime__c = 90;
+//         controller.quo.Warranty__c = 1;
+//         controller.quo.ExpirationDate = Date.today();
+//         controller.quo.Custom_Price_Total_Text__c = 1000;
+
+// /*        controller.activities[0].pageObject.PricebookEntryId = entry1.Id;
+//         controller.activities[0].pageObject.Set__c = 'set01';
+//         controller.activities[0].pageObject.UnitPrice = 11;
+//         controller.activities[0].pageObject.Quantity = 1
+//         controller.activities[0].pageObject.Discount = 0;
+//         controller.activities[0].pageObject.Custom_Price__c = 20;
+//         controller.activities[0].pageObject.Description = 'test1';*/
+        
+//         controller.Save();
+
+//         //system.assertEquals('',controller.errormessage);
+
+//         // controller.excelImport();
+
+//         // controller.OppReflection();
+
+//         // controller.BackBtn();
+       
+//         controller.Decide();
+//         List<Quote> QuoteList = [select Id from Quote]; 
+//         // Quote quo = QuoteList[0];
+//         // quo.PaymentTerms__c = 'Z9TT';
+//         // update quo;
+//         Order order = new Order(
+//             Name = 'order',
+//             CurrencyIsoCode = 'CNY',
+//             AccountId = user.Id,
+//             OpportunityId = opp.Id,
+//             QuoteId = QuoteList[0].Id, //quo.Id,
+//             EffectiveDate = Date.today(),
+//             Status = 'Draft',
+//             Pricebook2Id = pricebook.Id,
+//             EndUser__c = con.Id
+//         );
+//         insert order;
+
+//         order.confirm__c = true;
+//         update order;
+
+//         //controller.UnDecide();
+//         System.Test.StopTest();
+//     }
+
+    //    //浜у搧閰嶅鐩稿叧
+    //@isTest static void test_init5() {
+    //    Id pricebookId = Test.getStandardPricebookId();
+
+    //    Pricebook2 pricebook = new Pricebook2(
+    //        Name = 'IE',
+    //        ProductSegment__c = 'IE',
+    //        TradeType__c = 'Taxation',
+    //        SalesChannel__c = 'direct',
+    //        MachineParts__c = 'Machine',
+    //        isActive = true
+    //    );
+    //    insert pricebook;
+
+    //    Product2 product1 = new Product2();
+    //    product1.Name = 'product1';
+    //    product1.ProductCode = 'product1';
+    //    product1.Product_ECCode__c = 'product1';
+    //    product1.ProductModels__c = true;
+    //    product1.ProductStatus__c = '1';
+    //    insert product1;
+
+    //    PricebookEntry standardPrice1 = new PricebookEntry(
+    //        Pricebook2Id = pricebookId,
+    //        Product2Id = product1.Id,
+    //        UnitPrice = 0,
+    //        IsActive = true,
+    //        CurrencyIsoCode = 'CNY'
+    //    );
+    //    insert standardPrice1;
+
+    //    PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+    //    entry1.UnitPrice = 0;
+    //    entry1.IsActive = true;
+    //    entry1.UseStandardPrice = false;
+    //    entry1.CurrencyIsoCode = 'CNY';
+    //    insert entry1;
+
+    //    Product_Search__c ps = new Product_Search__c(Product__c = product1.Id);
+
+    //    List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+    //    Account user = new Account(
+    //        Name = '*',
+    //        FacilityName__c = 'user',
+    //        PostCode__c = '123456',
+    //        RecordTypeId = rectIE[0].Id
+    //    );
+    //    insert user;
+
+    //    Opportunity opp = new Opportunity(
+    //        Name = 'test opp',
+    //        AccountId = user.Id,
+    //        StageName = 'Prospect Created',
+    //        CurrencyIsoCode = 'CNY',
+    //        ProductSegment__c = 'BS',
+    //        CloseDate = Date.today(),
+    //        NewInquiryDate__c = Date.today().addDays(-2),
+    //        ExpectedOrderDate__c = Date.today().addDays(2),
+    //        TradeType__c = 'Taxation',
+    //        SalesChannel__c = 'direct',
+    //        Machine_Parts__c = 'Machine',
+    //        Pricebook2Id = pricebook.Id
+    //    );
+    //    insert opp;
+    //     Quote quo = new Quote(
+    //        Name = 'quo',
+    //        OpportunityId = opp.Id,
+    //        SetName1__c = 'IXP-7P2',
+    //        SetQty1__c = 1,
+    //        Is_Decided__c = true
+    //    );
+    //    insert quo;
+    //    List<productSet__c>  insertproductSets = new  List<productSet__c>();
+    //    productSet__c proSet1 = new productSet__c();
+    //    proSet1.Code__c = 'IXP-7P2';
+    //    proSet1.Name = 'IXP-7P2';
+    //    proSet1.IsValid__c = true;
+    //    proSet1.Name = 'IXP-7P2';
+    //    insertproductSets.add(proSet1);
+    //    productSet__c proSet2 = new productSet__c();
+    //    proSet2.Code__c = 'IXP-7P1SC';
+    //    proSet2.Name = 'IXP-7P1SC';
+    //    proSet2.IsValid__c = true;
+    //    proSet2.Name = 'IXP-7P1SC';
+    //    insertproductSets.add(proSet2);
+    //    productSet__c proSet3 = new productSet__c();
+    //    proSet3.Code__c = 'IXSP-T7LED';
+    //    proSet3.Name = 'IXSP-T7LED';
+    //    proSet3.IsValid__c = true;
+    //    proSet3.Name = 'IXSP-T7LED';
+    //    insertproductSets.add(proSet3);
+
+
+    //    insert insertproductSets;
+
+    //    productSetItem__c  productSetItem = new productSetItem__c();
+    //    productSetItem.productSet__c = proSet1.Id;
+    //    productSetItem.Count__c = 5;
+    //    productSetItem.product__c = product1.Id;
+    //    insert productSetItem ;
+    //    PageReference page = new PageReference('/apex/NewQuoteEntry?id=' + quo.Id );
+    //    System.Test.setCurrentPage(page);
+    //    NewQuoteEntryController controller = new NewQuoteEntryController();
+    //    Map<String,String> productSetCodeMap = new Map<String,String>();
+    //    productSetCodeMap.put('IXP-7P1SC', '3;49');
+    //    //productSetCodeMap.put('111111111', '3;49');
+    //    controller.init();
+    //    controller.setProduct_text = proSet1.Id+',1,49;'+proSet2.Id +',2,49;';
+    //    controller.setProductEntry();
+    //    controller.acquireProductSetId(productSetCodeMap);
+    //    controller.Save();
+    //    //controller.decideORundecideQuote(quo.Id,true);
+    //    controller.Decide();
+
+    //    List<QuoteLineItem> quoteLineItemList = [select id from QuoteLineItem];
+                                         
+    //    system.assertEquals(11111,quoteLineItemList.size());
+    //    Order order = new Order(
+    //        Name = 'order',
+    //        CurrencyIsoCode = 'CNY',
+    //        AccountId = user.Id,
+    //        OpportunityId = opp.Id,
+    //        QuoteId = quo.Id,
+    //        EffectiveDate = Date.today(),
+    //        Status = 'Draft',
+    //        Pricebook2Id = pricebook.Id
+    //    );
+
+    //    insert order;
+    //    List<Order> orderList = [select Id,ProductSegment__c from Order];
+    //    //system.assertEquals('Bss',orderList[0].ProductSegment__c);
+    //    List<OrderItem> ordLiList = 
+    //                                    [select Id, Quantity, PricebookEntry.ProductCode,QuoteLineItem.SingleProduct__c,
+    //                                        ODISingleProduct__c,Order.ProductSegment__c from  OrderItem ];
+    //    system.assertEquals(11111,ordLiList.size());   
+    //    order.confirm__c = true;
+    //    update order;
+
+    //}
+}
\ No newline at end of file
diff --git a/scr/classes/SBG027TriggerHandleTest.cls-meta.xml b/scr/classes/SBG027TriggerHandleTest.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/SBG027TriggerHandleTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG027TriggerHandler.cls b/scr/classes/SBG027TriggerHandler.cls
new file mode 100644
index 0000000..7f4b0dc
--- /dev/null
+++ b/scr/classes/SBG027TriggerHandler.cls
@@ -0,0 +1,320 @@
+public without sharing class SBG027TriggerHandler{
+    public static Set<Id> SBG027_Ids = new Set<Id>();    
+    public static void SBG027OrderTrigger(List<Order> newList, Map<Id, Order> newMap, List<Order> oldList, Map<Id, Order> oldMap){
+        if (!(Trigger.isBefore && Trigger.isUpdate)) {
+            return;
+        }   
+System.debug('-----SBG027OrderTrigger start');    
+        Map<Id, Id> accIds = new Map<Id, Id>();
+            List<String> strlist = new List<String>();
+                for (Order newOrd : newList) {
+                    strlist.add(newOrd.id);
+                }
+
+                for (Order newOrd : newList) {
+                     Order oldOrd = oldMap.get(newOrd.Id);
+                     if (oldOrd.confirm__c ==false && newOrd.confirm__c == true ){
+                        SBG027TriggerHandler.SBG027_Ids.add(newOrd.Id);
+                        BatchIF_Log__c iflog = new BatchIF_Log__c();
+                        iflog.Type__c = 'SBG027';
+                        iflog.Log__c  = 'callout start\n';
+                        insert iflog;
+                        iflog = [Select Id, Name from BatchIF_Log__c where Id = :iflog.Id];
+                        //SBG027TriggerHandler.callout(iflog.id,strlist, new Map<String, String>());
+                        SBG027Controller.callout(iflog.id,strlist, new Map<String, String>());
+                        
+                }
+         }
+    }
+
+
+   /**
+    * SBG027銇�佷俊鍑︾悊
+    *
+    * @param iflog_Id           銉偘銉嗐兗銉栥儷銇甀d
+    * @param ordIds             閫佷俊瀵捐薄鍟嗚珖(璜栫悊涓�1浠躲伄銇裤仹銇�)
+    * @param C1:Delete 2:Add(Insert) 3:Change(Update)
+    */
+//   @future (callout=true)
+//   public static void callout(String iflog_Id, List<String> ordIds, Map<String, String> purposeOfAdviceMap) {
+//       if (ordIds == null || ordIds.size() == 0) {
+//           return;
+//       }
+//       SBG027Sync.HTTPS_Port stub = new SBG027Sync.HTTPS_Port();
+//       stub.timeout_x = 100000; // timeout in milliseconds
+//       stub.endpoint_x = NFMUtil.SBG027_ENDPOINT;
+//       stub.inputHttpHeaders_x = new Map<String, String>();
+//       stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+//       if (NFMUtil.CLIENT_CERT_NAME != null) {
+//           stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+//       }
+
+//       // MessageGroupNumber 銇彇寰�
+//       List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog_Id];
+//       BatchIF_Log__c iflog = null;
+//       if (iflogList.size() > 0) {
+//           iflog = iflogList.get(0);
+//           iflog.ErrorLog__c = '';
+//       } else {
+//           // 銉囥兗銈垮彇銈屻仯銇︺仾銇勩仺銇�乺ollback銇曘倢銇︺亜銈嬨亾銇ㄣ仹銇�
+//           return;
+//       }
+//       String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + ordIds.size() + '\n';
+
+//       // Monitoring銇ō瀹�
+//       Datetime nowDT = Datetime.now();
+//       String nowStr = nowDT.format('yyyyMMddHHmm');
+//       SBG027Sync.GeDatas_element quotations = new SBG027Sync.GeDatas_element();
+//       quotations.Monitoring = new OlympusCoJpCommonMessage.Monitoring();
+//       quotations.Monitoring.Tag                  = 'MSGH';
+//       quotations.Monitoring.Sender               = '8405';
+//       quotations.Monitoring.Receiver             = '1330';
+//       quotations.Monitoring.MessageType          = 'SBG027';
+//       quotations.Monitoring.MessageGroupNumber   = iflog.Name;
+//       quotations.Monitoring.NumberOfRecord       = '' + ordIds.size();
+//       quotations.Monitoring.TransmissionDateTime = nowStr;
+//       quotations.Monitoring.Text = '';
+
+//       BatchIF_Log__c rowData = null;
+//       try {
+//           // 杌㈤�併儑銉笺偪銈掑彇寰椼�佸弬鐓у厛銇儑銉笺偪銇屻亗銈嬨伄銇с�併亾銇撱仹妞滅储蹇呰銇с仚銆�
+//           List<order> ordList = [select Id,Name,Opportunity.Name, Opportunity.CurrencyIsoCode,OrderNumber,Opportunity.ForeignTradeCompany__r.ManagementCode_F__c,CustomerContractPriceD__c,SpecialCondition_text__c,SalesChannel__c,
+//                                               Owner.Name,Opportunity.AccountId__c,Opportunity.InquiryNumber__c,Opportunity.SpecialDeliveryAddress__r.ManagementCode_F__c, ServiceFee_D__c,Opportunity.SpecialDeliveryAddress_D__c,Opportunity.SpecialDeliveryAddress_D__r.ManagementCode_F__c,
+//                                               Opportunity.ProductSegment__c, Opportunity.TradeType__c,Opportunity.Dealer__r.ManagementCode_Ext__c,EndUserD__c,ExpDelDate__c,EndUserD__r.ManagementCode_F__c,Discount_D__c,
+//                                               Opportunity.EndUser__c, Opportunity.Machine_Parts__c,Opportunity.Dealer__r.ManagementCode_F__c,Opportunity.Account.ManagementCode_F__c,Contract.Name,Shipment_Term_D__c,Shipment_Term2_D__c,
+//                                               Opportunity.SalesChannel__c, Opportunity.ExpectedDeliveryDate__c, Opportunity.DealerId__c,Opportunity.DealerSalesStaffName__c,OlympusContractPricesD__c,SpecialDeliveryContact_D__c,Opportunity.SpecialDeliveryContact_D__r.ManagementCode_F__c,
+//                                               Opportunity.ForeignTradeCompany__c, Opportunity.SpecialDeliveryAddress__c,PaymentTerms__c,SpecialDeliveryContact__c,PDF_Sp_Shipment_Term__c,PDF_Sp_ShippingTerms__c,
+//                                               ForeignTradeCompany_D__r.ManagementCode_F__c, SpecialDeliveryAccount_D__r.ManagementCode_F__c, SpecialDeliveryContact2_D__r.ManagementCode_F__c,Opportunity.Dealer__r.DummyDealer__c,ContractPriceTotal__c
+//                                          from order where Id IN :ordIds ];
+//System.debug('111111 ordList='+ordList);
+//           // Quotation銇儑銉笺偪銇ō瀹�
+            
+//           List<DecideQuoteProductSet__c> decideQuoteProductSetList = [
+//                               select Id,Name,DecideProductSet__c,DecideProductSetCount__c,
+//                                   DecideOpportunity__c,DecideProductSet__r.Code__c,
+//                                   DecideQuote__c,DecideOrder__c,DecideProductSet__r.Name
+//                               from DecideQuoteProductSet__c
+//                               where DecideOrder__c In :ordIds
+//                               ];
+           
+//           Map<String,String> dqpsNameAndCountMap = new Map<String,String>();
+//           String name ; String count;
+//           String value; String bppMapGetValue;
+//           for (DecideQuoteProductSet__c dqps :decideQuoteProductSetList) {
+//               name = dqps.DecideProductSet__r.Code__c;
+//               count = String.valueOf(dqps.DecideProductSetCount__c);
+//               value = name +','+ count;
+//               if (dqpsNameAndCountMap.containsKey(dqps.DecideOrder__c)) {
+
+//                   bppMapGetValue = dqpsNameAndCountMap.get(dqps.DecideOrder__c) +';'+ value ;
+//                   dqpsNameAndCountMap.put(dqps.DecideOrder__c, bppMapGetValue);
+//               } else {
+//                   dqpsNameAndCountMap.put(dqps.DecideOrder__c, value);
+//               }
+//           }
+//           //XHL-20190510-AddEnd
+
+
+
+
+//           quotations.GeData = new List<SBG027Sync.GeData_element>();
+//           for (Order ord : ordList) { 
+//               // 鍟嗚珖鍟嗗搧鎯呭牨銈掑彇寰�
+//               List<OrderItem> ordLiList = 
+//                                       [select Id, Quantity, PricebookEntry.ProductCode,QuoteLineItem.SingleProduct__c,
+//                                           ODISingleProduct__c,Order.ProductSegment__c
+//                                          from OrderItem where OrderId = :ord.Id 
+//                                          order by ODISingleProduct__c desc];
+
+
+//               SBG027Sync.GeData_element quotation = new SBG027Sync.GeData_element();
+//               if (ord.Opportunity.Dealer__r.DummyDealer__c == true){
+//               quotation.DealerCode          = ord.Opportunity.Account.ManagementCode_F__c;
+//               quotation.SalesAccountCode                   = ord.SpecialDeliveryAccount_D__r.ManagementCode_F__c;
+//               }
+//               else{
+//               quotation.DealerCode          = ord.Opportunity.Dealer__r.ManagementCode_Ext__c;
+//               quotation.SalesAccountCode                   = ord.Opportunity.Account.ManagementCode_F__c;
+
+//               }
+//               quotations.GeData.add(quotation);
+//               quotation.OrderCode                      = ord.OrderNumber;
+//               quotation.OpportunityCode                = ord.Opportunity.InquiryNumber__c;
+////                quotation.SalesAccountCode                   = ord.Opportunity.Account.ManagementCode_F__c;
+//               quotation.ProductSegment              = ord.Opportunity.ProductSegment__c;
+//               quotation.TradeType              = ord.Opportunity.TradeType__c;
+//               quotation.MachineParts                   = ord.Opportunity.Machine_Parts__c;
+//               quotation.SalesChannel   =                 ord.Opportunity.Machine_Parts__c == 'Parts' ? '40' : ord.Opportunity.SalesChannel__c == 'dealer' ?  '41' : '42';
+//               quotation.DeliveryDate          = NFMUtil.formatDate2Str(ord.Opportunity.ExpectedDeliveryDate__c);
+////                quotation.DealerCode          = ord.Opportunity.Dealer__r.ManagementCode_Ext__c;
+//               quotation.DealerSalesStaffName         = ord.Opportunity.DealerSalesStaffName__c;
+//               quotation.ForeignTradeCompany                   = ord.ForeignTradeCompany_D__r.ManagementCode_F__c;
+//               quotation.PaymentCondition                  = ord.PaymentTerms__c;
+//               quotation.EndUser            =  ord.EndUserD__r.ManagementCode_F__c;
+//               quotation.DeliveryDate = NFMUtil.formatDate2Str(ord.ExpDelDate__c);
+//               quotation.ServiceFee      =  ord.ServiceFee_D__c;
+//               //2017/01/15杩藉姞
+//               if(ord.Opportunity.SalesChannel__c == 'direct' && ord.Opportunity.Machine_Parts__c == 'Parts'){
+//                    quotation.Discount         = 0;
+//                    quotation.OlympusContractPrices = ord.CustomerContractPriceD__c;
+//               }
+//               else{
+//                   quotation.Discount         = ord.Discount_D__c;
+//                   quotation.OlympusContractPrices = ord.ContractPriceTotal__c;
+//               }
+//               quotation.SpecialDeliveryAddress                   = ord.SpecialDeliveryAccount_D__r.ManagementCode_F__c + ',' + ord.SpecialDeliveryContact2_D__r.ManagementCode_F__c;
+//               quotation.Other1            = ord.Name + ',' + ord.SalesChannel__c;
+//               quotation.Other2            = ord.SpecialCondition_text__c;
+//               quotation.Other3            = ord.Shipment_Term_D__c + ',' + ord.Shipment_Term2_D__c;
+
+//               quotation.GeDataDetails = new List<SBG027Sync.GeDataDetails_element>();
+//               //Detail_element
+//               Integer m = 0;
+//               for (Integer i = 0; i < ordLiList.size(); i++) {
+                    
+//                   if (ordLiList.get(i).Order.ProductSegment__c == 'BS') {
+
+//                       //XHL-20190510-AddStart
+//                       if (!ordLiList.get(i).ODISingleProduct__c) {
+//                           continue;
+//                       }
+//                       m++;
+//                       //XHL-20190510-AddEnd
+//                       SBG027Sync.GeDataDetails_element detail = new SBG027Sync.GeDataDetails_element();
+//                       quotation.GeDataDetails.add(detail);
+//                       detail.DetailLine                  = (i + 1) * 10;
+//                       detail.ItemCode                    = ordLiList.get(i).PricebookEntry.ProductCode;
+//                       detail.ItemQuantity                = Integer.valueOf(ordLiList.get(i).Quantity);
+//                   } else {
+
+//                       SBG027Sync.GeDataDetails_element detail = new SBG027Sync.GeDataDetails_element();
+//                       quotation.GeDataDetails.add(detail);
+//                       detail.DetailLine                  = (i + 1) * 10;
+//                       detail.ItemCode                    = ordLiList.get(i).PricebookEntry.ProductCode;
+//                       detail.ItemQuantity                = Integer.valueOf(ordLiList.get(i).Quantity);
+//                   }
+                    
+//               }
+
+//               //XHL-20190510-AddStart
+//               if (dqpsNameAndCountMap.containsKey(ord.Id)) {
+//                   value = dqpsNameAndCountMap.get(ord.Id);
+//                   List<String> nameCountList = new List<String>();
+//                   for (String str: value.split(';')){
+//                       nameCountList.add(str);
+//                   }
+//                   if (nameCountList.size() > 0 ){
+
+//                       for (String  nameCount :nameCountList) {
+
+//                           SBG027Sync.GeDataDetails_element detail = new SBG027Sync.GeDataDetails_element();
+//                           quotation.GeDataDetails.add(detail);
+//                           detail.DetailLine                  = (m + 1) * 10;
+//                           detail.ItemCode                    = nameCount.split(',')[0];
+//                           detail.ItemQuantity                = Integer.valueOf(nameCount.split(',')[1]);
+//                           m++;
+//                       }
+//                   }
+
+//               }
+//               //XHL-20190510-AddEnd
+//               logstr += quotation.OrderCode + '\n';
+//           }
+
+//           if (quotations.GeData.size() > 0) {
+//               //SBG027Sync.Quotations_element[] pQuotations = new SBG027Sync.Quotations_element[] { quotations };
+//               logstr += '\ncallout count=' + quotations.GeData.size();
+//               //OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG027_Sync_BC2GPI(pQuotations);
+//               // 鍘熷墖闈炲悓鏈熴仹銇欍伄銇с�乴ogs銈掔⒑瑾嶃仚銈嬪繀瑕併亴銇亜銇с仐銈囥亞銆�
+//               NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
+//               Monitoring.Tag                  = quotations.Monitoring.Tag;
+//               Monitoring.Sender               = quotations.Monitoring.Sender;
+//               Monitoring.Receiver             = quotations.Monitoring.Receiver;
+//               Monitoring.MessageType          = quotations.Monitoring.MessageType;
+//               Monitoring.MessageGroupNumber   = quotations.Monitoring.MessageGroupNumber;
+//               Monitoring.NumberOfRecord       = quotations.Monitoring.NumberOfRecord;
+//               Monitoring.TransmissionDateTime = quotations.Monitoring.TransmissionDateTime;
+//               Monitoring.Text = '';
+//               rowData = NFMUtil.makeRowData(Monitoring, 'SBG027', quotations);
+//               execute(rowData, iflog);
+//           }
+//           Set<String> inquiryNoList = new Set<String>();
+
+//           Map<String, Order> ordUpsertMap = new Map<String, Order>();
+//           logstr += '\nend';
+//       } catch(Exception ex) {
+//           // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+//           System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getMessage());
+//           System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getStackTraceString());
+//           logstr += ex.getMessage();
+//           iflog.ErrorLog__c += ex.getMessage() + '\n';
+//           iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+//       }
+//       if (rowData != null) {
+//           insert rowData;
+//       }
+
+//       System.debug(Logginglevel.DEBUG, 'SBG027_' + iflog.Name + ' end');
+//       iflog.Log__c = logstr;
+//       update iflog; 
+//   }  
+
+//   public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {
+//       //gaozw
+//       Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+//       String rowDataStr = NFMUtil.getRowDataStr(rowData);
+//       SBG027Sync.GeDatas_element quotations = (SBG027Sync.GeDatas_element) JSON.deserialize(rowDataStr, SBG027Sync.GeDatas_element.class);
+
+//       String logstr = quotations.Monitoring.MessageGroupNumber + ' start\n';
+//       Boolean needUpdateIflog = false;
+//       if  (iflog == null) {
+//           needUpdateIflog = true;
+//           iflog = new BatchIF_Log__c();
+//           iflog.Type__c = 'SBG027';
+//           iflog.MessageGroupNumber__c = quotations.Monitoring.MessageGroupNumber;
+//           iflog.Log__c = logstr;
+//           iflog.ErrorLog__c = '';
+//           insert iflog;
+//           iflog = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog.Id];
+//       } else {
+//           logstr = iflog.Log__c;
+//       } 
+//       try{
+//           //gaozw
+//           SBG027Sync.HTTPS_Port stub = new SBG027Sync.HTTPS_Port();
+//           stub.timeout_x = 100000; // timeout in milliseconds
+//           stub.endpoint_x = NFMUtil.SBG027_ENDPOINT;
+//           stub.inputHttpHeaders_x = new Map<String, String>();
+//           stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
+//           if (NFMUtil.CLIENT_CERT_NAME != null) {
+//               stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
+//           }
+//           SBG027Sync.GeDatas_element[] pQuotations = new SBG027Sync.GeDatas_element[] { quotations };
+//           OlympusCoJpCommonMessage.LOG_element[] logs = stub.SBG027_Sync_BC2GPI(pQuotations);
+//           rowData.retry_cnt__c=0;
+//       }catch(Exception ex) {
+//           // TODO IOException
+//           // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+//           System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getMessage());
+//           System.debug(Logginglevel.ERROR, 'SBG027_' + iflog.Name + ':' + ex.getStackTraceString());
+//           logstr += ex.getMessage();
+//           iflog.ErrorLog__c += ex.getMessage() + '\n';
+//           iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
+
+//           //---xiongyl---add
+//           if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+//           if (rowData.retry_cnt__c < batch_retry_max_cnt){
+//               rowData.retry_cnt__c++;
+//           }
+//           if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+//               rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩閫佷俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄩ�佷俊';
+//           }
+//       }
+//       iflog.Log__c = logstr;
+//       if (needUpdateIflog) {
+//           update iflog;
+//           update rowData;
+//       }
+//   }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG027TriggerHandler.cls-meta.xml b/scr/classes/SBG027TriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..4935896
--- /dev/null
+++ b/scr/classes/SBG027TriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>37.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG200Rest.cls b/scr/classes/SBG200Rest.cls
new file mode 100644
index 0000000..0398cd6
--- /dev/null
+++ b/scr/classes/SBG200Rest.cls
@@ -0,0 +1,401 @@
+@RestResource(urlMapping = '/SBG200/*')
+global with sharing class SBG200Rest {
+
+	global class GeDatas {
+		public NFMUtil.Monitoring Monitoring;
+		public GeData[] Partners;
+	}
+
+	//鍚堜綔浼欎即鎶ご灞傜骇
+	global class GeData {
+		public License_Info[] License_Info;
+
+		public String CompanyCode;		//鍏徃浠g爜
+		public Boolean IfControl;		//鏄惁涓ユ牸绠℃帶
+	}
+
+	//璇佺収灞傜骇
+	global class License_Info {
+		public Detail_Info[] Detail_Info;
+
+		public String LicenseType;		//璇佺収绫诲瀷
+		public String BusLicenseNo;		//璇佺収鍙�
+		public String ValidFrom;		//鏈熼檺鏁堟湡浠�
+		public String ValidTo;			//鏈熼檺鏁堟湡鑷�
+	}
+	//璇佺収鏄庣粏灞傜骇
+	global class Detail_Info {
+
+		public String ProName;			//瑁呯疆鍚嶇О
+		public String ProSerial;		//杈愬皠浜у搧绯诲垪
+		public String Quantity;			//鏁伴噺
+		public String Category;			//娲诲姩绉嶇被
+
+	}
+
+
+	@HttpPost
+	global static void execute() {
+		// 鍙栧緱鎺ュ彛浼犺緭鍐呭
+		String strData = RestContext.request.requestBody.toString();
+		GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
+
+		if (ges == null ) {
+			return;
+		}
+
+		NFMUtil.Monitoring Monitoring = ges.Monitoring;
+		if (Monitoring == null) {
+			return;
+		}
+
+		BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', ges.Partners);
+		if (String.isBlank(rowData.Log__c) == false) {
+			executefuture(rowData.Id);
+		}
+		// JSON銈掓埢銇�
+		RestResponse res = RestContext.response;
+		res.addHeader('Content-Type', 'application/json');
+		res.statusCode = 200;
+		String jsonResponse = '{"status": "0", "Message":""}';
+		res.responseBody = blob.valueOf(jsonResponse);
+		return;
+	}
+
+	@future
+	global static void executefuture(String rowData_Id) {
+		main(rowData_Id);
+	}
+
+	global static void main(String rowData_Id) {
+		Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+		BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+		String logstr = rowData.MessageGroupNumber__c + ' start\n';
+		BatchIF_Log__c iflog = new BatchIF_Log__c();
+		iflog.Type__c = 'SBG200';
+		iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+		iflog.Log__c = logstr;
+		iflog.ErrorLog__c = '';
+		insert iflog;
+
+		String rowDataStr = NFMUtil.getRowDataStr(rowData);
+		List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+		if (geDataList == null || geDataList.size() == 0) {
+			return;
+		}
+
+		//璇佺収杞崲琛�
+		Map<String, String> transferLicenseTypeMap = NFMUtil.BatchIF_Transfer('License_Information__c');
+		//璇佺収鏄庣粏杞崲琛�
+		Map<String, String> certificationDetailTransferMap = NFMUtil.BatchIF_Transfer('CertificationDetails__c');
+
+		Savepoint sp = Database.setSavepoint();
+		try {
+
+			List<GeData> satisfyGeDataList = SatisfyGeData(geDataList, iflog);
+
+			if ( satisfyGeDataList.size() > 0) {
+
+				Map<String, Account> accountMap = existAccountMap(satisfyGeDataList);
+
+				if ( accountMap.size() > 0 ) {
+
+					deleteAccountLicenseInformation(accountMap);
+
+					insertLicense_Information(satisfyGeDataList, accountMap, transferLicenseTypeMap, iflog, certificationDetailTransferMap);
+				} else {
+
+				}
+			}
+
+			logstr += '\nend';
+			rowData.retry_cnt__c = 0;
+
+		} catch (Exception ex) {
+
+			Database.rollback(sp);
+			System.debug(Logginglevel.ERROR, 'SBG200_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+			System.debug(Logginglevel.ERROR, 'SBG200_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+			logstr += '\n' + ex.getMessage();
+			iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+
+			if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+			if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+				rowData.retry_cnt__c++;
+				LogAutoSendSchedule.assignOneMinute();
+			}
+			if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+				rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+			}
+		}
+
+		update rowData;
+		iflog.Log__c = logstr;
+		if (iflog.Log__c.length() > 131072) {
+			iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+		}
+		if (iflog.ErrorLog__c.length() > 32768) {
+			iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+		}
+		update iflog;
+	}
+
+	public static void insertLicense_Information(List<GeData> satisfyGeDataList, Map<String, Account> existAccountMap,
+	        Map<String, String> transferLicenseTypeMap, BatchIF_Log__c iflog, Map<String, String> certificationDetailTransferMap) {
+
+		System.debug('insertLicense_Information--->Start');
+
+		Map<String, License_Info> satisfyLicenseInfoMap = new Map<String, License_Info>();
+		//Boolean ifControl = false;
+		Map<String,GeData> geDatalMap = new  Map<String,GeData>();
+		for (GeData gedata : satisfyGeDataList) {
+			geDatalMap.put(gedata.CompanyCode,gedata);
+			//ifControl = gedata.IfControl;
+			//System.label.IfControlRadiation = gedata.IfControl;
+			for (License_Info licenseInfo : gedata.License_Info) {
+
+				if (String.isBlank(licenseInfo.LicenseType) || String.isBlank(licenseInfo.BusLicenseNo) ||
+				        String.isBlank(licenseInfo.ValidFrom) || String.isBlank(licenseInfo.ValidTo)) {
+					continue;
+				}
+
+				String companyCodes = gedata.CompanyCode + ';' + licenseInfo.LicenseType;
+				satisfyLicenseInfoMap.put(companyCodes, licenseInfo);
+			}
+		}
+
+		if ( satisfyLicenseInfoMap.size() > 0 ) {
+
+			List<License_Information__c> licenseInformationList = new List<License_Information__c>();
+			List<CertificationDetails__c>  certificationDetailsList = new List<CertificationDetails__c>();
+			Map<String, List<CertificationDetails__c>> LicenseDetailsMap = new Map<String, List<CertificationDetails__c>>();
+
+			for (String companyCodes : satisfyLicenseInfoMap.keySet()) {
+
+				License_Info license = satisfyLicenseInfoMap.get(companyCodes);
+				String companyCode = companyCodes.split(';')[0];
+
+				String licenseType =  FieldTransformation(companyCode, transferLicenseTypeMap, 'LicenseType__c', license.LicenseType, iflog, 'LicenseType');
+
+				if (licenseType.equals('Invalid')) {
+					continue;
+				}
+
+				License_Information__c  licenseInformation = new License_Information__c();
+				licenseInformation.LicenseType__c = licenseType ;
+				licenseInformation.BusinessLicense__c = license.BusLicenseNo ;
+				licenseInformation.ValidFrom__c = NFMUtil.parseStr2Date(license.ValidFrom, false) ;
+				licenseInformation.ValidTo__c = NFMUtil.parseStr2Date(license.ValidTo, false) ;
+				licenseInformation.LicenseAndAccount__c = existAccountMap.get(companyCode).Id;
+				licenseInformation.Name = existAccountMap.get(companyCode).Name + licenseType;
+				//杈愬皠瀹夊叏璁稿彲璇�
+				if ( license.LicenseType == '08' && license.Detail_Info != null) {
+					licenseInformation.IfControl__c = geDatalMap.get(companyCode).IfControl;
+					LicenseDetailsMap.putAll(SatisfyLicenseDetailsMap(companyCode, license.Detail_Info, certificationDetailTransferMap, iflog));
+				}
+
+				licenseInformationList.add(licenseInformation);
+			}
+
+			if ( licenseInformationList.size() > 0 ) {
+
+				upsert licenseInformationList;
+
+				if ( LicenseDetailsMap.size() > 0) {
+
+					insertCertificationDetail(LicenseDetailsMap, licenseInformationList);
+				}
+			}
+		}
+
+		System.debug('insertLicense_Information--->End');
+	}
+	//淇濆瓨璇佺収鏄庣粏
+	public static void insertCertificationDetail (Map<String, List<CertificationDetails__c>> LicenseDetailsMap,
+	        List<License_Information__c> licenseInformationList) {
+
+		System.debug('insertCertificationDetail--->Start');
+		System.debug('LicenseDetailsMap---->' + LicenseDetailsMap);
+		List<String> licenseInformationIdList = new List<String>();
+		for (License_Information__c licenseInformation : licenseInformationList) {
+
+			if ( licenseInformation.LicenseType__c == '杈愬皠瀹夊叏璁稿彲璇�' ) {
+
+				licenseInformationIdList.add(licenseInformation.Id);
+			}
+		}
+		System.debug('licenseInformationIdList----->' + licenseInformationIdList);
+		List<License_Information__c> existList = [select id, Name, LicenseAndAccount__r.ManagementCode_Ext__c
+		        from License_Information__c where Id In :licenseInformationIdList];
+		Map<String, License_Information__c> existLicenseInformationMap = new Map<String, License_Information__c>();
+		System.debug('existList---->' + existList);
+		for (License_Information__c licenseInformation : existList) {
+
+			String accountManagementCode = licenseInformation.LicenseAndAccount__r.ManagementCode_Ext__c;
+			existLicenseInformationMap.put(accountManagementCode, licenseInformation);
+		}
+		System.debug('existLicenseInformationMap---->' + existLicenseInformationMap);
+		List<CertificationDetails__c> insertCertificationDetailList = new List<CertificationDetails__c>();
+		for ( String companyCode : LicenseDetailsMap.keySet()) {
+
+			for ( CertificationDetails__c certificationDetail : LicenseDetailsMap.get(companyCode)) {
+
+				if (existLicenseInformationMap.containsKey(companyCode)) {
+
+					certificationDetail.LicenseInformation__c = existLicenseInformationMap.get(companyCode).Id;
+					insertCertificationDetailList.add(certificationDetail);
+				}
+
+			}
+		}
+		System.debug('insertCertificationDetailList----->' + insertCertificationDetailList);
+
+		if (insertCertificationDetailList.size() > 0) {
+
+			upsert insertCertificationDetailList;
+		}
+
+
+		System.debug('insertCertificationDetail--->End');
+	}
+
+	//鑾峰彇绗﹀悎鐨勮瘉鐓ф槑缁�,骞剁粰璇佺収鏄庣粏璧嬪��
+	public static Map<String, List<CertificationDetails__c>> SatisfyLicenseDetailsMap(String  companyCode,
+	        List<Detail_Info> licenseDetailS, Map<String, String> certificationDetailTransferMap, BatchIF_Log__c iflog) {
+
+		System.debug('SatisfyLicenseDetailsMap--->Start');
+		Map<String, CertificationDetails__c> certificationDetailMap = new Map<String, CertificationDetails__c>();
+		Map<String, List<CertificationDetails__c>> result = new Map<String, List<CertificationDetails__c>>();
+		List<CertificationDetails__c> certificationDetailList = new List<CertificationDetails__c>();
+		for (Detail_Info detailInfo : licenseDetailS) {
+
+			if (String.isBlank(detailInfo.ProSerial) || String.isBlank(detailInfo.Quantity) ||
+			        String.isBlank(detailInfo.Category)  ) {
+
+				continue;
+			}
+
+			String licenseType =  FieldTransformation(companyCode, certificationDetailTransferMap, 'ProdustionType__c', detailInfo.ProSerial, iflog, 'ProSerial');
+			if (licenseType.equals('Invalid')) {
+				continue;
+			}
+			//String licenseType =  FieldTransformation(bpCode, certificationDetailTransferMap, 'ProductModel__c', detailInfo.ProSerial, iflog, 'ProSerial');
+			Integer quantity = Integer.valueof(detailInfo.Quantity);
+			String  remarks = detailInfo.ProName + '(' + quantity + ')';
+			String key = licenseType + '-' + detailInfo.Category;
+			if (!certificationDetailMap.containsKey(key)) {
+
+				//CertificationDetails__c detail = new CertificationDetails__c();
+				//detail.ProductModel__c = licenseType;
+				//detail.ProductModelNumber__c = Integer.valueOf(detailInfo.Quantity);
+				//detail.ActivitieTypes__c = detailInfo.Category;
+				//detail.DeviceName__c = detailInfo.ProName;
+				CertificationDetails__c detail = new CertificationDetails__c();
+				detail.ProdustionType__c = licenseType;
+				detail.ProductModelNumber__c = quantity;
+				detail.ActivitieTypes__c = detailInfo.Category;
+				detail.DeviceName__c = detailInfo.ProName;
+				detail.Remarks__c = remarks;
+				certificationDetailMap.put(key, detail);
+			} else {
+				certificationDetailMap.get(key).ProductModelNumber__c += quantity;
+				certificationDetailMap.get(key).DeviceName__c += '/' + detailInfo.ProName;
+				certificationDetailMap.get(key).Remarks__c += '/' + remarks;
+
+			}
+			
+		}
+		if ( certificationDetailMap.size() > 0 ) {
+			for (CertificationDetails__c detail : certificationDetailMap.values()) {
+				//result.add(detail);
+				certificationDetailList.add(detail);
+			}
+		}
+
+		result.put(companyCode, certificationDetailList);
+		System.debug('SatisfyLicenseDetailsMap--->End');
+		return result;
+	}
+
+	public static Map<String, Account> existAccountMap(List<GeData> satisfyGeDataList) {
+
+		System.debug('existAccountMap--->Start');
+		//鏇存柊瀹㈡埛锛屽悓鏃惰幏鍙栧鎴风殑缂栫爜鍜孖d
+		Map<String, Account> result = new Map<String, Account>();
+		Map<String, GeData> companyCodeMap = new Map<String, GeData>();
+
+		for (GeData gedata : satisfyGeDataList) {
+
+			companyCodeMap.put(geData.CompanyCode, gedata);
+		}
+
+		List<Account> existAccountList = [select Id, Name, ManagementCode_Ext__c
+		                                  from Account where ManagementCode_Ext__c In :companyCodeMap.keySet()];
+		if ( existAccountList.size() > 0) {
+
+			for (Account account : existAccountList) {
+
+				//if (companyCodeMap.containsKey(account.ManagementCode_Ext__c)) {
+
+				//	//鏇存柊瀹㈡埛"鏄惁涓ユ牸绠℃帶"瀛楁
+				//	account.IfControl__c = companyCodeMap.get(account.ManagementCode_Ext__c).IfControl;
+				//}
+
+				result.put(account.ManagementCode_Ext__c, account);
+			}
+
+			//upsert existAccountList;
+		}
+		System.debug('existAccountMap--->End');
+		return result;
+	}
+
+	public static List<GeData> SatisfyGeData( List<GeData> geDataList, BatchIF_Log__c iflog) {
+
+		List<GeData> result = new List<GeData>();
+		for (GeData geData : geDataList) {
+
+			if (String.isBlank(geData.CompanyCode)) {
+
+				iflog.ErrorLog__c += 'CompanyCode of is required,This data is skipped.\n';
+				continue;
+			}
+
+			if (gedata.License_Info == null) {
+				continue;
+			}
+
+			result.add(geData);
+		}
+
+		return result;
+	}
+
+	//杞崲鍓嶅悗鐨勫�肩殑瀵规瘮
+	public static String FieldTransformation(String bpCode, Map<String, String> transformation, String api, String toConvertStr, BatchIF_Log__c iflog, String receivesField ) {
+		String afterTransformation = NFMUtil.getMapValue(transformation, api, toConvertStr, iflog);
+
+		if (String.isNotBlank(afterTransformation) && !afterTransformation.equals(toConvertStr)) {
+
+			return afterTransformation;
+		}  else if (String.isNotBlank(afterTransformation) && afterTransformation.equals(toConvertStr)) {
+			return afterTransformation;
+		} else {
+
+			iflog.ErrorLog__c += 'BPCode[ ' + bpCode + ' ] of ' + receivesField + ' [ ' + toConvertStr + ' ]' + ' is  Invalid,This data is skipped.\n';
+			return 'Invalid';
+		}
+	}
+
+	public static void deleteAccountLicenseInformation(Map<String, Account> accountMap) {
+
+		System.debug('deleteAccountLicenseInformation--->Start');
+		List<License_Information__c> existList = [select id, Name, AccountManagementCode__c
+		        from License_Information__c where AccountManagementCode__c In :accountMap.keySet()];
+
+		if (existList.size() > 0) {
+			delete existList;
+		}
+		System.debug('deleteAccountLicenseInformation--->End');
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/SBG200Rest.cls-meta.xml b/scr/classes/SBG200Rest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG200Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG200RestTest.cls b/scr/classes/SBG200RestTest.cls
new file mode 100644
index 0000000..d1ec365
--- /dev/null
+++ b/scr/classes/SBG200RestTest.cls
@@ -0,0 +1,218 @@
+@isTest
+private class SBG200RestTest {
+
+    public static Account acc1;
+    public static Account acc2;
+    public static Account acc3;
+    public static Account acc4;
+
+    public static Contact core;
+    public static License_Information__c licenseInformation;
+
+    static void inittransfersData() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '5111'
+        );
+        Account acc2 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '5112'
+        );
+        Account acc3 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            CancelReason__c = 'test',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '5003'
+        );
+
+        Account acc4 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '300220'
+        );
+
+        insert new List<Account> {acc1, acc2, acc3,acc4};
+
+        License_Information__c licenseInformation = new License_Information__c();
+        licenseInformation.LicenseType__c = '杈愬皠瀹夊叏璁稿彲璇�' ;
+		licenseInformation.BusinessLicense__c = 'TestNo20191216' ;
+		licenseInformation.ValidFrom__c = Date.today().addDays(-22);
+		licenseInformation.ValidTo__c = Date.today().addDays(22);
+		licenseInformation.LicenseAndAccount__c = acc1.Id;
+		licenseInformation.Name = 'test01'+'杈愬皠瀹夊叏璁稿彲璇�';
+
+		insert licenseInformation;
+
+        List<BatchIF_Transfer__c> transfers = new List<BatchIF_Transfer__c>();
+        BatchIF_Transfer__c transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'Dealer_Type__c';
+        transfer.External_Value__c = '22';
+        transfer.Internal_Value__c = 'Authorize dealer';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'License_Information__c';
+        transfer.Column__c         = 'LicenseType__c';
+        transfer.External_Value__c = '01';
+        transfer.Internal_Value__c = '钀ヤ笟鎵х収';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'License_Information__c';
+        transfer.Column__c         = 'LicenseType__c';
+        transfer.External_Value__c = '08';
+        transfer.Internal_Value__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        transfers.add(transfer);
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProdustionType__c';
+        transfer.External_Value__c = 'D';
+        transfer.Internal_Value__c = 'Delta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProdustionType__c';
+        transfer.External_Value__c = 'V';
+        transfer.Internal_Value__c = 'Venta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProdustionType__c';
+        transfer.External_Value__c = 'DV';
+        transfer.Internal_Value__c = 'Delta+Venta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProdustionType__c';
+        transfer.External_Value__c = 'F';
+        transfer.Internal_Value__c = 'FOX-IQ';
+        transfers.add(transfer);
+
+        insert transfers;
+
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=acc1.id,ManagementCode_Ext__c = 'C100300X');
+        insert core;
+
+    }
+
+    static testMethod void testMethod1() {
+        inittransfersData();
+        SBG200Rest.GeDatas GeDatas = new  SBG200Rest.GeDatas();
+        SBG200Rest.GeData GeData = new  SBG200Rest.GeData();
+        SBG200Rest.License_Info License_Info01 = new  SBG200Rest.License_Info();
+        SBG200Rest.Detail_Info Detail_Info01 = new SBG200Rest.Detail_Info();
+        SBG200Rest.Detail_Info Detail_Info05 = new SBG200Rest.Detail_Info();
+        GeDatas.Partners = new  SBG200Rest.GeData[] {GeData};
+        GeData.License_Info = new  SBG200Rest.License_Info[] {License_Info01};
+        License_Info01.Detail_Info = new SBG200Rest.Detail_Info[] {Detail_Info01,Detail_Info05};
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+
+        GeData.CompanyCode = '';
+        GeData.IfControl = false;
+
+        License_Info01.LicenseType = '08';
+        License_Info01.BusLicenseNo = '20161101';
+        License_Info01.ValidFrom = '20180522';
+        License_Info01.ValidTo = null;
+        Detail_Info01.ProName = 'test01';
+        Detail_Info01.ProSerial = 'V';
+        Detail_Info01.Quantity = '222';
+        Detail_Info01.Category = '';
+
+        Detail_Info05.ProName = 'test02';
+        Detail_Info05.ProSerial = 'DV';
+        Detail_Info05.Quantity = '222';
+        Detail_Info05.Category = '';
+
+
+        System.Test.startTest();
+        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+
+        GeData.CompanyCode = '5111';
+        rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+
+        License_Info01.ValidTo = '20220522';
+        rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+
+        Detail_Info01.Category = '閿�鍞�';
+        Detail_Info05.Category = '浣跨敤';
+        rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+
+        License_Info01.LicenseType = '22';
+        rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+
+        License_Info01.LicenseType = '08';
+        Detail_Info01.ProSerial = 'Z';
+        rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+
+        License_Info01.LicenseType = '08';
+        Detail_Info01.ProSerial = 'F';
+        Detail_Info01.ProName = '2018052201201805220120180522012018052201201805220120180522012018052201201805220120180522012018052201' +
+        						'2018052201201805220120180522012018052201201805220120180522012018052201201805220120180522012018052201' +
+        						'2018052201201805220120180522012018052201201805220120180522012018052201201805220120180522012018052201';
+        rowData = NFMUtil.saveRowData(Monitoring, 'SBG200', GeDatas.Partners);
+        SBG200Rest.main(rowData.Id);
+        System.Test.stopTest();
+    }
+
+    @isTest
+    static void testMethod4() {
+        //娴嬭瘯 SBG200Rest.execute();
+        Test.startTest();
+
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+
+        String JsonMsg = '{"Monitoring":{"TransmissionDateTime":"201812201320","Text":"","Tag":"MSGH","Sender":"SFDC","Receiver":"SPO","NumberOfRecord":"1","MessageType":"SBG200","MessageGroupNumber":"20180001722190"},"Partners":[{"CompanyCode":"5111","IfControl":true,"License_Info":[{"Detail_Info":[{"ProName":"Test01","ProSerial":"D","Quantity":"22","Category":"閿�鍞�"},{"ProName":"Test02","ProSerial":"V","Quantity":"222","Category":"閿�鍞�"}],"LicenseType":"08","ValidTo":"20191118","ValidFrom":"20191104","BusLicenseNo":"纾婃床鍑ょ336鍙�"},{"Detail_Info":null,"LicenseType":"01","ValidTo":"99991231","ValidFrom":"20171117","BusLicenseNo":"91510100LEIZHOU"}]}]}';
+        req.requestURI = 'services/apexrest/SBG200/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response = res;
+
+        SBG200Rest.execute();
+
+        Test.stopTest();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG200RestTest.cls-meta.xml b/scr/classes/SBG200RestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG200RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG203Rest.cls b/scr/classes/SBG203Rest.cls
new file mode 100644
index 0000000..2d69b2c
--- /dev/null
+++ b/scr/classes/SBG203Rest.cls
@@ -0,0 +1,1682 @@
+@RestResource(urlMapping = '/SBG203/*')
+global with sharing class SBG203Rest {
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData[] Partners;
+    }
+    //鍚堜綔浼欎即鎶ご灞傜骇
+    global class GeData {
+        public License_Info[] License_Info;
+        public Consignee_Info[] Consignee_Info;
+        public Contract_Info[] Contract_Info;
+        public Authorized_Info[] Authorized_Info;
+
+        public String AgentType; //缁忛攢鍟嗗垎绫�
+        public String CompanyName; //浼佷笟鍚嶇О
+        public String CompanyEnglishName; //浼佷笟鍚嶇О锛堣嫳鏂囷級
+        public String DealerTradeType; //浠g悊鍟嗚锤鏄撶被鍨�
+        public String Mobilephone; //鍚堜綔浼欎即鎵嬫満
+        public String ProductSegment; //浜у搧鍒嗙被
+        public String KeyAccount; //鍏抽敭瀹㈡埛
+        public String ExportRegulatedCustomer; //鍑哄彛闄愬埗鐢ㄦ埛
+        public String MarketVerticals; //甯傚満鍒嗙被
+        public String Industry; //琛屼笟
+        public String Use; //鐢ㄩ��
+        public String SubUseEnterprise; //鍏ㄥ浗浼佷笟鐢ㄦ埛鐨凷ubUse
+        public String BPCode; //鍚堜綔浼欎即浠g爜(BS璇剧◣锛屽叾浠栧垎閲庡叕鐢�)
+        public String BPCodeforeign; //鍏嶇◣
+        public String BPType; //鍚堜綔浼欎即绫诲瀷
+        public String RegisterAddress; //浣忔墍(绛夊悓娉ㄥ唽鍦板潃)
+        public String RegionName; //鐪佸埆
+        public String City; //甯�
+        public String Phone; //鍚堜綔浼欎即鐢佃瘽
+        public String Postal; //鍚堜綔浼欎即閭紪
+        public String Fax; //鍚堜綔浼欎即浼犵湡
+        public String Region; //鐪佸埆()
+        public String ApplyType;
+        // 1.瀹㈡埛缁堟(鏇存柊瀹㈡埛)銆�2.鏂板(鍒涘缓-瀹㈡埛锛岃仈绯讳汉锛屼唬鐞嗗晢鎶樻墸锛岃瘉鐓х瓑)銆�3.鍙樻洿( 鍚屾柊澧�)銆�4.缁害(鍚屾柊澧�)銆�6.鍗忚鍙樻洿(瀹㈡埛锛屼唬鐞嗗晢鎶樻墸)銆�7.璇佺収鍙樻洿(瀹㈡埛锛岃瘉鐓э紝鑱旂郴浜�)銆�8.鏀惰揣淇℃伅鍙樻洿(瀹㈡埛锛岃仈绯讳汉)
+        public String STR_SUPPL1; //寮�绁ㄥ湴鍧�锛�80锛�
+
+        public String VTWEG; //鍒嗛攢娓犻亾
+        public String AccountSource; //瀹㈡埛鏉ユ簮
+        public Boolean TargetCustomer; //瀹㈡埛绫诲瀷
+        public Boolean IsCOMPO; //COMPO瀹㈡埛
+        public String UserType; //鐢ㄦ埛灞炴��
+        public String COMPOSubuse; //Subuse
+
+        public String KATR2; //寮�绁ㄧ被鍨�
+        public String CompanyCode; //鍏徃浠g爜
+        public String Incorporator; //娉曞畾浠h〃浜�(鍖婚櫌)
+        public String Invoice_phone; //寮�绁ㄨ仈绯荤數璇�
+        public String AgentValidFrom;
+        public String AgentValidTo;
+        public String TaxNo;
+        public String BankName;
+        public String BankCode;
+        public String Agreement1;
+        public String Agreement2;
+        public String Agreement3;
+        public String Agreement4;
+        public String Remark;
+        public String Z3PLAuthorizedNo;
+        public String AuthorizedScope;
+        public String AuthorizedVF;
+        public String AuthorizedVT;
+        public String CNTag;
+        public String Z3PLQualityAgrNo;
+        public String QualityAgrNoVF;
+        public String QualityAgrNoVT;
+        public String Z3PLTransAgrNo;
+        public String TransAgrVF;
+        public String TransAgrVT;
+        public String ServiceType;
+        public String CustomerService;
+        public String OperationProject;
+        public String Approver;
+        public String ApproveDate;
+        public String Comment;
+
+        public String other1;
+        public String other2;
+        public String other3;
+    }
+
+    // 璇佺収灞傜骇
+    global class License_Info {
+        public Detail_Info[] Detail_Info;
+
+        public String LicenseType; //璇佺収绫诲瀷
+        public String BusLicenseNo; //璇佺収鍙�
+        public String ValidFrom; //鏈熼檺鏁堟湡浠�
+        public String ValidTo; //鏈熼檺鏁堟湡鑷�
+        public String WarehouseAddress; //搴撴埧鍦板潃
+        public Boolean IfQuantityCtrl; //鏄惁鏁伴噺绠℃帶
+        //浠ヤ笅瀛楁鏆傛椂鐢ㄤ笉鍒�
+        public String ISSUEDATE1; //璇佺収鐨勫彂璇佹棩鏈�
+        public String DiagnosisScope; //璇婄枟绉戠洰
+        public String BusinessType; //缁忚惀鏂瑰紡
+        public String Principal; //浼佷笟璐熻矗浜�
+        public String BusinessAddress; //缁忚惀鍦烘墍锛堢瓑鍚屽姙鍏湴鍧�锛�
+        public String BusinessScope; //缁忚惀浜岀被鑼冨洿
+        public String BusinessScope1; //缁忚惀涓夌被鑼冨洿
+        public string IssueAuthority; //鍙戣瘉鏈哄叧
+        public String Exclusive; //浜岀被缁忚惀鑼冨洿鎺掗櫎瀛愬垎绫�
+        public String Exclusive1; //涓夌被缁忚惀鑼冨洿鎺掗櫎瀛愬垎绫�
+        public String other4;
+        public String other5;
+        public String other6;
+
+    }
+
+    global class Detail_Info {
+        public String ProSerial; //杈愬皠浜у搧绯诲垪
+        public String Quantity; //鏁伴噺
+        public String ProName; //瑁呯疆鍚嶇О
+        public String Category; //娲诲姩绉嶇被
+    }
+    // 鏀惰揣浜哄眰绾�
+    global class Consignee_Info {
+        public String ContactId; //鏀惰揣浜篒D(绠$悊缂栫爜)
+        public String ContactName; //鏈夋晥鏀惰揣浜哄悕绉�
+        public String ContactPhone; //鏀惰揣浜虹數璇�
+        public String PostalCode; //閭斂缂栫爜
+        public String ContactAddress; //鏈夋晥鏀惰揣浜哄湴鍧�
+        public String ContactMobilePhone; //鏀惰揣浜烘墜鏈�
+        public String CITY1; //鏀惰揣浜哄煄甯�
+        public String ContactEnglishName; //鑻辨枃鍚嶇О
+    }
+
+    // 閿�鍞汉灞傜骇
+    global class Authorized_Info {
+        public String SalesAuthorizedNo;
+        public String SalesMan;
+        public String SalesAuthorizedVF;
+        public String SalesAuthorizedVT;
+    }
+
+    // 鍚堝悓灞傜骇
+    global class Contract_Info {
+
+        public String ContractStartDate; //鍚堝悓寮�濮嬫棩
+        public String ContractEndDate; //鍚堝悓缁撴潫鏃�
+        public String DealerRank;
+        public String SubUse;
+        public String ContractRegion; //璐熻矗鐪�
+        public String DealerRate; //浠g悊鍟嗘姌鎵�
+
+        //浠ヤ笅瀛楁鏆傛椂涓嶄細浼犺緭鏁版嵁
+        public String TermContractNo; //鏈湡鍗忚缂栧彿
+        public String ContractOwner; //瀹㈡埛鎵�鏈変汉
+        public String ContractDecideStartDate; //鍏佽鎶ヤ环鏈熼棿(寮�濮嬫棩)
+        public String ContractDecideEndDate; //鍏佽鎶ヤ环鏈熼棿(缁撴潫鏃�)
+        public String BusinessAssistant; //钀ヤ笟鍔╃悊
+        public String SalesState; //鐢宠鐪�
+        public String SalesShopClass; //缁忛攢鍟嗗悎鍚屽垎绫�
+        public String ContractDepartmentClass; //鎷呭綋绉戝鍒嗙被
+        public String AgencyApplicationDay; //鐗圭害缁忛攢鍟嗙敵璇锋棩
+        public String AgencyApplicationNo; //鐗圭害缁忛攢鍟嗙敵璇风紪鐮�
+        public String SalesSection; //鐢宠閿�鍞
+        public String SelableProduct; //鎷呭綋浜у搧
+        public Double AimPrice; //鐩爣閲戦
+        public Double AimPriceAreaET; //ET鐩爣閲戦
+        public Double AimPriceAreaSP; //SP鑰楁潗鐩爣閲戦
+        public Double AimPriceAreaENG; //ENG鐩爣閲戦
+        public Double AimPriceAH; //濂ヨ緣鐩爣閲戦
+        public Double AimPriceSP; //SP鐩爣閲戦
+        public Double AimPriceGIR; //GIR鐩爣閲戦
+        public Double DealerdiscountET; //缁忛攢鍟嗘姌鎵T
+        public Double DealerdiscountENG; //缁忛攢鍟嗘姌鎵NG
+        public Double DealerdiscountSP; //缁忛攢鍟嗘姌鎵P
+        public Double DealerdiscountAH; //缁忛攢鍟嗘姌鎵eゥ杈�
+        public Double DealerdiscountBF; //缁忛攢鍟嗘姌鎵F
+        public Double DealerdiscountENF; //缁忛攢鍟嗘姌鎵NF
+        public Double DealerdiscountGI; //缁忛攢鍟嗘姌鎵I
+        public Double DealerdiscountGS; //缁忛攢鍟嗘姌鎵S
+        public Double DealerdiscountGYN; //缁忛攢鍟嗘姌鎵YN
+        public Double DealerdiscountOTH; //缁忛攢鍟嗘姌鎵TH
+        public Double DealerdiscountURO; //缁忛攢鍟嗘姌鎵RO
+        public Double DealerdiscountZF; //缁忛攢鍟嗘姌鎵f斂搴滈」鐩�
+        public String AimDivision; //鐩爣鍖哄垎
+
+    }
+
+    @HttpPost
+    global static void execute() {
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
+
+        if (ges == null) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG203', ges.Partners);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        String jsonResponse = '{"status": "0", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id =: rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG203';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List < GeData > geDataList = (List < GeData > ) JSON.deserialize(rowDataStr, List < GeData > .class);
+        if (geDataList == null || geDataList.size() == 0) {
+            return;
+        }
+        //瀹㈡埛杞崲琛�
+        Map < String, String > transferMap = NFMUtil.BatchIF_Transfer('Account');
+
+        //璇佺収杞崲琛�
+        Map < String, String > transferLicenseTypeMap = NFMUtil.BatchIF_Transfer('License_Information__c');
+
+        //璇佺収鏄庣粏杞崲琛�
+        Map < String, String > certificationDetailTransferMap = NFMUtil.BatchIF_Transfer('CertificationDetails__c');
+
+        // 鏌ユ壘瀹㈡埛鐨勫叏閮ㄨ褰曠被鍨�
+        Map < String, String > accountRecordTypeMap = getRecordTypeMap();
+        Savepoint sp = Database.setSavepoint();
+        try {
+
+            //婊¤冻鏉′欢鐨凣eData
+            List < GeData > satisfyGeData = SatisfyGeData(geDataList, iflog);
+
+            //鏍规嵁bPCodeList鏌ユ壘瀛樺湪鐨凙ccount
+            Map < String, Account > existAccountMap = ExistAccount(satisfyGeData, iflog);
+
+            List < Account > upsertAccountList = new List < Account > ();
+            Map < String, String > licenseChangeNotNullMap = new Map < String, String > ();
+            if (satisfyGeData.size() > 0) {
+
+                //鑰冭檻鏄惁鏄疊S缁忛攢鍟�
+                //瀛樺湪鐨凚S缁忛攢鍟�
+                Map < String, GeData > existBSAccountMap = new Map < String, GeData > ();
+                //涓嶅瓨鍦ㄧ殑BS缁忛攢鍟�
+                Map < String, GeData > notExistBSAccountMap = new Map < String, GeData > ();
+                //淇濆瓨BS缁忛攢鍟�
+                Map < String, Account > insertBSAccountMap = new Map < String, Account > ();
+                Boolean executeFlag = true;
+                for (GeData gda: satisfyGeData) {
+
+                    Account accountInfo = new Account();
+
+                    String transformProductSegment = gda.ProductSegment == 'LS' ? 'BS' : gda.ProductSegment; //gda.ProductSegment.split(':')[0];//FieldTransformation(gda.BPCode,transferMap, 'ProductSegment__c', gda.ProductSegment, iflog,'ProductSegment');
+
+                    if (existAccountMap.containsKey(gda.BPCode) && gda.BPType == '23' && transformProductSegment == 'BS') {
+                        //BS浠g悊鍟�-BPCode(璇剧◣)瀛樺湪
+
+                        if (existAccountMap.containsKey(gda.BPCodeforeign)) { //鍙樻洿BS浠g悊鍟�
+                            //BS浠g悊鍟�-BPCode(鍏嶇◣)瀛樺湪
+
+                            //鑾峰彇璇剧◣浠g悊鍟咺d
+                            existBSAccountMap.put(existAccountMap.get(gda.BPCode).Id + ';' + gda.BPCode + ';' + existAccountMap.get(gda.BPCode).Name, gda);
+                            //鑾峰彇鍏嶇◣浠g悊鍟咺d
+                            existBSAccountMap.put(existAccountMap.get(gda.BPCodeforeign).Id + ';' + gda.BPCodeforeign + ';' + existAccountMap.get(gda.BPCodeforeign).Name, gda);
+                            //鑾峰彇姣嶅叕鍙窱d
+                            existBSAccountMap.put(existAccountMap.get(gda.BPCode).ParentId + ';' + gda.BPCode + ':' + gda.BPCodeforeign + ';' + existAccountMap.get(gda.BPCode).Parent.Name, gda);
+                            //licenseChangeNotNullMap.put(gda.BPCodeforeign,gda.ApplyType);
+                            licenseChangeNotNullMap.put(gda.BPCode + ':' + gda.BPCodeforeign, gda.ApplyType);
+                        } else {
+                            //BS浠g悊鍟�-BPCode(璇剧◣)瀛樺湪锛孊S浠g悊鍟�-BPCodeforeign(鍏嶇◣)涓嶅瓨鍦�
+                            iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of BPCodeforeign is inexistence,This data is skipped.\n';
+                            executeFlag = false;
+                            continue;
+                        }
+                        logstr = GetLog(logstr, gda);
+
+                    } else if (gda.BPType == '23' && transformProductSegment == 'BS') {
+                        //鏂板BS浠g悊鍟�
+                        accountInfo.BS_Children_Code__c = gda.BPCode + ':' + gda.BPCodeforeign;
+                        accountInfo = AccountValueAssignment(gda, accountInfo, transferMap, accountRecordTypeMap, iflog);
+                        String dealerType = FieldTransformation(gda.BPCode, transferMap, 'Dealer_Type__c', gda.AgentType, iflog, 'AgentType');
+
+                        if (!dealerType.equals('Invalid')) {
+                            accountInfo.Dealer_Type__c = dealerType;
+                            //鏂板BS浠g悊鍟嗕腑鐨勬瘝鍏徃
+                            insertBSAccountMap.put(accountInfo.BS_Children_Code__c, accountInfo);
+                            //鏂板BS浠g悊鍟嗕腑鐨勫瓙鍏徃
+                            notExistBSAccountMap.put(gda.BPCode, gda);
+                            notExistBSAccountMap.put(gda.BPCodeforeign, gda);
+                            notExistBSAccountMap.put(accountInfo.BS_Children_Code__c, gda);
+                        } else {
+                            executeFlag = false;
+                            continue;
+                        }
+                        logstr = GetLog(logstr, gda);
+                    }
+                }
+
+                //鍙樻洿BS浠g悊鍟�
+                if (existBSAccountMap.size() > 0) {
+
+                    List < Account > updateBsChildrenAccountList = new List < Account > ();
+                    for (String accountId: existBSAccountMap.keySet()) {
+
+                        GeData gda = existBSAccountMap.get(accountId);
+
+                        Account accountInfo = new Account();
+                        accountInfo.Id = accountId.split(';')[0];
+                        accountInfo = AccountValueAssignment(gda, accountInfo, transferMap, accountRecordTypeMap, iflog);
+                        String dealerType = FieldTransformation(gda.BPCode, transferMap, 'Dealer_Type__c', gda.AgentType, iflog, 'AgentType');
+
+                        if (dealerType.equals('Invalid')) {
+                            executeFlag = false;
+                            continue;
+                        }
+                        accountInfo.Dealer_Type__c = dealerType;
+                        String bpCodeDutyFreeCode = gda.BPCode + ':' + gda.BPCodeforeign;
+                        if (accountId.split(';')[1] == bpCodeDutyFreeCode) { //BS浠g悊鍟嗘瘝鍏徃鏇村悕
+                            accountInfo.Name = gda.CompanyName + '(P)';
+                        } else { //BS浠g悊鍟嗗瓙鍏徃鏇村悕
+
+                            accountInfo.Name = gda.CompanyName;
+                        }
+                        updateBsChildrenAccountList.add(accountInfo);
+
+                    }
+
+                    //璺宠繃SBG001鎺ュ彛
+                    if (updateBsChildrenAccountList.size() > 0) {
+                        NFMUtil.EscapeSBG001TriggerHandler = true;
+                        update updateBsChildrenAccountList;
+                    }
+
+                }
+                //鏂板BS浠g悊鍟�
+                if (insertBSAccountMap.size() > 0) {
+                    insert insertBSAccountMap.values();
+
+                    List < Account > bsAccountPList = [Select Id, Name, BS_Children_Code__c from Account where BS_Children_Code__c In: insertBSAccountMap.keySet()];
+
+                    if (bsAccountPList.size() > 0) {
+
+                        List < Account > insertBsChildrenAccountList = new List < Account > ();
+
+                        for (Account acc: bsAccountPList) {
+
+                            String parentId = acc.Id;
+                            String parentName = acc.Name;
+                            String bsChildrenCode = acc.BS_Children_Code__c;
+
+                            if (notExistBSAccountMap.containsKey(bsChildrenCode)) {
+                                Integer no = 0;
+                                for (String bpCode: bsChildrenCode.split(':')) {
+
+                                    GeData gda = notExistBSAccountMap.get(bpCode);
+                                    Account accountInfo = new Account();
+
+                                    accountInfo.ManagementCode_Ext__c = bpCode;
+                                    accountInfo.ParentId = parentId;
+                                    accountInfo = AccountValueAssignment(gda, accountInfo, transferMap, accountRecordTypeMap, iflog);
+                                    if (no == 0) {
+                                        //璇剧◣浠g悊鍟�
+                                        accountInfo.DealerTradeType__c = NFMUtil.getMapValue(transferMap, 'DealerTradeType__c', '11', iflog);
+                                    } else {
+                                        //鍏嶇◣浠g悊鍟�
+                                        accountInfo.DealerTradeType__c = NFMUtil.getMapValue(transferMap, 'DealerTradeType__c', '12', iflog);
+                                    }
+
+                                    insertBsChildrenAccountList.add(accountInfo);
+                                    no++;
+
+                                }
+                            }
+                        }
+
+                        if (insertBsChildrenAccountList.size() > 0) {
+                            NFMUtil.EscapeSBG001TriggerHandler = true;
+                            insert insertBsChildrenAccountList;
+                        }
+
+                    }
+                }
+
+                //鏂板鎴栧彉鏇村叾瀹冪被鍨嬬殑瀹㈡埛
+                for (GeData gda: satisfyGeData) {
+                    String transformProductSegment = gda.ProductSegment == 'LS' ? 'BS' : gda.ProductSegment;
+                    if (gda.BPType == '23' && transformProductSegment == 'BS') {
+                        continue;
+                    }
+
+                    Account accountInfo = new Account();
+
+                    if (existAccountMap.containsKey(gda.BPCode)) {
+
+                        accountInfo = existAccountMap.get(gda.BPCode);
+                        licenseChangeNotNullMap.put(gda.BPCode, gda.ApplyType);
+                    } else {
+
+                        accountInfo.ManagementCode_Ext__c = gda.BPCode;
+                    }
+
+                    if (gda.BPType == '23') {
+                        String dealerType = FieldTransformation(gda.BPCode, transferMap, 'Dealer_Type__c', gda.AgentType, iflog, 'AgentType');
+
+                        if (dealerType.equals('Invalid')) {
+                            executeFlag = false;
+                        }
+                    }
+
+                    if (gda.BPType == '22') {
+                        accountInfo.RecordTypeId = '01228000000TF3Q'; //澶栬锤鍏徃
+                    } else if (gda.BPType == '23') {
+
+                        accountInfo.DealerTradeType__c = NFMUtil.getMapValue(transferMap, 'DealerTradeType__c', '13', iflog);
+
+                    } else if (gda.BPType == '24') { //鍏ㄥ浗浼佷笟鐢ㄦ埛(澶у鎴�)
+
+                        if ('42'.equals(gda.VTWEG)) {
+                            Map < String, String > subuseMap = getSubuseMap();
+
+                            if (!subuseMap.containsKey(gda.COMPOSubuse)) {
+                                iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of  COMPOSubuse  [ ' + gda.COMPOSubuse + ' ]' + ' is  Invalid,This data is skipped.\n';
+                                executeFlag = false;
+                            }
+
+                        } else {
+                            String keyAccount = FieldTransformation(gda.BPCode, transferMap, 'KeyAccount__c', gda.KeyAccount, iflog, 'KeyAccount');
+
+                            if (keyAccount.equals('Invalid')) {
+                                executeFlag = false;
+                            }
+                            String marketVerticals = FieldTransformation(gda.BPCode, transferMap, 'MarketVerticals__c', gda.MarketVerticals, iflog, 'MarketVerticals');
+
+                            if (marketVerticals.equals('Invalid')) {
+                                executeFlag = false;
+                            }
+                            String use = FieldTransformation(gda.BPCode, transferMap, 'Use__c', gda.Use, iflog, 'Use');
+                            if (use.equals('Invalid')) {
+                                executeFlag = false;
+                            }
+
+                            String industry = FieldTransformation(gda.BPCode, transferMap, 'IndustryC__c', gda.Industry, iflog, 'Industry');
+                            if (industry.equals('Invalid')) {
+                                executeFlag = false;
+                            }
+                        }
+
+
+                    }
+
+                    if (!executeFlag) {
+                        continue;
+                    }
+                    accountInfo = AccountValueAssignment(gda, accountInfo, transferMap, accountRecordTypeMap, iflog);
+                    upsertAccountList.add(accountInfo);
+                    logstr = GetLog(logstr, gda);
+                }
+
+                if (upsertAccountList.size() > 0) {
+                    NFMUtil.EscapeSBG001TriggerHandler = true;
+                    upsert upsertAccountList;
+                    for (Account acc: upsertAccountList) {
+                        if (acc.NationalEnterpriseUser__c) {
+                            UpsertAccountTeamMember(acc.Id);
+                        }
+                    }
+                }
+                existAccountMap = ExistAccount(satisfyGeData, iflog); //new Map<String,Account>();
+                Map < String, String > licenseChangeMap = LicenseChanges(existAccountMap); //new Map<String,String>();
+
+                if (executeFlag) {
+
+                    if (licenseChangeMap.size() > 0 && licenseChangeNotNullMap.size() > 0) {
+                        //鍙樻洿
+                        LicenseChange(licenseChangeMap, licenseChangeNotNullMap);
+                    }
+
+                    //鍚堝悓鐩稿叧(浠g悊鍟嗘姌鎵�)
+                    SatisfyDealerDiscount(satisfyGeData, existAccountMap, iflog);
+
+                    //璇佺収鐩稿叧
+                    SatisfyLicenseInfo(satisfyGeData, existAccountMap, transferLicenseTypeMap, certificationDetailTransferMap, iflog);
+
+                    //鑱旂郴浜虹浉鍏�
+                    SatisfyConsigneeInfoList(satisfyGeData, existAccountMap, iflog);
+
+                }
+
+            }
+
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+
+
+        } catch (Exception ex) {
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG203_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG203_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+    //璇佺収鍙樻洿
+    public static void LicenseChange(Map < String, String > licenseChangeMap, Map < String, String > licenseChangeNotNullMap) {
+
+        List < String > deleteExistDealerDiscountList = new List < String > ();
+        List < String > deleteExistLicenseInformationList = new List < String > ();
+        List < String > deleteExistContactList = new List < String > ();
+        for (String managementCode: licenseChangeMap.keySet()) {
+
+            if (licenseChangeNotNullMap.containsKey(managementCode)) {
+
+                String accountId = licenseChangeMap.get(managementCode);
+                //璇佺収鍙樻洿
+                if (licenseChangeNotNullMap.get(managementCode) == '2' || licenseChangeNotNullMap.get(managementCode) == '3' ||
+                    licenseChangeNotNullMap.get(managementCode) == '4' || licenseChangeNotNullMap.get(managementCode) == '7') {
+
+                    deleteExistLicenseInformationList.add(accountId);
+                }
+            }
+        }
+
+        List < License_Information__c > deleteLicenseInformationList = null;
+        if (deleteExistLicenseInformationList.size() > 0) {
+
+            deleteLicenseInformationList = [select Id from License_Information__c
+                where LicenseAndAccount__c In: deleteExistLicenseInformationList
+            ];
+            if (deleteLicenseInformationList.size() > 0) {
+                delete deleteLicenseInformationList;
+            }
+        }
+
+    }
+    //浠g悊鍟嗘姌鎵�
+    public static void SatisfyDealerDiscount(List < GeData > satisfyGeData, Map < String, Account > existAccountMap, BatchIF_Log__c iflog) {
+
+        //婊¤冻瑕佹眰鐨勪唬鐞嗗晢鎶樻墸
+        Map < String, Contract_Info > satisfyContractInfoMap = new Map < String, Contract_Info > ();
+        List < Dealer_Discount__c > dealerDiscountList = new List < Dealer_Discount__c > ();
+        Map < String, Dealer_Discount__c > dealerDiscountMap = new Map < String, Dealer_Discount__c > ();
+        //BS浠g悊鍟嗗厤绋庝唬鐞嗗晢鐩稿叧鐨勪唬鐞嗗晢鎶樻墸
+        Map < String, GeData > satisfy2GeData = new Map < String, GeData > ();
+        List < String > bpCodeList = new List < String > ();
+        Map < String, String > bpCodeMap = new Map < String, String > ();
+        //楠岃瘉浠g悊鍟嗘姌鎵e繀濉瓧娈�
+        for (GeData gda: satisfyGeData) {
+
+            // if (gda.BPType != '23') {
+            //     continue;
+            // }
+            if (!(gda.BPType == '23' || (gda.BPType == '24' && '42'.equals(gda.VTWEG)))) {
+                continue;
+            }
+            if (gda.Contract_Info == null) {
+                continue;
+            }
+            for (Contract_Info contractInfo: gda.Contract_Info) {
+                if (!String.isBlank(gda.ApplyType) && gda.ApplyType != '2' && gda.ApplyType != '3' && gda.ApplyType != '4' && gda.ApplyType != '6') {
+                    continue;
+                }
+                if (!existAccountMap.containsKey(gda.BPCode)) {
+                    iflog.ErrorLog__c += ' This BPCode[' + gda.BPCode + '] is not exist,This data is skipped .\n';
+                    continue;
+                }
+
+                String productSegment = existAccountMap.get(gda.BPCode).ProductSegment__c;
+                if (productSegment == 'BS') {
+
+                    if (String.isBlank(contractInfo.ContractRegion)) {
+                        continue;
+                    }
+                    bpCodeMap.put(gda.BPCode, gda.BPCode);
+                    bpCodeMap.put(gda.BPCodeforeign, gda.BPCodeforeign);
+                    satisfyContractInfoMap.put(gda.BPCode + productSegment + contractInfo.ContractRegion, contractInfo);
+                } else if (productSegment == 'IE') {
+
+                    satisfyContractInfoMap.put(gda.BPCode + productSegment + contractInfo.DealerRank, contractInfo);
+                    bpCodeMap.put(gda.BPCode, gda.BPCode);
+                } else if (productSegment == 'RVI') {
+
+                    // String processData = contractInfo.SubUse;
+                    // // String latitudeValue = gda.BPCode + 'Other';
+                    // if (String.isNotBlank(processData)) {
+
+                    //     if ( processData.indexOf('Civil Aviation') != -1) {
+                    //         // latitudeValue = gda.BPCode + 'Civil Aviation';
+                    //         bpCodeMap.put(gda.BPCode, gda.BPCode);
+                    //         if ( processData.indexOf(';') != -1 ) {
+                    //             // latitudeValue = gda.BPCode + 'Other';
+                    //             bpCodeMap.put(gda.BPCode, gda.BPCode);
+                    //         }
+                    //     } else {
+                    //         bpCodeMap.put(gda.BPCode, gda.BPCode);
+                    //     }
+                    //     satisfyContractInfoMap.put(gda.BPCode + productSegment + contractInfo.SubUse, contractInfo);
+                    // }
+                    bpCodeMap.put(gda.BPCode, gda.BPCode);
+                    satisfyContractInfoMap.put(gda.BPCode + productSegment + contractInfo.SubUse, contractInfo);
+                } else if (productSegment == 'NDT' || productSegment == 'ANI') {
+                    bpCodeMap.put(gda.BPCode, gda.BPCode);
+                    satisfyContractInfoMap.put(gda.BPCode + productSegment, contractInfo);
+                }
+                satisfy2GeData.put(gda.BPCode, gda);
+
+            }
+        }
+
+        Map < String, Dealer_Discount__c > existDealerDiscountMap = getExistDealerDiscountMap(bpCodeMap.values());
+        Map < String, String > satisfyBsDealerDiscountMap = new Map < String, String > ();
+
+        //Boolean bSforeignFlag = false;
+        Boolean bSFlag = false;
+        for (GeData gda: satisfy2GeData.values()) {
+
+            //Bs鍏嶇◣浠g悊鍟嗙浉鍏充唬鐞嗗晢鎶樻墸瀛楁鐨勮祴鍊�
+            for (Contract_Info contractInfo: satisfyContractInfoMap.values()) {
+
+                if (existAccountMap.containsKey(gda.BPCodeforeign)) {
+                    String productSegment = existAccountMap.get(gda.BPCodeforeign).ProductSegment__c;
+                    if (productSegment == 'BS') {
+
+                        Map < String, Dealer_Discount__c > dealerDiscountBSMap = BS_DealerDiscount(existAccountMap, contractInfo.ContractRegion, existDealerDiscountMap, contractInfo, gda.BPCode, gda.BPCodeforeign, satisfyBsDealerDiscountMap);
+                        dealerDiscountMap.putAll(dealerDiscountBSMap);
+                    }
+
+                }
+
+            }
+
+            //鍏跺畠浠g悊鍟嗙浉鍏充唬鐞嗗晢鎶樻墸瀛楁鐨勮祴鍊�
+            for (Contract_Info contractInfo: satisfyContractInfoMap.values()) {
+
+                String productSegment = existAccountMap.get(gda.BPCode).ProductSegment__c;
+                Dealer_Discount__c dealerDiscount;
+                if (productSegment == 'IE' || productSegment == 'NDT' || productSegment == 'ANI') {
+                    String latitudeValue = gda.BPCode;
+                    dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, productSegment);
+                    dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, productSegment, existAccountMap, '', '', gda.BPCode);
+                    dealerDiscountList.add(dealerDiscount);
+                } else if (productSegment == 'BS') {
+                    bSFlag = true;
+                    Map < String, Dealer_Discount__c > dealerDiscountBSMap = BS_DealerDiscount(existAccountMap, contractInfo.ContractRegion, existDealerDiscountMap, contractInfo, gda.BPCode, '', satisfyBsDealerDiscountMap);
+                    dealerDiscountMap.putAll(dealerDiscountBSMap);
+                } else if (productSegment == 'RVI') {
+
+                    String processData = contractInfo.SubUse;
+                    String latitudeValue = gda.BPCode + 'Other';
+                    contractInfo.SubUse = 'Other';
+                    if (String.isNotBlank(processData)) {
+                        // 鍖呭惈 Civil Aviation锛涘垱寤烘垨鏂板浠g悊鍟嗘姌鎵�
+                        if (processData.indexOf('Civil Aviation') != -1) {
+                            latitudeValue = gda.BPCode + 'Civil Aviation';
+                            contractInfo.SubUse = 'Civil Aviation';
+                            dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, productSegment);
+                            dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, productSegment, existAccountMap, '', '', gda.BPCode);
+                            dealerDiscountList.add(dealerDiscount);
+                            // 鍖呭惈';'璇存槑鍖呭惈 鍏跺畠鐨勫垎绫伙紱鍒涘缓鎴栨柊澧炰唬鐞嗗晢鎶樻墸
+                            if (processData.indexOf(';') != -1) {
+                                latitudeValue = gda.BPCode + 'Other';
+                                contractInfo.SubUse = 'Other';
+                                dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, productSegment);
+                                dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, productSegment, existAccountMap, '', '', gda.BPCode);
+                                dealerDiscountList.add(dealerDiscount);
+                            }
+                            continue;
+                        }
+                        // else {
+                        // contractInfo.SubUse = 'Other';
+                        // dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, productSegment);
+                        // dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, productSegment, existAccountMap, '', '', gda.BPCode);
+                        // dealerDiscountList.add(dealerDiscount);
+                        // }
+                    }
+                    dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, productSegment);
+                    dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, productSegment, existAccountMap, '', '', gda.BPCode);
+                    dealerDiscountList.add(dealerDiscount);
+
+                }
+            }
+        }
+        if (dealerDiscountList.size() > 0) {
+            upsert dealerDiscountList;
+        }
+        if (dealerDiscountMap.size() > 0) {
+            upsert dealerDiscountMap.values();
+        }
+        if (bSFlag) {
+            deleteDealerDiscount(satisfyBsDealerDiscountMap, existDealerDiscountMap);
+        }
+
+    }
+    //杞崲鍓嶅悗鐨勫�肩殑瀵规瘮
+    public static String FieldTransformation(String bpCode, Map < String, String > transformation, String api, String toConvertStr, BatchIF_Log__c iflog, String receivesField) {
+        String afterTransformation = NFMUtil.getMapValue(transformation, api, toConvertStr, iflog);
+        if (String.isNotBlank(afterTransformation) && !afterTransformation.equals(toConvertStr)) {
+            return afterTransformation;
+        } else if (String.isNotBlank(afterTransformation) && afterTransformation.equals(toConvertStr)) {
+            return afterTransformation;
+        } else {
+            iflog.ErrorLog__c += 'BPCode[ ' + bpCode + ' ] of ' + receivesField + ' [ ' + toConvertStr + ' ]' + ' is  Invalid,This data is skipped.\n';
+            return 'Invalid';
+        }
+    }
+
+    //BS浠g悊鍟嗘姌鎵�
+    public static Map < String, Dealer_Discount__c > BS_DealerDiscount(Map < String, Account > existAccountMap,
+        String contractRegion, Map < String, Dealer_Discount__c > existDealerDiscountMap,
+        Contract_Info contractInfo, String bpCode, String bPCodeforeign,
+        Map < String, String > satisfyBsDealerDiscountMap) {
+        Map < String, Dealer_Discount__c > result = new Map < String, Dealer_Discount__c > ();
+        String code = String.isBlank(bPCodeforeign) ? bpCode : bPCodeforeign;
+
+        if (contractRegion.indexOf(';') != -1) {
+            for (String region: contractRegion.split(';')) {
+                if (String.isNotBlank(region)) {
+                    Dealer_Discount__c dealerDiscount;
+                    String latitudeValue = code + region;
+                    dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, 'BS');
+                    dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, 'BS', existAccountMap, bPCodeforeign, region, bpCode);
+                    satisfyBsDealerDiscountMap.put(latitudeValue, latitudeValue);
+                    result.put(latitudeValue, dealerDiscount);
+                }
+            }
+        } else if (String.isNotBlank(contractRegion)) {
+
+            Dealer_Discount__c dealerDiscount;
+            String latitudeValue = code + contractRegion;
+
+            dealerDiscount = AcquireDealerDiscount(existDealerDiscountMap, latitudeValue, contractInfo, 'BS');
+            dealerDiscount = DealerDiscountFields(contractInfo, dealerDiscount, 'BS', existAccountMap, bPCodeforeign, contractRegion, bpCode);
+            satisfyBsDealerDiscountMap.put(latitudeValue, latitudeValue);
+            result.put(latitudeValue, dealerDiscount);
+        }
+        return result;
+    }
+
+    //浠g悊鍟嗗叾瀹冨瓧娈电殑璧嬪��
+    public static Dealer_Discount__c DealerDiscountFields(Contract_Info contractInfo, Dealer_Discount__c dealerDiscount, String productSegment,
+        Map < String, Account > existAccountMap, String bPCodeforeign, String region, String bpCode) {
+        String code = String.isNotBlank(bPCodeforeign) ? bPCodeforeign : bpCode;
+        dealerDiscount.Product_Segment__c = productSegment;
+        dealerDiscount.DimensionField1__c = 'Dealer_Code__c';
+        dealerDiscount.DimensionValue1__c = code;
+        dealerDiscount.DealerDiscountAccount__c = existAccountMap.get(code).Id;
+        dealerDiscount.Name = productSegment + '-' + existAccountMap.get(code).Name;
+        if (productSegment == 'BS') {
+            dealerDiscount.DimensionField2__c = 'Province__c';
+            dealerDiscount.DimensionValue2__c = region;
+            if (String.isNotBlank(bPCodeforeign)) {
+                dealerDiscount.DimensionValue1__c = code;
+                dealerDiscount.DealerDiscountAccount__c = existAccountMap.get(code).Id;
+                dealerDiscount.Name = productSegment + '-' + existAccountMap.get(code).Name;
+            }
+        } else if (productSegment == 'RVI') {
+            dealerDiscount.DimensionField2__c = 'Subuse__c';
+            dealerDiscount.DimensionValue2__c = contractInfo.SubUse == 'Civil Aviation' ? 'Civil Aviation' : 'Other';
+
+        }
+
+        return dealerDiscount;
+    }
+    //浠g悊鍟嗘姌鎵f棩鏈熺浉鍏冲瓧娈电殑璧嬪��
+    public static Dealer_Discount__c AcquireDealerDiscount(Map < String, Dealer_Discount__c > existDealerDiscountMap, String latitudeValue, Contract_Info contractInfo, String productSegment) {
+        system.debug('AcquireDealerDiscount--->Start');
+        Dealer_Discount__c dealerDiscount = new Dealer_Discount__c();
+        Date dateFrom = String.isBlank(contractInfo.ContractStartDate) ? Date.today() : NFMUtil.parseStr2Date(contractInfo.ContractStartDate, false);
+        Date dateTo = NFMUtil.parseStr2Date('20991231', true);
+
+        Decimal dealerRate; //(off:鐩存帴瀛�;ON:100-Decimal.valueOf(contractInfo.DealerRate))
+        //if ( productSegment == 'NDT' || productSegment == 'ANI') {
+        //  dealerRate = String.isBlank(contractInfo.DealerRate) ? 100 : Decimal.valueOf(contractInfo.DealerRate);
+        //} else
+        //2020-1-2 XHL Start
+        if (productSegment == 'BS') {
+            dealerRate = String.isBlank(contractInfo.DealerRate) ? 100 : 100 - Decimal.valueOf(contractInfo.DealerRate);
+        } else {
+            dealerRate = String.isBlank(contractInfo.DealerRate) ? 100 : Decimal.valueOf(contractInfo.DealerRate);
+        }
+        //2020-1-2 XHL End
+        if (existDealerDiscountMap.containsKey(latitudeValue)) {
+            dealerDiscount = existDealerDiscountMap.get(latitudeValue);
+            Date statusOneStart = dealerDiscount.Valid_Date_From__c;
+            Date statusOneEnd = dealerDiscount.Valid_Date_To__c;
+            Date statusTwoStart = dealerDiscount.Valid_Date_From2__c;
+            Date statusTwoEnd = dealerDiscount.Valid_Date_To2__c;
+
+            if (statusOneStart == null || statusOneEnd < Date.today() || statusOneStart == dateFrom) {
+                dealerDiscount.Valid_Date_To2__c = statusTwoEnd != null ? dateFrom.addDays(-1) : null;
+                dealerDiscount.Valid_Date_From__c = dateFrom;
+                dealerDiscount.Valid_Date_To__c = dateTo;
+                dealerDiscount.Dealer_Rank__c = dealerRate;
+            } else if (statusTwoStart == null || statusTwoEnd < Date.today() || statusTwoStart == dateFrom) {
+                //20200108---Add---Start-鎶樻墸寮�濮嬫棩2涓虹┖锛屾姌鎵e紑濮嬫棩1涓烘湭鏉ユ棩鏈燂紝鏇存柊鎶樻墸1
+                if (statusTwoStart == null && statusOneStart > Date.today()) {
+                    dealerDiscount.Valid_Date_From__c = dateFrom;
+                    dealerDiscount.Valid_Date_To__c = dateTo;
+                    dealerDiscount.Dealer_Rank__c = dealerRate;
+                    //20200108---Add---End
+                } else {
+                    dealerDiscount.Valid_Date_To__c = dateFrom.addDays(-1);
+                    dealerDiscount.Valid_Date_From2__c = dateFrom;
+                    dealerDiscount.Valid_Date_To2__c = dateTo;
+                    dealerDiscount.Dealer_Rank2__c = dealerRate;
+                }
+            } else {
+                if ((statusOneStart <= Date.today()) && (Date.today() <= statusOneEnd)) {
+                    dealerDiscount.Valid_Date_To__c = dateFrom.addDays(-1);
+                    dealerDiscount.Valid_Date_From2__c = dateFrom;
+                    dealerDiscount.Valid_Date_To2__c = dateTo;
+                    dealerDiscount.Dealer_Rank2__c = dealerRate;
+                } else if ((statusTwoStart <= Date.today()) && (Date.today() <= statusTwoEnd)) {
+                    dealerDiscount.Valid_Date_To2__c = dateFrom.addDays(-1);
+                    dealerDiscount.Valid_Date_From__c = dateFrom;
+                    dealerDiscount.Valid_Date_To__c = dateTo;
+                    dealerDiscount.Dealer_Rank__c = dealerRate;
+                }
+            }
+        } else {
+            dealerDiscount.Valid_Date_From__c = dateFrom;
+            dealerDiscount.Valid_Date_To__c = dateTo;
+            dealerDiscount.Dealer_Rank__c = dealerRate;
+        }
+        dealerDiscount.IsFromSPO__c = true;
+        return dealerDiscount;
+    }
+
+    public static void SatisfyLicenseInfo(List < GeData > satisfyGeData, Map < String, Account > existAccountMap, Map < String, String > transferLicenseTypeMap, Map < String, String > certificationDetailTransferMap, BatchIF_Log__c iflog) {
+        system.debug('SatisfyLicenseInfo---Start');
+        //璇佺収灞傜骇
+
+        List < License_Info > satisfyLicenseInfoList = new List < License_Info > ();
+        List < License_Information__c > licenseInformationList = new List < License_Information__c > ();
+        List < Account > upsertAccountBusinesslicense = new List < Account > ();
+        List < CertificationDetails__c > certificationDetailsList = new List < CertificationDetails__c > ();
+        for (GeData gda: satisfyGeData) {
+            if (gda.License_Info == null) {
+                continue;
+            }
+            satisfyLicenseInfoList = new List < License_Info > ();
+            for (License_Info licenseInfo: gda.License_Info) {
+                if (!String.isBlank(gda.ApplyType) && gda.ApplyType != '2' && gda.ApplyType != '3' && gda.ApplyType != '4' && gda.ApplyType != '7') {
+                    continue;
+                }
+                if (String.isBlank(licenseInfo.LicenseType) || String.isBlank(licenseInfo.BusLicenseNo)) {
+                    continue;
+                }
+                satisfyLicenseInfoList.add(licenseInfo);
+            }
+            if (satisfyLicenseInfoList.size() > 0) {
+
+                for (License_Info licenseInfo: satisfyLicenseInfoList) {
+                    License_Information__c licenseInformation = new License_Information__c();
+                    String licenseType = FieldTransformation(gda.BPCode, transferLicenseTypeMap, 'LicenseType__c', licenseInfo.LicenseType, iflog, 'LicenseType');
+                    if (licenseType.equals('Invalid')) {
+                        continue;
+                    }
+
+                    licenseInformation.LicenseType__c = licenseType;
+                    licenseInformation.BusinessLicense__c = licenseInfo.BusLicenseNo;
+                    licenseInformation.ValidFrom__c = NFMUtil.parseStr2Date(licenseInfo.ValidFrom, false);
+                    licenseInformation.ValidTo__c = NFMUtil.parseStr2Date(licenseInfo.ValidTo, false);
+                    String warehouseAddress = licenseInfo.WarehouseAddress;
+                    if (String.isNotBlank(warehouseAddress)) {
+                        if (warehouseAddress.endsWith(';') || warehouseAddress.endsWith('锛�')) {
+                            licenseInformation.StorageAddress__c = warehouseAddress.substring(0, warehouseAddress.length() - 1);
+                        } else {
+                            licenseInformation.StorageAddress__c = warehouseAddress;
+                        }
+                    } else {
+                        licenseInformation.StorageAddress__c = warehouseAddress;
+                    }
+
+
+                    String productSegment = gda.ProductSegment == 'LS' ? 'BS' : gda.ProductSegment;
+                    if (gda.BPType == '23' && productSegment == 'BS') {
+                        licenseInformation.LicenseAndAccount__c = existAccountMap.get(gda.BPCode).ParentId;
+                        licenseInformation.Name = existAccountMap.get(gda.BPCode).Parent.Name + licenseType;
+                    } else {
+                        licenseInformation.LicenseAndAccount__c = existAccountMap.get(gda.BPCode).Id;
+                        licenseInformation.Name = existAccountMap.get(gda.BPCode).Name + licenseType;
+                    }
+                    //杈愬皠瀹夊叏璁稿彲璇�
+                    if ('08'.equals(licenseInfo.LicenseType)) {
+                        licenseInformation.IfQuantityCtrl__c = licenseInfo.IfQuantityCtrl;
+                        if (licenseInfo.Detail_Info != null) {
+
+                            certificationDetailsList = SatisfyLicenseDetails(gda.BPCode, licenseInfo.Detail_Info, certificationDetailTransferMap, iflog);
+                        }
+                    }
+                    if ('04'.equals(licenseInfo.LicenseType)) {
+
+                        Account acc = new Account();
+                        acc.Id = licenseInformation.LicenseAndAccount__c;
+                        acc.Business_license__c = licenseInfo.BusLicenseNo;
+                        upsertAccountBusinesslicense.add(acc);
+                    }
+                    licenseInformationList.add(licenseInformation);
+                }
+            }
+
+        }
+
+        if (licenseInformationList.size() > 0) {
+            upsert licenseInformationList;
+            if (certificationDetailsList.size() > 0) {
+                insertCertificationDetail(certificationDetailsList, licenseInformationList);
+            }
+        }
+
+        if (upsertAccountBusinesslicense.size() > 0) {
+            upsert upsertAccountBusinesslicense;
+        }
+    }
+
+    //鑾峰彇绗﹀悎鐨勮瘉鐓ф槑缁�
+    public static List < CertificationDetails__c > SatisfyLicenseDetails(String bpCode, List < Detail_Info > LicenseDetailS, Map < String, String > certificationDetailTransferMap, BatchIF_Log__c iflog) {
+        Map < String, CertificationDetails__c > certificationDetailMap = new Map < String, CertificationDetails__c > ();
+        List < CertificationDetails__c > result = new List < CertificationDetails__c > ();
+        for (Detail_Info detailInfo: LicenseDetailS) {
+
+            String licenseType = FieldTransformation(bpCode, certificationDetailTransferMap, 'ProdustionType__c', detailInfo.ProSerial, iflog, 'ProSerial');
+            Integer quantity = String.isBlank(detailInfo.Quantity) ? null : Integer.valueof(detailInfo.Quantity);
+            String remarks = detailInfo.ProName + '(' + quantity + ')';
+            String key = licenseType + '-' + detailInfo.Category;
+            if (!certificationDetailMap.containsKey(key)) {
+                CertificationDetails__c detail = new CertificationDetails__c();
+                detail.ProdustionType__c = licenseType;
+                detail.ProductModelNumber__c = quantity;
+                detail.ActivitieTypes__c = detailInfo.Category;
+                detail.DeviceName__c = detailInfo.ProName;
+                detail.Remarks__c = remarks;
+                certificationDetailMap.put(key, detail);
+            } else {
+                certificationDetailMap.get(key).ProductModelNumber__c += quantity;
+                certificationDetailMap.get(key).DeviceName__c += '/' + detailInfo.ProName;
+                certificationDetailMap.get(key).Remarks__c += '/' + remarks;
+
+            }
+        }
+        if (certificationDetailMap.size() > 0) {
+            for (CertificationDetails__c detail: certificationDetailMap.values()) {
+                result.add(detail);
+            }
+        }
+
+        return result;
+    }
+
+    public static void insertCertificationDetail(List < CertificationDetails__c > certificationDetailsList,
+        List < License_Information__c > licenseInformationList) {
+
+        String radiationCertificateId = '';
+        for (License_Information__c licenseInformation: licenseInformationList) {
+            if (licenseInformation.LicenseType__c == '杈愬皠瀹夊叏璁稿彲璇�') {
+                radiationCertificateId = licenseInformation.Id;
+            }
+        }
+        for (CertificationDetails__c certificationDetail: certificationDetailsList) {
+            certificationDetail.LicenseInformation__c = radiationCertificateId;
+        }
+        upsert certificationDetailsList;
+
+    }
+    public static void SatisfyConsigneeInfoList(List < GeData > satisfyGeData, Map < String, Account > existAccountMap, BatchIF_Log__c iflog) {
+        system.debug('SatisfyConsigneeInfoList---Start');
+        //鏀惰揣浜哄眰绾х浉鍏�(鑱旂郴浜�)
+        List < Contact > upsertContactList = new List < Contact > ();
+        Map < String, Consignee_Info > satisfyConsigneeInfoMap = new Map < String, Consignee_Info > ();
+        // 浠g悊鍟嗙鐢� 灏嗕唬鐞嗗晢鐢ㄦ埛璁剧疆涓烘湭鍚敤
+        List < String > disableContactIdList = new List < String > ();
+        Boolean disableUserFlag = false;
+        // 浠g悊鍟嗙鐢� 灏嗕唬鐞嗗晢鐢ㄦ埛璁剧疆涓烘湭鍚敤
+        // 
+        List < Contact > existContact = getexistContactList(satisfyGeData,existAccountMap);
+        
+        for (GeData gda: satisfyGeData) {
+            if (gda.Consignee_Info == null) {
+                continue;
+            }
+            satisfyConsigneeInfoMap = new Map < String, Consignee_Info > ();
+            for (Consignee_Info consigneeInfo: gda.Consignee_Info) {
+                if (!String.isBlank(gda.ApplyType) && gda.ApplyType != '2' && gda.ApplyType != '3' &&
+                    gda.ApplyType != '4' && gda.ApplyType != '7' && gda.ApplyType != '8') {
+                    continue;
+                }
+                if (String.isBlank(consigneeInfo.ContactName) || String.isBlank(consigneeInfo.ContactId)) {
+                    continue;
+                }
+                if (String.isBlank(consigneeInfo.ContactAddress) && gda.BPType != '22') {
+                    continue;
+                }
+
+                String contactId = processContactId(consigneeInfo.ContactId);
+                satisfyConsigneeInfoMap.put(contactId, consigneeInfo);
+
+            }
+            system.debug('<--satisfyConsigneeInfoMap-->' + satisfyConsigneeInfoMap);
+            Map < String, Contact > existContactMap = new Map < String, Contact > ();
+            if (satisfyConsigneeInfoMap.size() > 0) {
+
+                // String accountId = existAccountMap.get(gda.BPCode).Id;
+                // List < Contact > existContact = [select Id, ManagementCode_Ext__c, IsFromSPO__c, ManagementCode_F__c
+                //     from Contact
+                //     where AccountId =: accountId
+                // ];
+
+                if (existContact.size() > 0) {
+                    for (Contact con: existContact) {
+
+                        String contactId = processContactId(con.ManagementCode_F__c);
+                        existContactMap.put(contactId, con);
+                        if (!satisfyConsigneeInfoMap.containsKey(contactId)) {
+                            Contact cont = new Contact();
+                            cont.Id = con.Id;
+                            cont.ContactStatus__c = 'Cancel';
+                            cont.ContactStatusD__c = 'Cancel';
+                            if (String.isNotBlank(con.ManagementCode_Ext__c)) {
+                                upsertContactList.add(cont);
+                            }
+
+                        }
+
+                        disableContactIdList.add(con.Id);
+                    }
+                    // 灏嗕唬鐞嗗晢鐢ㄦ埛璁剧疆涓烘湭鍚敤
+                    // if (gda.ApplyType == '1' && disableContactIdList != null && disableContactIdList.size() > 0) {
+                    //     disableUserFlag = true;
+                    // }
+                    // 灏嗕唬鐞嗗晢鐢ㄦ埛璁剧疆涓烘湭鍚敤
+                }
+                system.debug('existContactMap------>' + existContactMap);
+                for (Consignee_Info consigneeInfo: satisfyConsigneeInfoMap.values()) {
+
+                    String contactId = processContactId(consigneeInfo.ContactId);
+                    Contact con = new Contact();
+                    if (existContactMap.containsKey(contactId)) {
+                        con = existContactMap.get(contactId);
+                        if (String.isNotBlank(con.ManagementCode_Ext__c)) {
+                            con.ManagementCode_Ext__c = consigneeInfo.ContactId;
+                        }
+                    } else {
+                        con.ManagementCode_Ext__c = consigneeInfo.ContactId;
+                        con.IsFromSPO__c = true;
+                        con.Department = '鏃�';
+                    }
+                    con.AccountId = existAccountMap.get(gda.BPCode).Id;
+                    con.MobilePhone = consigneeInfo.ContactPhone; //SPO鍙湁涓�涓�糲onsigneeInfo.ContactPhone鏁呬綔姝ゅ鐞�20191016 consigneeInfo.ContactMobilePhone;
+                    con.MobilePhoneD__c = consigneeInfo.ContactPhone;
+                    con.Phone = consigneeInfo.ContactPhone;
+                    con.PhoneD__c = consigneeInfo.ContactPhone;
+                    con.Postcode__c = consigneeInfo.PostalCode;
+                    con.PostcodeD__c = consigneeInfo.PostalCode;
+                    con.Address1__c = gda.BPType == '22' ? gda.RegisterAddress : consigneeInfo.ContactAddress;
+                    con.Address1D__c = gda.BPType == '22' ? gda.RegisterAddress : consigneeInfo.ContactAddress;
+                    con.EnglishAddress__c = gda.BPType == '22' ? gda.STR_SUPPL1 : '';
+                    if (String.isNotBlank(consigneeInfo.ContactEnglishName) && gda.BPType == '22') {
+                        con.LastName = consigneeInfo.ContactName + '(' + consigneeInfo.ContactEnglishName + ')';
+                        con.FirstName = null;
+                        con.ContactEnglishName__c = consigneeInfo.ContactEnglishName;
+                    } else {
+                        con.LastName = consigneeInfo.ContactName;
+                        con.FirstName = null;
+                    }
+
+                    con.ContactStatus__c = 'Active';
+                    con.ContactStatusD__c = 'Active';
+                    con.StatusD__c = 'Pass';
+                    con.ProductSegmentBS__c = false;
+                    con.ProductSegmentRVI__c = false;
+                    con.ProductSegmentIE__c = false;
+                    con.ProductSegmentNDT__c = false;
+                    con.ProductSegmentANI__c = false;
+
+                    String productSegment = existAccountMap.get(gda.BPCode).ProductSegment__c;
+                    if (productSegment == 'BS') {
+                        con.ProductSegmentBS__c = true;
+                    } else if (productSegment == 'RVI') {
+                        con.ProductSegmentRVI__c = true;
+                    } else if (productSegment == 'IE') {
+                        con.ProductSegmentIE__c = true;
+                    } else if (productSegment == 'NDT') {
+                        con.ProductSegmentNDT__c = true;
+                    } else if (productSegment == 'ANI') {
+                        con.ProductSegmentANI__c = true;
+                    }
+
+                    upsertContactList.add(con);
+                }
+            }
+
+        }
+        // 灏嗕唬鐞嗗晢鐢ㄦ埛璁剧疆涓烘湭鍚敤 START
+        // if (disableUserFlag) {
+
+        //     List < User > disableUserList = [SELECT Id, Name, ContactId, IsActive FROM User WHERE ContactId In: disableContactIdList AND IsActive = true];
+        //     if (disableUserList.size() > 0) {
+        //         for (User user: disableUserList) {
+        //             user.IsActive = false;
+        //         }
+        //         update disableUserList;
+        //     }
+        // }
+        // 灏嗕唬鐞嗗晢鐢ㄦ埛璁剧疆涓烘湭鍚敤 END
+        if (upsertContactList.size() > 0) {
+            NFMUtil.EscapeSBG001TriggerHandler = true;
+            system.debug('upsertContactList---->' + upsertContactList);
+            upsert upsertContactList;
+        }
+        system.debug('SatisfyConsigneeInfoList---End');
+
+    }
+
+    public static List < Contact > getexistContactList(List < GeData > satisfyGeData, Map < String, Account > existAccountMap){
+        List < Contact > existContact = new List < Contact >();
+        String accountIdStr = null;
+        Boolean  contactCancelFlg = false;
+        for (GeData gda: satisfyGeData) {
+            // 瀹㈡埛绂佺敤锛屽皢瀹㈡埛涓嬬殑鑱旂郴浜鸿繘琛屾棤鏁�
+            if (!String.isBlank(gda.ApplyType) && gda.ApplyType == '1' ) {
+                contactCancelFlg = true;
+            }
+            accountIdStr = existAccountMap.get(gda.BPCode).Id;
+        }
+
+        if (String.isNotBlank(accountIdStr)) {
+            existContact = [select Id, ManagementCode_Ext__c, IsFromSPO__c, ManagementCode_F__c
+                from Contact
+                where AccountId =: accountIdStr
+            ];
+
+            if (contactCancelFlg && existContact.size() > 0 ) {
+                for (Contact con: existContact) {
+                    con.ContactStatus__c = 'Cancel';
+                    con.ContactStatusD__c = 'Cancel';
+                }
+
+                update existContact;
+            }
+        }
+
+        return existContact;
+    }
+
+
+    public static String processContactId(String contactId) {
+        String result = '';
+        Pattern pattern = Pattern.compile('[0-9]*');
+        Matcher isNum = pattern.matcher(contactId);
+        String stringNum = '';
+        if (isNum.matches()) {
+            Integer integerNum = Integer.valueOf(contactId);
+            stringNum = String.valueOf(integerNum);
+        }
+        result = String.isBlank(stringNum) ? contactId : stringNum;
+        return result;
+    }
+
+    //楠岃瘉瀛楁鏄惁鏈夊��
+    public static Boolean FieldIsBlank(String bpCode, String verifyField, String receivesField, BatchIF_Log__c iflog) {
+
+        if (String.isBlank(bpCode)) {
+            iflog.ErrorLog__c += 'BPCode is required,This data is skipped.\n';
+            return true;
+        } else if (String.isBlank(verifyField)) {
+            iflog.ErrorLog__c += 'BPCode[ ' + bpCode + ' ] of ' + receivesField + ' is required,This data is skipped.\n';
+            return true;
+        } else {
+            return false;
+        }
+
+    }
+    //灏� 鍚� 鏅撴檽(00328000010GuUC)鏀惧埌鍏ㄥ浗浼佷笟鐢ㄦ埛鐨勫鎴峰洟闃熼噷闈�
+    public static void UpsertAccountTeamMember(String accountId) {
+        AccountTeamMember atm = new AccountTeamMember();
+        atm.accountId = accountId;
+        atm.userId = '005280000071H0s';
+        atm.teamMemberRole = 'Sales Manager';
+        atm.ACCOUNTACCESSLEVEL = 'Edit';
+        atm.CONTACTACCESSLEVEL = 'Edit';
+        atm.OPPORTUNITYACCESSLEVEL = 'None';
+        atm.CASEACCESSLEVEL = 'None';
+        upsert atm;
+    }
+
+    public static List < GeData > SatisfyGeData(List < GeData > geDataList, BatchIF_Log__c iflog) {
+
+        List < GeData > result = new List < GeData > ();
+
+        for (GeData gda: geDataList) {
+            Boolean ErrorFlg = false;
+            if (FieldIsBlank(gda.BPCode, gda.BPCode, 'BPCode', iflog)) {
+                ErrorFlg = true;
+            }
+
+            if (FieldIsBlank(gda.BPCode, gda.BPType, 'BPType', iflog)) {
+                ErrorFlg = true;
+            }
+
+            if (FieldIsBlank(gda.BPCode, gda.ProductSegment, 'ProductSegment', iflog)) {
+                ErrorFlg = true;
+            }
+
+            if (FieldIsBlank(gda.BPCode, gda.CompanyName, 'CompanyName', iflog)) {
+                ErrorFlg = true;
+            }
+
+            // if (FieldIsBlank(gda.BPCode, gda.VTWEG, 'VTWEG', iflog)) {
+            //     ErrorFlg = true;
+            // }
+
+            if (gda.BPType == '24') {
+
+                // 鍒嗛攢娓犻亾-鐩撮攢
+                if ('42'.equals(gda.VTWEG)) {
+
+                    if (FieldIsBlank(gda.BPCode, gda.AccountSource, 'BPType is 24 of AccountSource', iflog)) {
+                        ErrorFlg = true;
+                    }
+                    if (FieldIsBlank(gda.BPCode, gda.UserType, 'BPType is 24 of UserType', iflog)) {
+                        ErrorFlg = true;
+                    }
+                    if (FieldIsBlank(gda.BPCode, gda.COMPOSubuse, 'BPType is 24 of COMPOSubuse', iflog)) {
+                        ErrorFlg = true;
+                    }
+                    if (gda.TargetCustomer == null) {
+                        iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of TargetCustomer is required,This data is skipped.\n'; //瀹㈡埛绫诲瀷
+                        ErrorFlg = true;
+                    }
+
+                    if (gda.IsCOMPO == null) {
+                        iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of IsCOMPO is required,This data is skipped.\n'; //COMPO瀹㈡埛
+                        ErrorFlg = true;
+                    }
+                } else {
+                    if (FieldIsBlank(gda.BPCode, gda.KeyAccount, 'BPType is 24 of KeyAccount', iflog)) {
+                        ErrorFlg = true;
+                    }
+
+                    if (FieldIsBlank(gda.BPCode, gda.ExportRegulatedCustomer, 'BPType is 24 of ExportRegulatedCustomer', iflog)) {
+                        ErrorFlg = true;
+                    }
+
+                    if (FieldIsBlank(gda.BPCode, gda.MarketVerticals, 'BPType is 24 of MarketVerticals', iflog)) {
+                        ErrorFlg = true;
+                    }
+
+                    if (FieldIsBlank(gda.BPCode, gda.Industry, 'BPType is 24 of Industry', iflog)) {
+                        ErrorFlg = true;
+                    }
+
+                    if (FieldIsBlank(gda.BPCode, gda.Use, 'BPType is 24 of Use', iflog)) {
+                        ErrorFlg = true;
+                    }
+                }
+
+            }
+            String transformProductSegment = gda.ProductSegment == 'LS' ? 'BS' : gda.ProductSegment;
+
+            if (gda.BPType == '23') {
+                //缁忛攢鍟嗗垎绫�
+                if (FieldIsBlank(gda.BPCode, gda.AgentType, 'AgentType', iflog)) {
+                    ErrorFlg = true;
+                }
+            }
+            if (gda.BPType == '23' && transformProductSegment == 'BS') {
+                //鍏嶇◣缂栫爜
+                if (FieldIsBlank(gda.BPCode, gda.BPCodeforeign, 'BPType is 23 and ProductSegment is BS  BPCodeforeign', iflog)) {
+                    ErrorFlg = true;
+                } else {
+                    String foreign = gda.BPCodeforeign.trim();
+                    if (foreign.equals('3000000378')) {
+                        gda.BPCodeforeign = foreign + '-1';
+                    }
+                }
+            }
+            if (ErrorFlg) {
+                continue;
+            }
+            result.add(gda);
+        }
+
+        return result;
+    }
+    //瀛樺湪鐨勫鎴�
+    public static Map < String, Account > ExistAccount(List < GeData > satisfyGeData, BatchIF_Log__c iflog) {
+
+        Map < String, Account > result = new Map < String, Account > ();
+        List < String > bPCodeList = new List < String > ();
+        for (GeData gda: satisfyGeData) {
+            String transformProductSegment = gda.ProductSegment == 'LS' ? 'BS' : gda.ProductSegment;
+            if (gda.BPType == '23' && transformProductSegment == 'BS') {
+                bPCodeList.add(gda.BPCodeforeign);
+            }
+            bPCodeList.add(gda.BPCode);
+        }
+
+        if (bPCodeList.size() > 0) {
+            List < Account > accountList = [select Id, Name, ManagementCode_Ext__c, ParentId, ProductSegment__c,
+                Parent.Name, Parent.BS_Children_Code__c, Address1__c, RecordTypeId, IsPartner, ProhibitionAccount__c
+                from Account
+                where ManagementCode_Ext__c In: bPCodeList
+            ];
+
+            if (accountList.size() > 0) {
+
+                for (Account acc: accountList) {
+                    result.put(acc.ManagementCode_Ext__c, acc);
+                }
+            }
+        }
+
+        return result;
+    }
+
+    public static Map < String, String > LicenseChanges(Map < String, Account > existAccountMap) {
+        Map < String, String > result = new Map < String, String > ();
+
+        if (existAccountMap.size() > 0) {
+
+            for (Account acc: existAccountMap.values()) {
+
+                if (acc.RecordTypeId == '012280000005gnE' && acc.ProductSegment__c == 'BS') {
+
+                    result.put(acc.Parent.BS_Children_Code__c, acc.ParentId);
+                } else {
+                    result.put(acc.ManagementCode_Ext__c, acc.Id);
+                }
+            }
+        }
+        return result;
+
+    }
+
+    public static Account AccountValueAssignment(GeData gda, Account accountInfo, Map < String, String > transferMap, Map < String, String > accountRecordTypeMap, BatchIF_Log__c iflog) {
+        system.debug('AccountValueAssignment---Start');
+        system.debug('accountRecordTypeMap---->' + accountRecordTypeMap);
+        String productSegment = gda.ProductSegment == 'LS' ? 'BS' : gda.ProductSegment;
+        if (gda.BPType == '23') {
+            if (String.isNotBlank(accountInfo.BS_Children_Code__c)) {
+                accountInfo.DealerTradeType__c = FieldTransformation(gda.BPCode, transferMap, 'DealerTradeType__c', '13', iflog, 'DealerTradeType');
+                accountInfo.Name = gda.CompanyName + '(P)';
+            } else {
+                accountInfo.Name = gda.CompanyName;
+            }
+            accountInfo.RecordTypeId = '012280000005gnE';
+            // accountInfo.DisableDate__c = gda.ApplyType == '1' ? Date.today() : null;
+            // 灏嗕唬鐞嗗晢鐨勫悎浣滀紮浼村鎴疯缃负鍋�
+            if (gda.ApplyType == '1') {
+                accountInfo.DisableDate__c = Date.today();
+                accountInfo.IsPartner = false; //灏嗕唬鐞嗗晢鐨勫悎浣滀紮浼村鎴疯缃负False
+                accountInfo.ProhibitionAccount__c = true;
+            }
+            // 灏嗕唬鐞嗗晢鐨勫悎浣滀紮浼村鎴疯缃负鍋�
+            accountInfo.Dealer_Type__c = NFMUtil.getMapValue(transferMap, 'Dealer_Type__c', gda.AgentType, iflog);
+            accountInfo.EnglishAddress__c = gda.RegisterAddress;
+        } else if (gda.BPType == '22') {
+            accountInfo.RecordTypeId = '01228000000TF3Q'; //澶栬锤鍏徃
+            accountInfo.Name = gda.CompanyName;
+            accountInfo.EnglishAddress__c = gda.STR_SUPPL1;
+        } else if (gda.BPType == '24') { //鍏ㄥ浗浼佷笟鐢ㄦ埛(澶у鎴�)
+            accountInfo.Name = gda.CompanyName;
+            accountInfo.FacilityName__c = gda.CompanyName;
+            accountInfo.DivisionName__c = '鏃�';
+            accountInfo.DivisionName_D__c = '鏃�';
+
+            if (String.isNotBlank(gda.Postal)) {
+                accountInfo.PostCode__c = gda.Postal;
+                accountInfo.PostCodeD__c = gda.Postal;
+            }
+
+
+
+            // 鍒嗛攢娓犻亾-鐩撮攢
+            if ('42'.equals(gda.VTWEG)) {
+                // IE鐩撮攢
+                accountInfo.CustomerSource__c = gda.AccountSource; //瀹㈡埛鏉ユ簮 銆怌ustomerSource銆戞坊鍔犻�夐」鍊� 鐩撮攢銆佷唬鐞嗗晢
+                accountInfo.TargetCustomer__c = gda.TargetCustomer ? '鐩爣' : '闈炵洰鏍�'; //瀹㈡埛绫诲瀷
+                accountInfo.compo_Acc__c = gda.IsCOMPO ? 'COMPO瀹㈡埛' : '闈濩OMPO瀹㈡埛'; //COMPO瀹㈡埛
+                accountInfo.UserType__c = gda.UserType; //鐢ㄦ埛灞炴��
+                accountInfo.RecordTypeId = accountRecordTypeMap.get('IE_Account'); //IE鐩撮攢 //'0120T0000003Cxt';
+                accountInfo.FacilityNameD__c = gda.CompanyName;
+                Map < String, String > subuseMap = getSubuseMap();
+                accountInfo.IsNew__c = false;
+                if (subuseMap.containsKey(gda.COMPOSubuse)) {
+                    String industryC_MarketVerticals_Use = subuseMap.get(gda.COMPOSubuse);
+                    List < String > fieldList = industryC_MarketVerticals_Use.split(';');
+                    accountInfo.Sub_Use__c = fieldList[0];
+                    accountInfo.Sub_UseD__c = fieldList[0];
+                    accountInfo.IndustryC__c = fieldList[1];
+                    accountInfo.IndustryCD__c = fieldList[1];
+                    accountInfo.MarketVerticals__c = fieldList[2];
+                    accountInfo.MarketVerticalsD__c = fieldList[2];
+                    accountInfo.Use__c = fieldList[3];
+                    accountInfo.UseD__c = fieldList[3];
+
+                }
+
+                if (gda.ApplyType == '1') {
+                    accountInfo.DisableDate__c = Date.today();
+                    accountInfo.IsPartner = false;
+                    accountInfo.AccountStatus__c = 'Cancel';
+                    accountInfo.AccountStatusD__c = 'Cancel';
+                }
+            } else {
+                String keyAccount = FieldTransformation(gda.BPCode, transferMap, 'KeyAccount__c', gda.KeyAccount, iflog, 'KeyAccount');
+                String marketVerticals = FieldTransformation(gda.BPCode, transferMap, 'MarketVerticals__c', gda.MarketVerticals, iflog, 'MarketVerticals');
+                String use = FieldTransformation(gda.BPCode, transferMap, 'Use__c', gda.Use, iflog, 'Use');
+                String industry = FieldTransformation(gda.BPCode, transferMap, 'IndustryC__c', gda.Industry, iflog, 'Industry');
+                accountInfo.KeyAccount__c = keyAccount;
+                accountInfo.IndustryC__c = industry;
+                accountInfo.IndustryCD__c = industry;
+
+                accountInfo.MarketVerticals__c = marketVerticals;
+                accountInfo.MarketVerticalsD__c = marketVerticals;
+                accountInfo.Use__c = use;
+                accountInfo.UseD__c = use;
+                accountInfo.Sub_Use__c = gda.SubUseEnterprise;
+                accountInfo.Sub_UseD__c = gda.SubUseEnterprise;
+                accountInfo.NationalEnterpriseUser__c = true;
+
+                accountInfo.ExportRegulatedCustomer__c = false;
+                if (gda.ExportRegulatedCustomer == '1') {
+                    accountInfo.ExportRegulatedCustomer__c = true;
+                }
+                if (productSegment == 'BS') {
+                    accountInfo.RecordTypeId = '01228000000TdF1'; //瀹㈡埛BS
+                } else if (productSegment == 'ANI') {
+                    accountInfo.RecordTypeId = '01228000000TdFL'; //瀹㈡埛ANI
+                } else if (productSegment == 'IE') {
+                    accountInfo.RecordTypeId = '01228000000TdF6'; //瀹㈡埛IE
+                } else if (productSegment == 'NDT') {
+                    accountInfo.RecordTypeId = '01228000000TdFG'; //瀹㈡埛NDT
+                } else if (productSegment == 'RVI') {
+                    accountInfo.RecordTypeId = '01228000000TdFB'; //瀹㈡埛RVI
+                }
+            }
+
+        }
+
+        accountInfo.ProductSegment__c = productSegment;
+        accountInfo.Province__c = gda.Region;
+        accountInfo.MobilePhoneNumber__c = gda.Mobilephone;
+        accountInfo.EnglishName__c = gda.CompanyEnglishName;
+        accountInfo.EnglishNameD__c = gda.CompanyEnglishName;
+        accountInfo.City__c = gda.City;
+        accountInfo.CityD__c = gda.City;
+        accountInfo.Address1__c = gda.RegisterAddress;
+        accountInfo.Address1D__c = gda.RegisterAddress;
+        accountInfo.Phone = gda.Phone;
+        accountInfo.PhoneD__c = gda.Phone;
+        accountInfo.Fax = gda.Fax;
+        accountInfo.FaxD__c = gda.Fax;
+        accountInfo.stautesD__c = 'Pass';
+        system.debug('AccountValueAssignment---End');
+        return accountInfo;
+    }
+
+    public static String GetLog(String logstr, GeData gda) {
+        logstr += '绠$悊缂栫爜:' + gda.BPCode;
+        logstr += '\n鍙樻洿绫诲瀷:' + gda.ApplyType;
+        logstr += '\n瀹㈡埛绫诲瀷:' + gda.BPType;
+        if (gda.BPType == '23') {
+            logstr += '\n缁忛攢鍟嗗垎绫�:' + gda.AgentType;
+        }
+        return logstr;
+    }
+
+    public static Map < String, Dealer_Discount__c > getExistDealerDiscountMap(List < String > bpCodeList) {
+        Map < String, Dealer_Discount__c > result = new Map < String, Dealer_Discount__c > ();
+        //鏌ユ壘瀛樺湪鐨勪唬鐞嗗晢鎶樻墸
+        List < Dealer_Discount__c > dealerDiscounts = [Select Id, Name, LatitudeValue__c, Valid_Date_From__c,
+            Valid_Date_From2__c, Valid_Date_To__c, Valid_Date_To2__c
+            from Dealer_Discount__c
+            where DimensionValue1__c In: bpCodeList
+        ];
+
+
+        if (dealerDiscounts.size() > 0) {
+
+            for (Dealer_Discount__c dealerDis: dealerDiscounts) {
+
+                result.put(dealerDis.LatitudeValue__c, dealerDis);
+            }
+        }
+        return result;
+    }
+
+
+    public static Map < String, String > getRecordTypeMap() {
+        Map < String, String > result = new Map < String, String > ();
+        List < RecordType > recordTypeList = [select Id, DeveloperName from RecordType where IsActive = true and SobjectType = 'Account'];
+        if (recordTypeList.size() > 0) {
+            for (RecordType recordType: recordTypeList) {
+                result.put(recordType.DeveloperName, recordType.Id);
+            }
+        }
+        return result;
+    }
+
+    public static void deleteDealerDiscount(Map < String, String > satisfyBsDealerDiscountMap, Map < String, Dealer_Discount__c > existDealerDiscountMap) {
+        List < Dealer_Discount__c > dealerDiscountList = new List < Dealer_Discount__c > ();
+        for (String key: existDealerDiscountMap.keySet()) {
+
+            if (!satisfyBsDealerDiscountMap.containsKey(key)) {
+                dealerDiscountList.add(existDealerDiscountMap.get(key));
+            }
+        }
+        if (dealerDiscountList != null) {
+            delete dealerDiscountList;
+        }
+
+    }
+
+    /**
+     * [getSubuseMap description]
+     * @return [description]
+     */
+    public static Map < String, String > getSubuseMap() {
+
+        // Sub_Use;IndustryC;MarketVerticals;Use
+        Map < String, String > subuseMap = new Map < String, String > ();
+        subuseMap.put('I045', '鍖荤枟鍣ㄦ;Medical Device/Equipment;Manufacturing;(Manufacturing) Other');
+        subuseMap.put('I046', '婵�鍏夊姞宸�;Other;Manufacturing;(Manufacturing) Other');
+        subuseMap.put('I047', '鍒惰嵂;Pharmaceutical;Manufacturing;(Manufacturing) Other');
+        subuseMap.put('I048', '鍔ㄦ鐗�;Food/Feed/Agriculture;Other;(Other) Other');
+        subuseMap.put('I049', '鏂拌兘婧愭苯杞�;Automotive;Manufacturing;Automotive Body/Engine');
+        subuseMap.put('I050', '5G-PCB;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I051', '5G-鍗婂浣�;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I052', '5G-鍏朵粬;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I053', 'Compo-鍗婂浣�-鍓嶉亾;Electronics;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I054', 'Compo-鍗婂浣�-涓湡;Electronics;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I055', 'Compo-鍗婂浣�-鍚庨亾;Electronics;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I056', 'Compo-FPD;Electronics;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I057', 'Compo-3D 娴嬮噺浠�;Electronics;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I058', 'Compo-娴嬭瘯浠櫒;Electronics;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I059', 'Compo-鎷夋浖鍏夎氨浠�;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I060', 'Compo-琛�娑�;Medical Device/Equipment;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I061', 'Compo-灏挎恫/绮究;Medical Device/Equipment;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I062', 'Compo-缁嗚優瀛�;Medical Device/Equipment;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I063', 'Compo-閬椾紶瀛�;Medical Device/Equipment;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I064', 'Compo-鐥呯悊;Medical Device/Equipment;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I065', 'Compo-鐢熸畺;Medical Device/Equipment;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I066', 'Compo-楂樼鏄惧井闀�;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I067', 'Compo-缁嗚優瑙傚療;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I068', 'Compo-鐢靛瓙鏄惧井闀�;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I069', 'Compo-楂樺唴娑�;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I070', 'Compo-娴佸紡缁嗚優浠�;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I071', 'Compo-ODM;Other;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I072', 'Compo-绮惧噯鍖荤枟;Academic Research;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I073', 'Compo-鍏朵粬;Other;Manufacturing;(Manufacturing)OEM');
+        subuseMap.put('I038', '鐢靛瓙绫籣鍏朵粬;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I036', '鐢靛瓙閮ㄥ搧;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I035', '鍗婂浣�;Electronics;Manufacturing;Semiconductor');
+        subuseMap.put('I037', '澶槼鑳�;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I041', '鐭虫补鍦拌川;Mining/Geology;Natural Resources;Geology : Geological Surveys');
+        subuseMap.put('I043', '閲嶅伐璁惧;Fabricated Metal Manufacturing;Manufacturing;(Manufacturing) Other');
+        subuseMap.put('I044', '鏉愭枡绫籣鍏朵粬;Academic Research;Manufacturing;Industrial Scientific research');//闇�鐗规畩澶勭悊锛氭潗鏂欑被_鍏朵粬
+        subuseMap.put('I042', '浜旈噾妯″叿;Metal Manufacturing;Manufacturing;Machined Parts');
+        subuseMap.put('I039', '閲戝睘;Metal Manufacturing;Manufacturing;Casting');
+        subuseMap.put('I033', 'LED;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I034', 'FPD;Electronics;Manufacturing;Electronic Device');
+        subuseMap.put('I040', '姹借溅;Automotive;Manufacturing;Automotive Body/Engine');
+
+        return subuseMap;
+    }
+    // public static Map < String, String > getSubuseMap() {
+    //     Map < String, String > subuseMap = new Map < String, String > ();
+    //     subuseMap.put('I045', '鍖荤枟鍣ㄦ_Medical Device/Equipment_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('I046', '婵�鍏夊姞宸Other_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('I047', '鍒惰嵂_Pharmaceutical_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('I048', '鍔ㄦ鐗Food/Feed/Agriculture_Other_(Other) Other');
+    //     subuseMap.put('I049', '鏂拌兘婧愭苯杞Automotive_Manufacturing_Automotive Body/Engine');
+    //     subuseMap.put('I050', '5G-PCB_Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I051', '5G-鍗婂浣揰Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I052', '5G-鍏朵粬_Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I053', 'Compo-鍗婂浣�-鍓嶉亾_Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I054', 'Compo-鍗婂浣�-涓湡_Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I055', 'Compo-鍗婂浣�-鍚庨亾_Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I056', 'Compo-FPD_Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I057', 'Compo-3D 娴嬮噺浠猒Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I058', 'Compo-娴嬭瘯浠櫒_Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I059', 'Compo-鎷夋浖鍏夎氨浠猒Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I060', 'Compo-琛�娑瞋Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I061', 'Compo-灏挎恫/绮究_Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I062', 'Compo-缁嗚優瀛Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I063', 'Compo-閬椾紶瀛Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I064', 'Compo-鐥呯悊_Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I065', 'Compo-鐢熸畺_Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I066', 'Compo-楂樼鏄惧井闀淿Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I067', 'Compo-缁嗚優瑙傚療_Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I068', 'Compo-鐢靛瓙鏄惧井闀淿Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I069', 'Compo-楂樺唴娑礯Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I070', 'Compo-娴佸紡缁嗚優浠猒Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I071', 'Compo-ODM_Other_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I072', 'Compo-绮惧噯鍖荤枟_Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I073', 'Compo-鍏朵粬_Other_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('I038', '鐢靛瓙绫籣鍏朵粬_Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I036', '鐢靛瓙閮ㄥ搧_Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I035', '鍗婂浣揰Electronics_Manufacturing_Semiconductor');
+    //     subuseMap.put('I037', '澶槼鑳絖Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I041', '鐭虫补鍦拌川_Mining/Geology_Natural Resources_Geology : Geological Surveys');
+    //     subuseMap.put('I043', '閲嶅伐璁惧_Fabricated Metal Manufacturing_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('I044', '鏉愭枡绫籣鍏朵粬_Academic Research_Manufacturing_Industrial Scientific research');//闇�鐗规畩澶勭悊锛氭潗鏂欑被_鍏朵粬
+    //     subuseMap.put('I042', '浜旈噾妯″叿_Metal Manufacturing_Manufacturing_Machined Parts');
+    //     subuseMap.put('I039', '閲戝睘_Metal Manufacturing_Manufacturing_Casting');
+    //     subuseMap.put('I033', 'LED_Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I034', 'FPD_Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('I040', '姹借溅_Automotive_Manufacturing_Automotive Body/Engine');
+
+    //     return subuseMap;
+    // }
+
+    // public static Map < String, String > getSubuseMap() {
+    //     Map < String, String > subuseMap = new Map < String, String > ();
+    //     subuseMap.put('鍖荤枟鍣ㄦ', 'Medical Device/Equipment_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('婵�鍏夊姞宸�', 'Other_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('鍒惰嵂', 'Pharmaceutical_Manufacturing_(Manufacturing) Other');
+    //     subuseMap.put('鍔ㄦ鐗�', 'Food/Feed/Agriculture_Other_(Other) Other');
+    //     subuseMap.put('鏂拌兘婧愭苯杞�', 'Automotive_Manufacturing_Automotive Body/Engine');
+    //     subuseMap.put('5G-PCB', 'Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('5G-鍗婂浣�', 'Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('5G-鍏朵粬', 'Electronics_Manufacturing_Electronic Device');
+    //     subuseMap.put('Compo-鍗婂浣�-鍓嶉亾', 'Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鍗婂浣�-涓湡', 'Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鍗婂浣�-鍚庨亾', 'Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-FPD', 'Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-3D 娴嬮噺浠�', 'Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-娴嬭瘯浠櫒', 'Electronics_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鎷夋浖鍏夎氨浠�', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-琛�娑�', 'Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-灏挎恫/绮究', 'Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-缁嗚優瀛�', 'Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-閬椾紶瀛�', 'Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鐥呯悊', 'Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鐢熸畺', 'Medical Device/Equipment_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-楂樼鏄惧井闀�', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-缁嗚優瑙傚療', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鐢靛瓙鏄惧井闀�', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-楂樺唴娑�', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-娴佸紡缁嗚優浠�', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-ODM', 'Other_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-绮惧噯鍖荤枟', 'Academic Research_Manufacturing_(Manufacturing)OEM');
+    //     subuseMap.put('Compo-鍏朵粬', 'Other_Manufacturing_(Manufacturing)OEM');
+
+    //     return subuseMap;
+    // }
+}
\ No newline at end of file
diff --git a/scr/classes/SBG203Rest.cls-meta.xml b/scr/classes/SBG203Rest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG203Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG203RestTest.cls b/scr/classes/SBG203RestTest.cls
new file mode 100644
index 0000000..5d396de
--- /dev/null
+++ b/scr/classes/SBG203RestTest.cls
@@ -0,0 +1,385 @@
+@isTest
+private class SBG203RestTest {
+    public static Account acc0;
+    public static Account acc1;
+    public static Account acc2;
+    public static Account acc3;
+    public static Account acc4;
+
+    public static Contact core;
+    public static Dealer_Discount__c dealerDiscount;
+    public static Dealer_Discount__c dealerDiscount1;
+    public static Dealer_Discount__c dealerDiscount2;
+    public static Dealer_Discount__c dealerDiscount3;
+    @testSetup
+    static void inittransfersData() {
+        NFMUtil.EscapeSBG001TriggerHandler = true;
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Account acc0 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            NationalEnterpriseUser__c = true
+        );
+        insert acc0;
+        Account acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '30022',
+            ParentId = acc0.Id,
+            NationalEnterpriseUser__c = true
+        );
+        Account acc2 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '30122',
+            NationalEnterpriseUser__c = true
+        );
+        Account acc5 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '30121',
+            NationalEnterpriseUser__c = true
+        );
+        Account acc3 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            CancelReason__c = 'test',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '30222',
+            NationalEnterpriseUser__c = true
+        );
+
+        Account acc4 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            PostCode__c = '123456',
+            ManagementCode_Ext__c = '300220',
+            ParentId = acc0.Id,
+            NationalEnterpriseUser__c = true
+        );
+
+        insert new List<Account> {acc1, acc2, acc3,acc4,acc5};
+
+
+        List<BatchIF_Transfer__c> transfers = new List<BatchIF_Transfer__c>();
+        BatchIF_Transfer__c transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'Dealer_Type__c';
+        transfer.External_Value__c = '22';
+        transfer.Internal_Value__c = 'Authorize dealer';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'License_Information__c';
+        transfer.Column__c         = 'LicenseType__c';
+        transfer.External_Value__c = '01';
+        transfer.Internal_Value__c = '钀ヤ笟鎵х収';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'License_Information__c';
+        transfer.Column__c         = 'LicenseType__c';
+        transfer.External_Value__c = '04';
+        transfer.Internal_Value__c = '绗簩绫诲尰鐤楀櫒姊扮粡钀ュ妗堝嚟璇�';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'License_Information__c';
+        transfer.Column__c         = 'LicenseType__c';
+        transfer.External_Value__c = '08';
+        transfer.Internal_Value__c = '杈愬皠瀹夊叏璁稿彲璇�';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'KeyAccount__c';
+        transfer.External_Value__c = '鍏ㄧ悆瀹㈡埛';
+        transfer.Internal_Value__c = 'Global Account';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'Use__c';
+        transfer.External_Value__c = 'BS11';
+        transfer.Internal_Value__c = 'Cell Biology - Cancer Research';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'MarketVerticals__c';
+        transfer.External_Value__c = '涓村簥';
+        transfer.Internal_Value__c = 'Clinical';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Account';
+        transfer.Column__c         = 'IndustryC__c';
+        transfer.External_Value__c = '鐢熺墿宸ヨ壓';
+        transfer.Internal_Value__c = 'Biotech';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProductModel__c';
+        transfer.External_Value__c = 'D';
+        transfer.Internal_Value__c = 'Delta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProductModel__c';
+        transfer.External_Value__c = 'V';
+        transfer.Internal_Value__c = 'Venta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProductModel__c';
+        transfer.External_Value__c = 'DV';
+        transfer.Internal_Value__c = 'Delta+Venta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'CertificationDetails__c';
+        transfer.Column__c         = 'ProductModel__c';
+        transfer.External_Value__c = 'F';
+        transfer.Internal_Value__c = 'FOX-IQ';
+        transfers.add(transfer);
+        insert transfers;
+
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=acc1.id,ManagementCode_Ext__c = 'C100300X');
+        insert core;
+
+        dealerDiscount = new Dealer_Discount__c();
+        dealerDiscount.DimensionValue1__c = '30022';
+        dealerDiscount.DimensionValue2__c = '灞辫タ';
+        dealerDiscount.DealerDiscountAccount__c = acc3.Id;
+        dealerDiscount.DimensionField1__c = 'Dealer_Code__c';
+        dealerDiscount.DimensionField2__c = 'Province__c';
+        dealerDiscount.Dealer_Rank__c = 49;
+        dealerDiscount.Valid_Date_From__c = Date.today().addDays(2);
+        dealerDiscount.Valid_Date_To__c = Date.today().addDays(22);
+        //dealerDiscount.Valid_Date_From2__c = Date.today().addDays(23);
+        //dealerDiscount.Valid_Date_To2__c = Date.today().addDays(33);
+        insert dealerDiscount;
+
+        dealerDiscount1 = new Dealer_Discount__c();
+        dealerDiscount1.DimensionValue1__c = '30022';
+        dealerDiscount1.DimensionValue2__c = '灞变笢';
+        dealerDiscount1.DealerDiscountAccount__c = acc3.Id;
+        dealerDiscount1.DimensionField1__c = 'Dealer_Code__c';
+        dealerDiscount1.DimensionField2__c = 'Province__c';
+        dealerDiscount1.Dealer_Rank__c = 49;
+        dealerDiscount1.Valid_Date_From__c = Date.today().addDays(-22);
+        dealerDiscount1.Valid_Date_To__c = Date.today().addDays(22);
+        dealerDiscount.Valid_Date_From2__c = Date.today().addDays(23);
+        dealerDiscount.Valid_Date_To2__c = Date.today().addDays(33);
+
+        insert dealerDiscount1;
+
+        dealerDiscount2 = new Dealer_Discount__c();
+        dealerDiscount2.DimensionValue1__c = '300220';
+        dealerDiscount2.DimensionValue2__c = '灞辫タ';
+        dealerDiscount2.DealerDiscountAccount__c = acc4.Id;
+        dealerDiscount2.DimensionField1__c = 'Dealer_Code__c';
+        dealerDiscount2.DimensionField2__c = 'Province__c';
+        dealerDiscount2.Dealer_Rank__c = 49;
+        dealerDiscount2.Valid_Date_From__c = Date.today().addDays(-22);
+        dealerDiscount2.Valid_Date_To__c = Date.today().addDays(22);
+        dealerDiscount2.Valid_Date_From2__c = Date.today().addDays(23);
+        dealerDiscount2.Valid_Date_To2__c = Date.today().addDays(33);
+
+        insert dealerDiscount2;
+
+        dealerDiscount3 = new Dealer_Discount__c();
+        dealerDiscount3.DimensionValue1__c = '300220';
+        dealerDiscount3.DimensionValue2__c = '灞变笢';
+        dealerDiscount3.DealerDiscountAccount__c = acc4.Id;
+        dealerDiscount3.DimensionField1__c = 'Dealer_Code__c';
+        dealerDiscount3.DimensionField2__c = 'Province__c';
+        dealerDiscount3.Dealer_Rank__c = 49;
+        dealerDiscount3.Valid_Date_From__c = Date.today().addDays(2);
+        dealerDiscount3.Valid_Date_To__c = Date.today().addDays(22);
+        dealerDiscount3.Valid_Date_From2__c = Date.today().addDays(23);
+        dealerDiscount3.Valid_Date_To2__c = Date.today().addDays(33);
+
+        insert dealerDiscount3;
+    }
+
+    //瀹㈡埛蹇呭~瀛楁楠岃瘉
+    static testMethod void fieldcheck00() {
+        // 24 -鐩撮攢
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+        String JsonMsg = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"24","BPCodeforeign":"3000002109","BPCode":"","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23","VTWEG":"42","AccountSource":"","UserType":"","COMPOSubuse":"","TargetCustomer":null,"IsCOMPO":null}]}';
+        
+        req.requestURI = 'services/apexrest/SBG203/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response= res;
+        SBG203Rest.execute();
+        // 24 - 鍒嗛攢
+        RestRequest req01 = new RestRequest();
+        RestResponse res01 = new RestResponse();
+        String JsonMsg01 = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"24","BPCodeforeign":"3000002109","BPCode":"","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23","VTWEG":"41","AccountSource":"","UserType":"","COMPOSubuse":"","TargetCustomer":null,"IsCOMPO":null}]}';
+        
+        req01.requestURI = 'services/apexrest/SBG203/execute';
+        req01.httpMethod = 'POST';
+        req01.requestBody = Blob.valueof(JsonMsg01);
+        RestContext.request = req01;
+        RestContext.response= res01;
+        SBG203Rest.execute();
+
+        // 23 - 鍒嗛攢
+        RestRequest req00 = new RestRequest();
+        RestResponse res00 = new RestResponse();
+        String JsonMsg00 = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"LS","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"23","BPCodeforeign":"3000002107","BPCode":"","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"","VTWEG":"41","AccountSource":"","UserType":"","COMPOSubuse":"","TargetCustomer":null,"IsCOMPO":null}]}';
+        req00.requestURI = 'services/apexrest/SBG203/execute';
+        req00.httpMethod = 'POST';
+        req00.requestBody = Blob.valueof(JsonMsg00);
+        RestContext.request = req00;
+        RestContext.response= res00;
+        SBG203Rest.execute();
+    }
+
+
+    static testMethod void insertOrUpdate_BS_Account() {
+
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+        String JsonMsg = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"LS","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"娴嬭瘯;","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":"灞辫タ","ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"23","BPCodeforeign":"3000002106","BPCode":"3000002105","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23"}]}';
+        req.requestURI = 'services/apexrest/SBG203/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response= res;
+        SBG203Rest.execute();
+
+        
+    }
+
+    static testMethod void insertOrUpdate_BS_Account00() {
+
+
+        RestRequest req00 = new RestRequest();
+        RestResponse res00 = new RestResponse();
+        String JsonMsg00 = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"LS","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"娴嬭瘯","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":"灞辫タ;灞变笢","ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"23","BPCodeforeign":"30022","BPCode":"30022","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"1","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23"}]}';
+        req00.requestURI = 'services/apexrest/SBG203/execute';
+        req00.httpMethod = 'POST';
+        req00.requestBody = Blob.valueof(JsonMsg00);
+        RestContext.request = req00;
+        RestContext.response= res00;
+        SBG203Rest.execute();
+        
+    }
+
+    static testMethod void insertOrUpdate_BS_Account01() {
+
+
+        RestRequest req00 = new RestRequest();
+        RestResponse res00 = new RestResponse();
+        String JsonMsg00 = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"LS","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"娴嬭瘯","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":"灞辫タ;灞变笢","ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"23","BPCodeforeign":"30022","BPCode":"30022","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"2","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23"}]}';
+        req00.requestURI = 'services/apexrest/SBG203/execute';
+        req00.httpMethod = 'POST';
+        req00.requestBody = Blob.valueof(JsonMsg00);
+        RestContext.request = req00;
+        RestContext.response= res00;
+        SBG203Rest.execute();
+        
+    }
+
+    //鍙樻洿(鍗忚鍙樻洿(缁忛攢鍟嗘姌鎵�)銆佽瘉鐓у彉鏇淬�佹敹璐т汉鍙樻洿(鑱旂郴浜�))(灏氭湭寮�鍙�)
+    static testMethod void insertOrUpdate_RVI_Account() {
+        // BPType=24 RVI
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+        String JsonMsg = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"BS11","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"RVI","Postal":"100010","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"鍏朵粬","License_Info":[{"WarehouseAddress":"娴嬭瘯锛�","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"澶у鎴�","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"鏁欒偛","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"0","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation;鍏朵粬","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"24","BPCodeforeign":"3000002108","BPCode":"3000002108","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23","AccountSource":"鐩撮攢","TargetCustomer":true,"IsCOMPO":true,"UserType":"鐮旂┒鎵�","COMPOSubuse":"I073","VTWEG":"41"}]}';
+        req.requestURI = 'services/apexrest/SBG203/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response= res;
+        SBG203Rest.execute();
+
+        
+    }
+    //鍙樻洿(鍗忚鍙樻洿(缁忛攢鍟嗘姌鎵�)銆佽瘉鐓у彉鏇淬�佹敹璐т汉鍙樻洿(鑱旂郴浜�))(灏氭湭寮�鍙�)
+    static testMethod void insertOrUpdate_RVI_Account01() {
+        // BPType=24 RVI
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+        String JsonMsg = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"BS11","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"RVI","Postal":"100010","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"鍏朵粬","License_Info":[{"WarehouseAddress":"娴嬭瘯锛�","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"澶у鎴�","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"鏁欒偛","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"0","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation;鍏朵粬","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"24","BPCodeforeign":"3000002108","BPCode":"3000002108","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23","AccountSource":"鍒嗛攢","TargetCustomer":true,"IsCOMPO":true,"UserType":"鐮旂┒鎵�","COMPOSubuse":"I073","VTWEG":"42"}]}';
+        req.requestURI = 'services/apexrest/SBG203/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response= res;
+        SBG203Rest.execute();
+
+        
+    }
+
+    static testMethod void insertOrUpdate_RVI_Account00() {
+    
+
+        // BPType=23 RVI
+        RestRequest req00 = new RestRequest();
+        RestResponse res00 = new RestResponse();
+        String JsonMsg00 = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"BS11","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"RVI","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"鍏朵粬","License_Info":[{"WarehouseAddress":"娴嬭瘯;","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"},{"WarehouseAddress":"","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"04","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207257","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"},{"WarehouseAddress":"","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"08","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":[{"ProSerial":"Delta鍜孷anta","Quantity":"22","ProName":"DE2000/DPO2000","Category":"閿�鍞�"}],"BusLicenseNo":"914401067299207258","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"澶у鎴�","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"鏁欒偛","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"0","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation;鍏朵粬","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"23","BPCodeforeign":"30121","BPCode":"30122","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23"}]}';
+        req00.requestURI = 'services/apexrest/SBG203/execute';
+        req00.httpMethod = 'POST';
+        req00.requestBody = Blob.valueof(JsonMsg00);
+        RestContext.request = req00;
+        RestContext.response= res00;
+        SBG203Rest.execute();
+        
+    }
+    // ANI
+    static testMethod void insertOrUpdate_ANI_Account() {
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+        String JsonMsg = '{"Monitoring":{"Tag":"MSGH","Sender":"1330","Receiver":"1592","MessageType":"SBG203","MessageGroupNumber":"20200000334093","NumberOfRecord":"1","TransmissionDateTime":"202010160915"},"Partners":[{"Z3PLTransAgrNo":"","Z3PLQualityAgrNo":"","Z3PLAuthorizedNo":"","Use":"","TransAgrVT":null,"TransAgrVF":null,"TaxNo":"914401067299207256","SubUseEnterprise":"","STR_SUPPL1":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","ServiceType":"","Remark":"骞垮窞鍏冨崌鏄疘E鐨勭绾︿唬鐞嗗晢锛屽苟涓�8鏈�25鏃ュ弬鍔犱簡FY2021 SSBG 缁忛攢鍟嗗悎瑙勫煿璁�","RegisterAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","RegionName":"","Region":"骞夸笢","QualityAgrNoVT":"","QualityAgrNoVF":"","ProductSegment":"ANI","Postal":"","Phone":"020-38730350","other3":null,"other2":null,"other1":null,"OperationProject":null,"Mobilephone":"","MarketVerticals":"","License_Info":[{"WarehouseAddress":"","ValidTo":"99991231","ValidFrom":"20151211","Principal":"鍒樻櫤閿�","other6":"","other5":"","other4":"","LicenseType":"01","ISSUEDATE1":"20151211","IssueAuthority":"","IfQuantityCtrl":false,"Exclusive1":null,"Exclusive":null,"DiagnosisScope":null,"Detail_Info":null,"BusLicenseNo":"914401067299207256","BusinessType":"鐮旂┒鍜岃瘯楠屽彂灞曪紙鍏蜂綋缁忚惀椤圭洰璇风櫥褰曞箍宸炲競鍟嗕簨涓讳綋淇℃伅鍏ず骞冲彴鏌ヨ銆備緷娉曢』缁忔壒鍑嗙殑椤圭洰锛岀粡鐩稿叧閮ㄩ棬鎵瑰噯鍚庢柟鍙紑灞曠粡钀ユ椿鍔ㄣ�傦級","BusinessScope1":"","BusinessScope":null,"BusinessAddress":"骞夸笢骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2"}],"KeyAccount":"","KATR2":"2A","Invoice_phone":"020-38730350","Industry":"","Incorporator":"鍒樻櫤閿�","Fax":"","ExportRegulatedCustomer":"","DealerTradeType":"","CustomerService":null,"Contract_Info":[{"TermContractNo":null,"SubUse":"Civil Aviation","SelableProduct":null,"SalesState":null,"SalesShopClass":null,"SalesSection":null,"DealerRate":"70","DealerRank":null,"DealerdiscountZF":null,"DealerdiscountURO":null,"DealerdiscountSP":null,"DealerdiscountOTH":null,"DealerdiscountGYN":null,"DealerdiscountGS":null,"DealerdiscountGI":null,"DealerdiscountET":null,"DealerdiscountENG":null,"DealerdiscountENF":null,"DealerdiscountBF":null,"DealerdiscountAH":null,"ContractStartDate":"20220522","ContractRegion":null,"ContractOwner":null,"ContractEndDate":null,"ContractDepartmentClass":null,"ContractDecideStartDate":null,"ContractDecideEndDate":null,"BusinessAssistant":null,"AimPriceSP":null,"AimPriceGIR":null,"AimPriceAreaSP":null,"AimPriceAreaET":null,"AimPriceAreaENG":null,"AimPriceAH":null,"AimPrice":null,"AimDivision":null,"AgencyApplicationNo":null,"AgencyApplicationDay":null}],"Consignee_Info":[{"PostalCode":"","ContactPhone":"020-38730350","ContactName":"娲尝","ContactMobilePhone":"","ContactId":"135281","ContactEnglishName":null,"ContactAddress":"骞垮窞甯傚ぉ娌冲尯澶╂渤鍖楄矾689鍙峰厜澶ч摱琛屽ぇ鍘�24灞侲2","CITY1":"骞垮窞甯�"}],"CompanyName":"骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃","CompanyEnglishName":null,"CompanyCode":"5112","Comment":"鍚屾剰","CNTag":"","City":"骞垮窞甯�","BPType":"23","BPCodeforeign":"30222","BPCode":"30222","BankName":"涓浗宸ュ晢閾惰骞垮窞绉戞妧鍥敮琛�","BankCode":"3602062719200061533","AuthorizedVT":null,"AuthorizedVF":null,"AuthorizedScope":"","Authorized_Info":null,"Approver":"Zhou Fang (鏂硅垷) (OCSM)","ApproveDate":"20200910","ApplyType":"3","Agreement4":null,"Agreement3":null,"Agreement2":null,"Agreement1":null,"AgentValidTo":"","AgentValidFrom":"","AgentType":"23"}]}';
+        req.requestURI = 'services/apexrest/SBG203/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response= res;
+        SBG203Rest.execute();    
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG203RestTest.cls-meta.xml b/scr/classes/SBG203RestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG203RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG204Rest.cls b/scr/classes/SBG204Rest.cls
new file mode 100644
index 0000000..05378fa
--- /dev/null
+++ b/scr/classes/SBG204Rest.cls
@@ -0,0 +1,349 @@
+@RestResource(urlMapping = '/SBG204/*')
+global with sharing class SBG204Rest {
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData[] GeData;
+    }
+
+    global class GeData {
+
+        public String MaterialNo;         //鐗╂枡鍙�
+
+        public String RegisterNo;         //娉ㄥ唽璇佸彿
+        public String RegisterNoClass_New; //娉ㄥ唽璇佸彿缁忚惀鑼冨洿缂栧彿(鏂�)
+        public String RegisterNoClass_Old; //娉ㄥ唽璇佸彿缁忚惀鑼冨洿缂栧彿(鏃�)
+
+        public String ValidFrom;          //娉ㄥ唽璇佸彿鏁堟湡浠�
+        public String ValidTo;            //娉ㄥ唽璇佸彿鏁堟湡鑷�
+        public String MedPrdClass;        //鍖荤枟鍣ㄦ鍒嗙被
+
+        public String Model;              //浜у搧鍨嬪彿
+        public String ProductName;        //浜у搧鍚嶇О(濮旀墭浜у搧鍚嶇О)
+        public String PrdCompanyLicense;  //鐢熶骇浼佷笟璁稿彲璇佸彿/澶囨鍑瘉鍙�
+        public String PrdCompanyAddr;     //鐢熶骇浼佷笟鍦板潃
+        public String ClinicalCode;       //鍨嬪彿瑙勬牸
+        public String REG_Name;           // 娉ㄥ唽浜哄悕绉�
+        public String REG_ADD;            // 娉ㄥ唽浜轰綇鎵�
+
+
+
+        public String AuthorizedCompany;  //濮旀墭鏂逛紒涓氬悕绉�
+
+        public String ApprovedDate;       //濮旀墭鎵瑰噯鏃ユ湡
+        public String Z3PLAuthorized;    //鏄惁3PL濮旀墭浜у搧
+        public String AuthorizedCompany_SH;
+        public String ApprovedDate_SH;
+        public String YXQX;
+
+        public String Other1;
+        public String Other2;
+        public String Other3;
+
+        public String MaterialGroup;      //鐗╂枡缁�
+        public String MaterialStatus;     //鐗╂枡鐘舵��
+        public String RegisterNoStatus;   //娉ㄥ唽璇佸彿鐘舵��
+
+        public String Unit;               //鍗曚綅(鍩烘湰鍗曚綅)
+        public String StroageCondition;   //鍌ㄥ瓨鏉′欢
+        public String TransCondition;     //杩愯緭鏉′欢
+        public String Z3PLAuthorizedNo;   //3PL涓氬姟濮旀墭鍗忚鍙�
+        public String PrdValidFrom;       //濮旀墭浜у搧鏁堟湡浠�
+        public String PrdValidTo;         //濮旀墭浜у搧鏁堟湡鑷�
+        public String BusinessScope;      //缁忚惀鑼冨洿
+
+        public String MaterialStatusType;  // 鐘舵�� 1:鍙洿鏂扮墿鏂欑姸鎬�
+
+
+        public String APP_NAME_BJ;   //  鍖椾含棣栬惀瀹℃牳浜�
+        public String APP_DATE_BJ;   //  鍖椾含瀹℃牳鏃ユ湡
+        public String APP_RSLT_BJ;   //  鍖椾含棣栬惀瀹℃牳缁撴灉
+        public String APP_NAME_SH;   //  涓婃捣棣栬惀瀹℃牳浜�
+        public String APP_DATE_SH;   //  涓婃捣瀹℃牳鏃ユ湡
+        public String APP_RSLT_SH;   //  涓婃捣棣栬惀瀹℃牳缁撴灉
+        public String APP_NAME_GZ;   //  骞垮窞棣栬惀瀹℃牳浜�
+        public String APP_DATE_GZ;   //  骞垮窞瀹℃牳鏃ユ湡
+        public String APP_RSLT_GZ;   //  骞垮窞棣栬惀瀹℃牳缁撴灉
+        public String APP_NAME_OSH;   //  OSH棣栬惀瀹℃牳浜�
+        public String APP_DATE_OSH;   //  OSH瀹℃牳鏃ユ湡
+        public String APP_RSLT_OSH;   //  OSH棣栬惀瀹℃牳缁撴灉
+        public String PROD_ADD;       // 鐢熶骇鍦板潃
+        public String STRU_COM;      // 缁撴瀯鍙婄粍鎴�
+        public String ADOPT_RANGE;    // 閫傜敤鑼冨洿
+
+
+    }
+
+    @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG204', ges.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        String jsonResponse = '{"status": "0", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main (String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG204';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String groupNumber = rowData.MessageGroupNumber__c;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> GeDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+
+        if (GeDataList == null || GeDataList.size() == 0) {
+            return;
+        }
+
+        Map<String, String> transferMap = new Map<String, String>();
+        List<BatchIF_Transfer__c> transferList = [select Table__c,
+                                  Column__c,
+                                  External_value__c,
+                                  Internal_value__c
+                                  from BatchIF_Transfer__c
+                                  where Dropped_Flag__c = false
+                                          and (Table__c = 'Product_Register__c'
+                                                  or Table__c = 'Product2')];
+        for (BatchIF_Transfer__c t : transferList) {
+            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+
+            List<String> productNoList = new List<String>();
+            List<String> mD5KeyList = new List<String>();
+            List<String> registerNoDelList = new List<String>();
+            List<GeData> satisfyGeData = new List<GeData>();
+            for (GeData data : GeDataList) {
+                //浣滀负浜у搧娉ㄥ唽璇佺殑鍞竴鏍囪瘑蹇呴』閮芥湁鍊兼墠绠楁纭殑浜у搧娉ㄥ唽璇�
+                if (String.isNotBlank(data.RegisterNo) && String.isNotBlank(data.ValidFrom)) {
+                    mD5KeyList.add(MD5Encrypt(data.RegisterNo,data.ValidFrom));
+                } else {
+                    iflog.ErrorLog__c += 'RegisterNo/ValidFrom is required,This data is skipped.\n';
+                    continue;
+                }
+
+                //浜у搧Code鐨凩ist
+                if (String.isNotBlank(data.MaterialNo)) {
+                    Pattern pattern = Pattern.compile('^[0-9]*$');  
+                    Matcher isNum = pattern.matcher(data.MaterialNo); 
+                    if (isNum.matches()) {
+                        data.MaterialNo = data.MaterialNo.leftPad(18, '0');
+                    }
+                    productNoList.add(data.MaterialNo);
+                } else {
+                    iflog.ErrorLog__c += 'RegisterNo[ ' + data.RegisterNo + ' ] of MaterialNo is required,This data is skipped.\n';
+                    continue;
+                }
+
+                // 鍒犻櫎娉ㄥ唽璇佸叧绯籐ist
+                if (String.isNotBlank(data.RegisterNo)) {
+                    registerNoDelList.add(MD5Encrypt(data.RegisterNo,data.ValidFrom));
+                }
+
+                satisfyGeData.add(data);
+
+            }
+
+            Map<String, Product2> productMap = new Map<String, Product2>();
+            Map<String, Product_Register__c> registerMap = new Map<String, Product_Register__c>();
+
+            // 浜у搧
+            List<Product2> productList = [select id, ProductCode from Product2 where ProductCode = :productNoList];
+            for (Product2 product : productList) {
+                productMap.put(product.ProductCode, product);
+            }
+
+            List<Product_Register__c> registerList2 = [select id, Name, MD5EncryptionKey__c from Product_Register__c where MD5EncryptionKey__c = :mD5KeyList];
+            for (Product_Register__c register : registerList2) {
+                registerMap.put(register.MD5EncryptionKey__c, register);
+            }
+            List<Product_Register_Link__c> prlinkList = new List<Product_Register_Link__c>();
+
+            prlinkList = [select id,
+                          Product2__c,
+                          Product2__r.ProductCode,
+                          Product_Register__c,
+                          Product_Register__r.Name
+                          from Product_Register_Link__c
+                          where Product_Register__r.MD5EncryptionKey__c in :registerNoDelList];
+
+            Map<String, Product2> upd_productMap = new Map<String, Product2>();
+            Map<String, Product_Register__c> ups_registerMap = new Map<String, Product_Register__c>();
+            Map<String, Product_Register_Link__c> ins_linkMap = new Map<String, Product_Register_Link__c>();
+
+
+            for (GeData data : satisfyGeData) {
+
+                Product2 prd = new Product2();
+                Product_Register__c pr = new Product_Register__c();
+
+
+                if (String.isNotBlank(data.MaterialNo)) {
+
+                    if (productMap.containsKey(data.MaterialNo)) {
+
+                        prd = productMap.get(data.MaterialNo);
+                        prd.Product_CCode__c = data.Model;
+                        String prdCompanyAddr = data.REG_Name;
+
+                        if (String.isNotBlank(prdCompanyAddr)) {
+                            if (prdCompanyAddr.indexOf(';') != -1) {
+                                String splitPrdCompanyAddr =  prdCompanyAddr.split(';')[0];
+                                prd.Factory__c = splitPrdCompanyAddr.indexOf(':') == -1 ?  splitPrdCompanyAddr : splitPrdCompanyAddr.split(':')[1];
+                            } else {
+                                prd.Factory__c = prdCompanyAddr;
+                            }
+                        } else {
+                            prd.Factory__c = prdCompanyAddr;
+                        }
+                    } else {
+
+                        iflog.ErrorLog__c += 'OTCode[' + data.MaterialNo + ']涓嶅瓨鍦╘n';
+                        continue;
+                    }
+
+                    upd_productMap.put(data.MaterialNo, prd);
+
+                    logstr += 'Product:' + data.MaterialNo;
+                }
+                if (String.isNotBlank(data.RegisterNo) ) {
+                    String mD5key = MD5Encrypt(data.RegisterNo,data.ValidFrom);
+                    if (registerMap.containsKey(mD5key)) {
+                        pr = registerMap.get(mD5key);
+                    } 
+                    pr.MD5EncryptionKey__c    = mD5key;                  //浜у搧娉ㄥ唽璇佸彿鐨勫敮涓�鏍囪瘑
+                    pr.Name                   = data.RegisterNo;         //娉ㄥ唽璇佸彿
+                    pr.IsFromSPO__c           = true;
+                    pr.RegisterNoClass_New__c = data.RegisterNoClass_New; //娉ㄥ唽璇佸彿鍒嗙被缂栧彿(鏂�)
+                    pr.RegisterNoClass_Old__c = data.RegisterNoClass_Old; //娉ㄥ唽璇佸彿鍒嗙被缂栧彿(鏃�)
+                    pr.ValidFrom__c           = NFMUtil.parseStr2Date(data.ValidFrom);          //娉ㄥ唽璇佸彿鏁堟湡浠�
+                    pr.ValidTo__c             = NFMUtil.parseStr2Date(data.ValidTo);            //娉ㄥ唽璇佸彿鏁堟湡鑷�
+                    pr.MedPrdClass__c         = data.MedPrdClass;        //鍖荤枟鍣ㄦ鍒嗙被
+                    pr.PrdCompanyLicense__c   = data.PrdCompanyLicense;  //鐢熶骇浼佷笟璁稿彲璇佸彿/澶囨鍑瘉鍙�
+                    pr.PrdCompanyAddr__c      = data.PrdCompanyAddr;     //鐢熶骇浼佷笟鍦板潃
+                    pr.ClinicalProductCode__c = data.ClinicalCode;       //鍨嬪彿瑙勬牸
+                    pr.RegistrantName__c = data.REG_Name ;               // 娉ㄥ唽浜哄悕绉�
+                    pr.RegistrantResidence__c = data.REG_ADD ;           // 娉ㄥ唽浜轰綇鎵�
+                    ups_registerMap.put(data.RegisterNo, pr); 
+                    logstr += '  Register:' + data.RegisterNo + '\n';
+                }
+            }
+            
+            if (upd_productMap.keySet().size() > 0) update upd_productMap.values();
+            if (ups_registerMap.keySet().size() > 0) upsert ups_registerMap.values();
+
+            // 鍒犻櫎娉ㄥ唽璇佸彿涓嬫墍鏈夌墿鏂�
+            List<Product_Register_Link__c> delList = new List<Product_Register_Link__c>();
+            for (Product_Register_Link__c prlc : prlinkList) {
+
+                delList.add(prlc);
+
+            }
+
+            if (delList.size() > 0 )    delete delList;
+
+
+            // 鍙栧緱鎵�鏈夋敞鍐岃瘉ID
+            registerList2 = [select id, Name, MD5EncryptionKey__c from Product_Register__c where MD5EncryptionKey__c = :mD5KeyList];
+            for (Product_Register__c register : registerList2) {
+                registerMap.put(register.MD5EncryptionKey__c, register);
+            }
+
+            // 浜у搧鍜屾敞鍐岃瘉鍏崇郴琛�
+            for (GeData data : satisfyGeData) {
+                if (!productMap.containsKey(data.MaterialNo)) {
+                    // 浜у搧涓嶅瓨鍦ㄧ殑鍦哄悎
+                    continue;
+                }
+
+                String prlink = data.MaterialNo + '_' + data.RegisterNo;
+                Product_Register_Link__c prl = new Product_Register_Link__c();
+                prl.Product2__c = productMap.get(data.MaterialNo).id;
+                prl.Product_Register__c = registerMap.get(MD5Encrypt(data.RegisterNo,data.ValidFrom)).id;
+                prl.If_Delete__c = false;
+                ins_linkMap.put(prlink, prl);
+
+            }
+
+            if (ins_linkMap.keySet().size() > 0) insert ins_linkMap.values();
+
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+
+        } catch (Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBG204_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBG204_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+    //灏�"浜у搧娉ㄥ唽璇佸彿"涓�"娉ㄥ唽璇佸彿鏁堟湡浠�"杩涜MD5鍔犲瘑浣滀负浜у搧娉ㄥ唽璇佺殑鍞竴鏍囪瘑
+    public static String MD5Encrypt(String RegisterNo,String ValidFrom){
+        if (String.isBlank(RegisterNo) || String.isBlank(ValidFrom)) {
+            return null;
+        }
+        String result = '';
+        //娉ㄥ唽璇佸彿鏁堟湡浠�
+        Date  startOfDay = NFMUtil.parseStr2Date(ValidFrom);
+        //鏃堕棿鎴�
+        Long timestamp = Datetime.newInstanceGmt(startOfDay.year(), startOfDay.Month(),startOfDay.Day(), 0, 0, 0).getTime();
+        //MD5杞寲
+        String mD5EncryptionKey = EncodingUtil.convertToHex(Crypto.generateDigest('MD5', Blob.valueOf(RegisterNo+timestamp))).toUpperCase();
+        result = mD5EncryptionKey;
+        return result;
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG204Rest.cls-meta.xml b/scr/classes/SBG204Rest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG204Rest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG204RestExecute.cls b/scr/classes/SBG204RestExecute.cls
new file mode 100644
index 0000000..45a8211
--- /dev/null
+++ b/scr/classes/SBG204RestExecute.cls
@@ -0,0 +1,122 @@
+global with sharing class SBG204RestExecute {
+    
+
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData[] GeData;
+    }
+
+    global class GeData {
+
+        public String MaterialNo;         //鐗╂枡鍙�
+
+        public String RegisterNo;         //娉ㄥ唽璇佸彿
+        public String RegisterNoClass_New; //娉ㄥ唽璇佸彿缁忚惀鑼冨洿缂栧彿(鏂�)
+        public String RegisterNoClass_Old; //娉ㄥ唽璇佸彿缁忚惀鑼冨洿缂栧彿(鏃�)
+
+        public String ValidFrom;          //娉ㄥ唽璇佸彿鏁堟湡浠�
+        public String ValidTo;            //娉ㄥ唽璇佸彿鏁堟湡鑷�
+        public String MedPrdClass;        //鍖荤枟鍣ㄦ鍒嗙被
+
+        public String Model;              //浜у搧鍨嬪彿
+        public String ProductName;        //浜у搧鍚嶇О(濮旀墭浜у搧鍚嶇О)
+        public String PrdCompanyLicense;  //鐢熶骇浼佷笟璁稿彲璇佸彿/澶囨鍑瘉鍙�
+        public String PrdCompanyAddr;     //鐢熶骇浼佷笟鍦板潃
+        public String ClinicalCode;       //鍨嬪彿瑙勬牸
+        public String REG_Name;           // 娉ㄥ唽浜哄悕绉�
+        public String REG_ADD;            // 娉ㄥ唽浜轰綇鎵�
+
+
+
+        public String AuthorizedCompany;  //濮旀墭鏂逛紒涓氬悕绉�
+
+        public String ApprovedDate;       //濮旀墭鎵瑰噯鏃ユ湡
+        public String Z3PLAuthorized;    //鏄惁3PL濮旀墭浜у搧
+        public String AuthorizedCompany_SH;
+        public String ApprovedDate_SH;
+        public String YXQX;
+
+        public String Other1;
+        public String Other2;
+        public String Other3;
+
+        public String MaterialGroup;      //鐗╂枡缁�
+        public String MaterialStatus;     //鐗╂枡鐘舵��
+        public String RegisterNoStatus;   //娉ㄥ唽璇佸彿鐘舵��
+
+        public String Unit;               //鍗曚綅(鍩烘湰鍗曚綅)
+        public String StroageCondition;   //鍌ㄥ瓨鏉′欢
+        public String TransCondition;     //杩愯緭鏉′欢
+        public String Z3PLAuthorizedNo;   //3PL涓氬姟濮旀墭鍗忚鍙�
+        public String PrdValidFrom;       //濮旀墭浜у搧鏁堟湡浠�
+        public String PrdValidTo;         //濮旀墭浜у搧鏁堟湡鑷�
+        public String BusinessScope;      //缁忚惀鑼冨洿
+
+        public String MaterialStatusType;  // 鐘舵�� 1:鍙洿鏂扮墿鏂欑姸鎬�
+
+
+        public String APP_NAME_BJ;   //  鍖椾含棣栬惀瀹℃牳浜�
+        public String APP_DATE_BJ;   //  鍖椾含瀹℃牳鏃ユ湡
+        public String APP_RSLT_BJ;   //  鍖椾含棣栬惀瀹℃牳缁撴灉
+        public String APP_NAME_SH;   //  涓婃捣棣栬惀瀹℃牳浜�
+        public String APP_DATE_SH;   //  涓婃捣瀹℃牳鏃ユ湡
+        public String APP_RSLT_SH;   //  涓婃捣棣栬惀瀹℃牳缁撴灉
+        public String APP_NAME_GZ;   //  骞垮窞棣栬惀瀹℃牳浜�
+        public String APP_DATE_GZ;   //  骞垮窞瀹℃牳鏃ユ湡
+        public String APP_RSLT_GZ;   //  骞垮窞棣栬惀瀹℃牳缁撴灉
+        public String APP_NAME_OSH;   //  OSH棣栬惀瀹℃牳浜�
+        public String APP_DATE_OSH;   //  OSH瀹℃牳鏃ユ湡
+        public String APP_RSLT_OSH;   //  OSH棣栬惀瀹℃牳缁撴灉
+        public String PROD_ADD;       // 鐢熶骇鍦板潃
+        public String STRU_COM;      // 缁撴瀯鍙婄粍鎴�
+        public String ADOPT_RANGE;    // 閫傜敤鑼冨洿
+
+
+    }
+
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main (String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBG204';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String groupNumber = rowData.MessageGroupNumber__c;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> GeDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+
+        if (GeDataList == null || GeDataList.size() == 0) {
+            return;
+        }
+
+        for (GeData data : GeDataList) {
+        	if (String.isNotBlank(data.ValidFrom)) {
+        		String validFrom = data.ValidFrom;
+        		// validFrom = String.valueOf(Datetime.valueOf(validFrom));
+        		List<String> validFromList = validFrom.split(' ')[0].split('/');//6/12/2017 12:00:00 AM 
+        		data.ValidFrom = '' +validFromList[2] + validFromList[1] +validFromList[0];
+        		// System.debug('validFrom--->'+validFrom);
+        	}
+        	if (String.isNotBlank(data.ValidTo)){
+        		String validTo = data.ValidTo;
+        		List<String> validFromList = validTo.split(' ')[0].split('/');//6/12/2017 12:00:00 AM 
+        		data.ValidTo = '' +validFromList[2] + validFromList[1] +validFromList[0];
+        	}
+        	System.debug('data.ValidFrom--->'+data.ValidFrom);
+        	System.debug('data.ValidTo--->'+data.ValidTo);
+
+        }
+        String rowDataStr1 = JSON.serialize(GeDataList);
+        System.debug('rowDataStr1--->'+rowDataStr1);
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBG204RestExecute.cls-meta.xml b/scr/classes/SBG204RestExecute.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG204RestExecute.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBG204RestTest.cls b/scr/classes/SBG204RestTest.cls
new file mode 100644
index 0000000..c71b0c4
--- /dev/null
+++ b/scr/classes/SBG204RestTest.cls
@@ -0,0 +1,92 @@
+@isTest
+private class SBG204RestTest {
+
+	@isTest
+	static void test_method_one() {
+
+		// product
+		Product2 prd1 = new Product2();
+		prd1.ProductCode            = 'Prd1';
+		prd1.Name                   = 'Prd1';
+
+		insert prd1;
+
+		// 浜у搧娉ㄥ唽璇�
+		Product_Register__c prc = new Product_Register__c();
+		prc.Name = 'SFDC娴嬭瘯鐢�2018001';
+		insert prc;
+
+		// 浜у搧-娉ㄥ唽璇佸叧绯�
+		Product_Register_Link__c prl = new Product_Register_Link__c();
+		prl.Product_Register__c = prc.id;
+		prl.Product2__c = prd1.id;
+		insert prl;
+
+		// IF杞�佽〃
+		BatchIF_Transfer__c trans1 = new BatchIF_Transfer__c();
+		trans1.Table__c = 'Product2';
+		trans1.Column__c = 'Product_Status__c';
+		trans1.External_Value__c = '20';
+		trans1.Internal_Value__c = '姝e父閿�鍞�';
+		insert trans1;
+
+		BatchIF_Transfer__c trans2 = new BatchIF_Transfer__c();
+		trans2.Table__c = 'Product_Register__c';
+		trans2.Column__c = 'RegisterNoStatus__c';
+		trans2.External_Value__c = '20';
+		trans2.Internal_Value__c = '鏈夋晥';
+		insert trans2;
+
+		SBG204Rest.GeDatas GeDatas = new SBG204Rest.GeDatas();
+		SBG204Rest.GeData GeData = new SBG204Rest.GeData();
+		GeDatas.GeData = new SBG204Rest.GeData[] {GeData};
+
+		Datetime nowDT = Datetime.now();
+		String nowStr = nowDT.format('yyyyMMddHHmm');
+		GeDatas.Monitoring = new NFMUtil.Monitoring();
+		GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+
+		// test1
+		GeData.MaterialNo = 'Prd1';
+		GeData.MaterialStatus = '20';
+		GeData.RegisterNo = 'SFDC娴嬭瘯鐢�2018001';
+		GeData.RegisterNoStatus = '20';
+		GeData.REG_Name = '鍖椾含甯� 浜┈妗�;鍖椾含甯� 閰掍粰妗�';
+		GeData.ValidFrom = '20180522';
+
+		NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+		BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBG204', GeDatas.GeData);
+		SBG204Rest.executefuture(rowData.Id);
+
+		// test2
+		GeData.MaterialNo = 'Prd1';
+		GeData.MaterialStatus = '20';
+		GeData.RegisterNo = 'SFDC娴嬭瘯鐢�2018001';
+		GeData.RegisterNoStatus = '30';
+		GeData.REG_Name = '鍖椾含甯� 浜┈妗�;鍖椾含甯� 閰掍粰妗�';
+		GeData.ValidFrom = '20180522';
+
+
+		rowData = NFMUtil.saveRowData(Monitoring, 'SBG204', GeDatas.GeData);
+		SBG204Rest.executefuture(rowData.Id);
+
+	}
+
+	@isTest static void test_method_two() {
+		Test.startTest();
+
+		RestRequest req = new RestRequest();
+		RestResponse res = new RestResponse();
+
+		String JsonMsg = '{"Monitoring":{"TransmissionDateTime":"201812201320","Text":"","Tag":"MSGH","Sender":"SFDC","Receiver":"SPO","NumberOfRecord":"1","MessageType":"NFM204","MessageGroupNumber":"20180001722190"},"GeData":[{"Z3PLAuthorizedNo":"","Z3PLAuthorized":"","YXQX":"1骞�","ValidTo":null,"ValidFrom":"20180522","Unit":null,"TransCondition":null,"StroageCondition":null,"RegisterNoStatus":"50","RegisterNoClass_Old":"","RegisterNoClass_New":"","RegisterNo":"FYL","ProductName":"SSC6024 : Sof-Curl 杈撳翱绠℃敮鏋剁 6Fr.X 24cm","PrdValidTo":null,"PrdValidFrom":null,"PrdCompanyLicense":"","PrdCompanyAddr":"","Other3":null,"Other2":null,"Other1":null,"Model":"SSC6024 ","MedPrdClass":"","MaterialStatusType":null,"MaterialStatus":"10","MaterialNo":"SSC6024","MaterialGroup":null,"BusinessScope":"","AuthorizedCompany_SH":"","AuthorizedCompany":"","ApprovedDate_SH":null,"ApprovedDate":null}]}';
+		req.requestURI = 'services/apexrest/SBG204Rest/execute';
+		req.httpMethod = 'POST';
+		req.requestBody = Blob.valueof(JsonMsg);
+		RestContext.request = req;
+		RestContext.response = res;
+
+		SBG204Rest.execute();
+
+		Test.stopTest();
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/SBG204RestTest.cls-meta.xml b/scr/classes/SBG204RestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBG204RestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGCallLogRest.cls b/scr/classes/SBGCallLogRest.cls
new file mode 100644
index 0000000..9914d59
--- /dev/null
+++ b/scr/classes/SBGCallLogRest.cls
@@ -0,0 +1,68 @@
+/**********************************************************************
+閫氳瘽璁板綍
+*************************************************************************/
+@RestResource(urlMapping='/SBGCallLog/*')
+global with sharing class SBGCallLogRest {
+    
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public GeData[] GeData;
+    }
+    /*
+    閫氳瘽璁板綍:  1 鍛煎彨鏍囪瘑锛坈allid锛� 2 鍛煎彨绫诲瀷锛坈allType  0鍛煎叆 1 鍛煎嚭锛�3 涓诲彨鍙风爜锛坈allerNo锛�  4  琚彨鍙风爜锛� calleeNo锛� 5 鍛煎彨鏃堕棿   6.鎺ュ惉鏃堕棿  7 鎸傛満鏃堕棿  8 褰曢煶鏂囦欢鍚嶅湴鍧�
+鏈帴鐢佃瘽:  1鍛煎彨鏍囪瘑锛坈allid锛� 2 鏉ョ數鍙风爜   3  鏉ョ數鏃堕棿
+    */
+    global class GeData {
+
+        public String callid; //鍛煎彨鏍囪瘑
+        public String callType; //鍛煎彨绫诲瀷
+        public String callerNo; //涓诲彨鍙风爜
+        public String calleeNo; //琚彨鍙风爜
+        public String callTime; //鍛煎彨鏃堕棿
+        public String answerTime; //鎺ュ惉鏃堕棿
+        public String hangUpTime; //鎸傛満鏃堕棿
+        public String recordingAddress; //褰曢煶鏂囦欢鍚嶅湴鍧�
+        public String callLogType;//閫氳瘽鐘舵��
+        
+    }
+
+    @HttpPost
+    global static void execute() {
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBGCallLog', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBGCallLogRest.cls-meta.xml b/scr/classes/SBGCallLogRest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBGCallLogRest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGITMRest.cls b/scr/classes/SBGITMRest.cls
new file mode 100644
index 0000000..0290b39
--- /dev/null
+++ b/scr/classes/SBGITMRest.cls
@@ -0,0 +1,365 @@
+@RestResource(urlMapping = '/SBGITM/*')
+global with sharing class SBGITMRest  {
+
+    //
+    //璇ユ帴鍙�20200320涓嬬彮涔嬪悗姝e紡搴熷純锛岀壒姝ゆ爣娉紝鏀圭敤鏂版帴鍙�-SBGITMRestNew
+    //
+    //
+    
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public SBGITMRest.GeData[] GeData;
+    }
+    global class GeData {
+        public String  ProductCode;
+        public String  ProductDescription;
+        public String  ProductStatus;
+        public String  EffectiveDateTo;
+        public String  Other1;
+        public String  Other2;
+        public String  Other3;
+
+        //20190717 SSBG_CBPR
+        public String Exemption;//璞佸厤鏍囪瘑
+        public String IsRadiant;//杈愬皠鏍囪瘑
+        public String NMPAStatus;//棣栬惀鐗╂枡鐘舵��
+        public String StatusEffectiveDateFrom;//鏈夋晥鏈熷紑濮嬫棩
+        //20190717 SSBG_CBPR
+        public String ZCHG_STATUS;
+    }
+
+    @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBGITM', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+
+        //Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        //BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        //String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        //BatchIF_Log__c iflog = new BatchIF_Log__c();
+        //iflog.Type__c = 'SBGITM';
+        //iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        //iflog.Log__c = logstr;
+        //iflog.ErrorLog__c = '';
+        //insert iflog;
+        //String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        //List<GeData> itemMasterList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        //if (itemMasterList == null || itemMasterList.size() == 0) {
+        //    return;
+        //}
+
+        //Savepoint sp = Database.setSavepoint();
+        //try {
+        //    // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+        //    List<String> productCodeList = new List<String>();
+        //    for (GeData GeData : itemMasterList) {
+        //        if (GeData.ProductCode == null || GeData.ProductCode == '') {
+        //            // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+        //            continue;
+        //        }
+        //        productCodeList.add(GeData.ProductCode);
+        //    }
+        //    List<Product2> prdList = [select Id,
+        //                              ProductCode,
+        //                              Description,
+        //                              ProductStatus__c,
+        //                              EffectiveDateTo__c,
+        //                              NMPAStatus_one__c, MaterialStatus_one_Start__c, MaterialStatus_one_End__c,
+        //                              NMPAStatus_two__c, MaterialStatus_two_Start__c, MaterialStatus_two_End__c
+        //                              from Product2
+        //                              where ProductModels__c = false and ProductCode in :productCodeList];
+        //    Map<String, Product2> prdsMap = new Map<String, Product2>();
+        //    for (Product2 prd : prdList) {
+        //        prdsMap.put(prd.ProductCode, prd);
+        //    }
+
+        //    // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+        //    prdList = new List<Product2>();
+        //    Map<String, Product2> prdUpdateMap = new Map<String, Product2>();
+        //    for (GeData GeData : itemMasterList) {
+        //        if (GeData.ProductCode == null || GeData.ProductCode == '') {
+        //            // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+        //            iflog.ErrorLog__c += 'MaterialNumber is required\n';
+        //            continue;
+        //        }
+
+        //        if (String.isBlank(GeData.ProductDescription)) {
+        //            iflog.ErrorLog__c += 'Description is required:' + GeData.ProductCode  + ' \n';
+        //            continue;
+        //        }
+
+        //        Product2 prd = prdsMap.get(GeData.ProductCode);
+        //        String prdName = null;
+
+        //        if (prd == null) {
+        //            prd = new Product2();
+        //        }
+
+        //        // 闋呯洰杌㈤�併伄銈汇儍銉�
+        //        prd.ProductCode        = GeData.ProductCode;
+        //        prd.IsActive = true;
+        //        if (prdUpdateMap.get(prd.ProductCode) == null) {
+        //            prdList.add(prd);
+        //            prdUpdateMap.put(prd.ProductCode, prd);
+        //            //logstr += GeData.MaterialNumber + ' ';               // 渚℃牸琛ㄣ伄銇ㄣ亾銈嶃伨銇ㄣ倎銇og銈掑嚭銇�
+        //        } else {
+        //            prd = prdUpdateMap.get(prd.ProductCode);
+        //        }
+
+
+        //        //SSBG-CBPR
+        //        // 涓枃鍚嶇О銇岃虎閫併仐銇︺亶銇熷牬鍚�
+        //        prdName = GeData.ProductDescription;
+        //        if (prdName != null) {
+
+        //            //SSBG-CBPR
+        //            Date dateFrom = '00000000'.equals(GeData.StatusEffectiveDateFrom) ? Date.today() : NFMUtil.parseStr2Date(GeData.StatusEffectiveDateFrom, false);
+        //            Date oneStart = prd.MaterialStatus_one_Start__c;
+        //            Date oneEnd = prd.MaterialStatus_one_End__c;
+        //            Date twoStart = prd.MaterialStatus_two_Start__c;
+        //            Date twoEnd = prd.MaterialStatus_two_End__c ;
+
+        //            String campState = String.isBlank( GeData.NMPAStatus) ? 'Z1' : GeData.NMPAStatus;
+        //            if (prd == null) {
+
+        //                prd.NMPAStatus_one__c = campState;
+        //                prd.MaterialStatus_one_Start__c = dateFrom;
+        //                prd.MaterialStatus_one_End__c = NFMUtil.parseStr2Date('40001231', true);
+        //            } else if ( oneStart == null || oneEnd < Date.today() || oneStart == dateFrom) {
+
+        //                if (twoEnd != null) {
+        //                    prd.MaterialStatus_two_End__c = dateFrom.addDays(-1);
+        //                }
+        //                prd.NMPAStatus_one__c = campState;
+        //                prd.MaterialStatus_one_Start__c = dateFrom;
+        //                prd.MaterialStatus_one_End__c = NFMUtil.parseStr2Date('40001231', true);
+        //            } else if (twoStart == null || twoEnd < Date.today() || twoStart == dateFrom) {
+
+        //                prd.NMPAStatus_two__c = campState;
+        //                prd.MaterialStatus_one_End__c = dateFrom.addDays(-1);
+        //                prd.MaterialStatus_two_Start__c = dateFrom;
+        //                prd.MaterialStatus_two_End__c = NFMUtil.parseStr2Date('40001231', true);
+        //            } else {
+
+        //                if ( (oneStart <= Date.today()) && (Date.today() <= oneEnd)) {
+        //                    prd.MaterialStatus_one_End__c = dateFrom.addDays(-1);
+        //                    prd.NMPAStatus_two__c = campState;
+        //                    prd.MaterialStatus_two_Start__c = dateFrom;
+        //                    prd.MaterialStatus_two_End__c = NFMUtil.parseStr2Date('40001231', true);
+        //                } else if ( (twoStart <= Date.today()) && (Date.today() <= twoEnd)) {
+        //                    prd.MaterialStatus_two_End__c = dateFrom.addDays(-1);
+        //                    prd.NMPAStatus_one__c = campState;
+        //                    prd.MaterialStatus_one_Start__c = dateFrom;
+        //                    prd.MaterialStatus_one_End__c = NFMUtil.parseStr2Date('40001231', true);
+        //                }
+        //            }
+
+
+        //            prd.If_Exempt_Product__c = GeData.Exemption == '1' ? true : false;
+        //            prd.If_Radiation_Product__c = GeData.IsRadiant == '1' ? true : false;
+
+        //            //SSBG-CBPR
+
+
+        //            // 銉囥儠銈┿儷銉堝��
+        //            prd.Name = prdName;
+        //            String alternative_Products = null;
+        //            String nDM_Model_No = null;
+        //            prd.Name = prdName.trim();
+
+        //            // 鍨嬬暘:浠f浛鍝�::涓枃鍚嶇О 銇儜銈裤兗銉�
+        //            //Pattern pt = Pattern.compile('(.*):(.*)::(.*)');
+        //            //Matcher mc = pt.matcher(prdName);
+        //            //if (mc.matches() == false
+        //            //        && ((prd.Name.indexOf(':') >= 0 && prd.Name.indexOf(':') != prd.Name.indexOf('::'))
+        //            //                || (prd.Name.indexOf('锛�') >= 0 && prd.Name.indexOf('锛�') != prd.Name.indexOf('锛氾細'))
+        //            //           )
+        //            //) {
+        //            //    // 鍨嬬暘::涓枃鍚嶇О 銇儜銈裤兗銉�
+        //            //    pt = Pattern.compile('(.*):(.*)');
+        //            //    mc = pt.matcher(prdName);
+        //            //    if (mc.matches()) {
+        //            //        nDM_Model_No = mc.group(1).trim();
+        //            //        prd.Name = mc.group(2).trim();
+        //            //        prd.Product_ECCode__c = nDM_Model_No;
+        //            //        System.debug('mc is1' + mc);
+        //            //        System.debug('prdName is1' + prdName);
+        //            //        System.debug('nDM_Model_No is1' + nDM_Model_No);
+        //            //    } else {
+        //            //        pt = Pattern.compile('(.*)锛�(.*)');
+        //            //        mc = pt.matcher(prdName);
+        //            //        if (mc.matches()) {
+        //            //            nDM_Model_No = mc.group(1).trim();
+        //            //            prd.Name =  mc.group(2).trim();
+        //            //            prd.Product_ECCode__c = nDM_Model_No;
+        //            //            System.debug('mc is2' + mc);
+        //            //            System.debug('prdName is2' + prdName);
+        //            //            System.debug('nDM_Model_No is2' + nDM_Model_No);
+        //            //        }
+        //            //    }
+        //            //}
+
+        //            if (prdName.indexOf(':') < 0 && prdName.indexOf('锛�') < 0) {
+        //                prd.Product_ECCode__c = GeData.ProductCode;
+        //            } else {
+        //                Integer max = -1;
+        //                Integer min = 100000;
+        //                Integer starh = prdName.indexOf(':');
+        //                if (starh >= 0) {
+        //                    if (min > starh) {
+        //                        min = starh;
+        //                    }
+        //                }
+        //                Integer stara = prdName.indexOf('锛�');
+        //                if (stara >= 0) {
+        //                    if (min > stara) {
+        //                        min = stara;
+        //                    }
+        //                }
+        //                Integer endh = prdName.lastIndexOf(':');
+        //                if (endh >= 0) {
+        //                    if (max < endh) {
+        //                        max = endh;
+        //                    }
+        //                }
+        //                Integer enda = prdName.lastIndexOf('锛�');
+        //                if (enda >= 0) {
+        //                    if (max < enda) {
+        //                        max = enda;
+        //                    }
+        //                }
+        //                prd.Product_ECCode__c = prdName.substring(0, min);
+        //                prd.Name =  prdName.substring(max + 1, prdName.length());
+        //            }
+        //            if (GeData.ProductCode != null) {
+        //                prd.ProductCode = GeData.ProductCode;
+        //            }
+        //            if (GeData.ProductDescription != null) {
+        //                prd.Description = GeData.ProductDescription;
+        //            }
+        //            if (GeData.ProductStatus != null) {
+        //                prd.ProductStatus__c = GeData.ProductStatus;
+        //            }
+        //            if (GeData.EffectiveDateTo != null) {
+        //                prd.EffectiveDateTo__c = NFMUtil.parseStr2Date(GeData.EffectiveDateTo, true);
+        //            }
+
+
+        //            //SSBG-CBPR
+        //        }
+        //    }
+        //    if (prdList.size() > 0) {
+        //        logstr += 'Execute Record:' + prdList.size() + '\n';
+        //        upsert prdList;
+        //        // PricebookEntry銇儑銉笺偪銇屻仾銇勫牬鍚坕nsert銇欍倠銆丆NY銇║SD銇伩
+        //        Pricebook2 pricebook = ControllerUtil.getStandardPricebook();
+
+        //        String pricebookId = pricebook.Id;
+        //        List<PricebookEntry> pbeList = [Select Product2Id, CurrencyIsoCode, UnitPrice, Pricebook2Id From PricebookEntry where Product2Id in: prdList and Pricebook2Id = :pricebookId order by Product2Id, CurrencyIsoCode];
+        //        List<PricebookEntry> pbeInsertList = new List<PricebookEntry>();
+        //        Map<String, PricebookEntry> rmbMap = new Map<String, PricebookEntry>();
+        //        Map<String, PricebookEntry> usdMap = new Map<String, PricebookEntry>();
+        //        for (PricebookEntry pbe : pbeList) {
+        //            if (pbe.CurrencyIsoCode == 'CNY') {
+        //                rmbMap.put(pbe.Product2Id, pbe);
+        //            } else if (pbe.CurrencyIsoCode == 'USD') {
+        //                usdMap.put(pbe.Product2Id, pbe);
+        //            }
+        //        }
+        //        for (Product2 prd : prdList) {
+        //            logstr += prd.ProductCode;
+        //            if (rmbMap.get(prd.Id) == null) {
+        //                PricebookEntry pbe = new PricebookEntry();
+        //                pbe.Pricebook2Id    = pricebookId;
+        //                pbe.Product2Id      = prd.Id;
+        //                pbe.CurrencyIsoCode = 'CNY';
+        //                pbe.UnitPrice       = 0;
+        //                pbe.IsActive        = prd.IsActive;
+        //                pbeInsertList.add(pbe);
+        //                logstr += ' add(CNY_0)';
+        //            }
+        //            if (usdMap.get(prd.Id) == null) {
+        //                PricebookEntry pbe = new PricebookEntry();
+        //                pbe.Pricebook2Id    = pricebookId;
+        //                pbe.Product2Id      = prd.Id;
+        //                pbe.CurrencyIsoCode = 'USD';
+        //                pbe.UnitPrice       = 0;
+        //                pbe.IsActive        = prd.IsActive;
+        //                pbeInsertList.add(pbe);
+        //                logstr += ' add(USD_0)';
+        //            }
+        //            logstr += ' ';
+        //        }
+        //        if (pbeInsertList.size() > 0) {
+        //            logstr += 'Execute Record2:' + pbeInsertList.size() + '\n';
+        //            insert pbeInsertList;
+        //        }
+        //    }
+        //    logstr += '\nend';
+        //    rowData.retry_cnt__c = 0;
+        //} catch (Exception ex) {
+        //    // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+        //    Database.rollback(sp);
+        //    System.debug(Logginglevel.ERROR, 'SBGITM_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+        //    System.debug(Logginglevel.ERROR, 'SBGITM_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+        //    logstr += '\n' + ex.getMessage();
+        //    iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+        //    if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+        //    if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+        //        rowData.retry_cnt__c++;
+        //        LogAutoSendSchedule.assignOneMinute();
+        //    }
+        //    if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+        //        rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+        //    }
+        //}
+        //update rowData;
+        //iflog.Log__c = logstr;
+        //if (iflog.Log__c.length() > 131072) {
+        //    iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        //}
+        //if (iflog.ErrorLog__c.length() > 32768) {
+        //    iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        //}
+        //update iflog;
+
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SBGITMRest.cls-meta.xml b/scr/classes/SBGITMRest.cls-meta.xml
new file mode 100644
index 0000000..91b23b8
--- /dev/null
+++ b/scr/classes/SBGITMRest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>46.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGITMRestNew.cls b/scr/classes/SBGITMRestNew.cls
new file mode 100644
index 0000000..65b75b6
--- /dev/null
+++ b/scr/classes/SBGITMRestNew.cls
@@ -0,0 +1,358 @@
+@RestResource(urlMapping = '/SBGITMRestNew/*')
+global with sharing class SBGITMRestNew {
+    global class GeDatasRest {
+        public GeDatas GeDatas;
+    }
+
+    global class GeDatas {
+        public NFMUtil.Monitoring Monitoring;
+        public SBGITMRestNew.GeData[] GeData;
+    }
+    global class GeData {
+        public String  ProductCode;
+        public String  ProductDescription;
+        public String  ProductStatus;
+        public String  EffectiveDateTo;
+        public String  Other1;
+        public String  Other2;
+        public String  Other3;
+
+        //20190717 SSBG_CBPR
+        public String Exemption;//璞佸厤鏍囪瘑
+        public String IsRadiant;//杈愬皠鏍囪瘑
+        public String NMPAStatus;//棣栬惀鐗╂枡鐘舵��
+        public String StatusEffectiveDateFrom;//鏈夋晥鏈熷紑濮嬫棩
+        //20190717 SSBG_CBPR
+
+        public String ZCHG_STATUS;//鍙樻洿鏂瑰紡--1.鏂板;2.鍙樻洿(涓嶅彉鏇碞MPAStatus涓嶴tatusEffectiveDateFrom)
+        //3.棣栬惀鐗╂枡鐘舵�佸彉鏇�(鍙洿NMPAStatus涓嶴tatusEffectiveDateFrom);9.鍙樻洿(ProductStatus__c)
+        public String ECCODE;
+
+        public String ProSerial; //杈愬皠浜у搧绯诲垪
+    }
+
+    @HttpPost
+    global static void execute() {
+
+        // 鍙栧緱鎺ュ彛浼犺緭鍐呭
+        String strData = RestContext.request.requestBody.toString();
+        GeDatasRest ges = (GeDatasRest) JSON.deserializeStrict(strData, GeDatasRest.class);
+
+        if (ges == null ) {
+            return;
+        }
+
+        NFMUtil.Monitoring Monitoring = ges.GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBGITMRestNew', ges.GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) {
+            executefuture(rowData.Id);
+        }
+
+        // JSON銈掓埢銇�
+        RestResponse res = RestContext.response;
+        res.addHeader('Content-Type', 'application/json');
+        res.statusCode = 200;
+        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
+        String jsonResponse = '{"status": "Success", "Message":""}';
+        res.responseBody = blob.valueOf(jsonResponse);
+        return;
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        main(rowData_Id);
+    }
+
+    global static void main(String rowData_Id) {
+
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBGITMRestNew';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> itemMasterList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (itemMasterList == null || itemMasterList.size() == 0) {
+            return;
+        }
+
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+            List<String> productCodeList = new List<String>();
+            for (GeData GeData : itemMasterList) {
+                if (GeData.ProductCode == null || GeData.ProductCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    continue;
+                }
+                Pattern pattern = Pattern.compile('^[0-9]*$');  
+                Matcher isNum = pattern.matcher(GeData.ProductCode); 
+                if (isNum.matches()) {
+                    GeData.ProductCode = GeData.ProductCode.leftPad(18, '0');
+                }
+                
+                productCodeList.add(GeData.ProductCode);
+            }
+            List<Product2> prdList = [select Id,
+                                      ProductCode,
+                                      Description,
+                                      ProductStatus__c,
+                                      EffectiveDateTo__c,
+                                      NMPAStatus_one__c, MaterialStatus_one_Start__c, MaterialStatus_one_End__c,
+                                      NMPAStatus_two__c, MaterialStatus_two_Start__c, MaterialStatus_two_End__c
+                                      from Product2
+                                      where ProductModels__c = false and ProductCode in :productCodeList];
+            Map<String, Product2> prdsMap = new Map<String, Product2>();
+            for (Product2 prd : prdList) {
+                prdsMap.put(prd.ProductCode, prd);
+            }
+
+            // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+            prdList = new List<Product2>();
+            Map<String, Product2> prdUpdateMap = new Map<String, Product2>();
+            for (GeData GeData : itemMasterList) {
+                if (GeData.ProductCode == null || GeData.ProductCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'MaterialNumber is required\n';
+                    continue;
+                }
+
+                if (String.isBlank(GeData.ProductDescription) && GeData.ZCHG_STATUS != '9') {
+                    iflog.ErrorLog__c += 'Description is required:' + GeData.ProductCode  + ' \n';
+                    continue;
+                }
+
+                Product2 prd = prdsMap.get(GeData.ProductCode);
+                String prdName = null;
+
+                if (prd == null && GeData.ZCHG_STATUS == '1' ) {
+                    prd = new Product2();
+                } else if (prd == null && GeData.ZCHG_STATUS != '1') {
+                    iflog.ErrorLog__c += 'Product[' + GeData.ProductCode + ']NotExist\n';
+                    continue;
+                }
+
+                // 闋呯洰杌㈤�併伄銈汇儍銉�
+                prd.ProductCode        = GeData.ProductCode;
+                prd.IsActive = true;
+                if (prdUpdateMap.get(prd.ProductCode) == null) {
+                    prdList.add(prd);
+                    prdUpdateMap.put(prd.ProductCode, prd);
+                    //logstr += GeData.MaterialNumber + ' ';               // 渚℃牸琛ㄣ伄銇ㄣ亾銈嶃伨銇ㄣ倎銇og銈掑嚭銇�
+                } else {
+                    prd = prdUpdateMap.get(prd.ProductCode);
+                }
+
+                if (GeData.ZCHG_STATUS == '9') {
+                    if (GeData.ProductStatus != null) {
+                        logstr += 'From SAP 鈫� '+GeData.ProductCode+'鈫� 浜у搧鐘舵�佸彉鏇碶n';
+                        prd.ProductStatus__c = GeData.ProductStatus;
+                    }
+                    continue;
+                }
+                // 涓枃鍚嶇О銇岃虎閫併仐銇︺亶銇熷牬鍚�
+                prdName = GeData.ProductDescription;
+                if (prdName != null) {
+
+                    if (GeData.ZCHG_STATUS == '1') {
+                        logstr += 'From SPO 鈫� '+GeData.ProductCode+'鈫� 浜у搧鏂板\n';
+                        prd = product2NMPAStatus(prd, GeData);
+                    } else if (GeData.ZCHG_STATUS == '2') {
+                        logstr += 'From SPO 鈫� '+GeData.ProductCode+'鈫� 浜у搧鍙樻洿 闈為钀ョ墿鏂欑姸鎬佸彉鏇碶n';
+                        //prd = product2NMPAStatus(prd,GeData);
+                    } else if (GeData.ZCHG_STATUS == '3') {
+                        logstr += 'From SPO 鈫� '+GeData.ProductCode+'鈫� 浜у搧鍙樻洿 鍙钀ョ墿鏂欑姸鎬佸彉鏇碶n';
+                        prd = product2NMPAStatus(prd, GeData);
+                        continue;
+                    }
+
+                    prd.If_Exempt_Product__c = GeData.Exemption == '1' ? true : false;
+                    if (GeData.IsRadiant == '1') {
+                        prd.If_Radiation_Product__c = true;
+                    } else {
+                        prd.If_Radiation_Product__c = false;
+                    }
+                    prd.RadiationType__c = GeData.ProSerial;
+
+                    // 銉囥儠銈┿儷銉堝��
+                    prd.Name = prdName;
+                    String alternative_Products = null;
+                    String nDM_Model_No = null;
+                    prd.Name = prdName.trim();
+
+                    if (String.isBlank(GeData.ECCODE)) {
+                        prd.Product_ECCode__c = GeData.ProductCode;
+                        prd.Description =  GeData.ProductDescription ;
+                    } else {
+                        prd.Product_ECCode__c = GeData.ECCODE;
+                        prd.Description = GeData.ECCODE + ':' + GeData.ProductDescription ;
+                    }
+
+                    if (GeData.ProductCode != null) {
+                        prd.ProductCode = GeData.ProductCode;
+                    }
+
+                    if (GeData.ProductStatus != null) {
+                        prd.ProductStatus__c = GeData.ProductStatus;
+                    }
+                    prd.EffectiveDateTo__c = NFMUtil.parseStr2Date('40001231', true);
+                }
+            }
+            if (prdList.size() > 0) {
+                logstr += 'Execute Record:' + prdList.size() + '\n';
+                upsert prdList;
+                // PricebookEntry銇儑銉笺偪銇屻仾銇勫牬鍚坕nsert銇欍倠銆丆NY銇║SD銇伩
+                Pricebook2 pricebook = ControllerUtil.getStandardPricebook();
+
+                String pricebookId = pricebook.Id;
+                List<PricebookEntry> pbeList = [Select Product2Id, CurrencyIsoCode, UnitPrice, Pricebook2Id From PricebookEntry where Product2Id in: prdList and Pricebook2Id = :pricebookId order by Product2Id, CurrencyIsoCode];
+                List<PricebookEntry> pbeInsertList = new List<PricebookEntry>();
+                Map<String, PricebookEntry> rmbMap = new Map<String, PricebookEntry>();
+                Map<String, PricebookEntry> usdMap = new Map<String, PricebookEntry>();
+                for (PricebookEntry pbe : pbeList) {
+                    if (pbe.CurrencyIsoCode == 'CNY') {
+                        rmbMap.put(pbe.Product2Id, pbe);
+                    } else if (pbe.CurrencyIsoCode == 'USD') {
+                        usdMap.put(pbe.Product2Id, pbe);
+                    }
+                }
+                for (Product2 prd : prdList) {
+                    logstr += prd.ProductCode;
+                    if (rmbMap.get(prd.Id) == null) {
+                        PricebookEntry pbe = new PricebookEntry();
+                        pbe.Pricebook2Id    = pricebookId;
+                        pbe.Product2Id      = prd.Id;
+                        pbe.CurrencyIsoCode = 'CNY';
+                        pbe.UnitPrice       = 0;
+                        pbe.IsActive        = prd.IsActive;
+                        pbeInsertList.add(pbe);
+                        logstr += ' add(CNY_0)';
+                    }
+                    if (usdMap.get(prd.Id) == null) {
+                        PricebookEntry pbe = new PricebookEntry();
+                        pbe.Pricebook2Id    = pricebookId;
+                        pbe.Product2Id      = prd.Id;
+                        pbe.CurrencyIsoCode = 'USD';
+                        pbe.UnitPrice       = 0;
+                        pbe.IsActive        = prd.IsActive;
+                        pbeInsertList.add(pbe);
+                        logstr += ' add(USD_0)';
+                    }
+                    logstr += ' ';
+                }
+                if (pbeInsertList.size() > 0) {
+                    logstr += 'Execute Record2:' + pbeInsertList.size() + '\n';
+                    insert pbeInsertList;
+                }
+            }
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+        } catch (Exception ex) {
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBGITM_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBGITM_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+
+    }
+    /**
+     * 涓轰骇鍝侀钀ョ姸鎬佽祴鍊�
+     * @param [prd] [浜у搧]
+     * @param [geData] [鎺ュ彛鏁版嵁]
+     * @return [浜у搧]
+     */
+    public static Product2 product2NMPAStatus(Product2 prd, GeData geData) {
+
+        //SSBG-CBPR
+        Date dateFrom = '00000000'.equals(geData.StatusEffectiveDateFrom) ? Date.today() : NFMUtil.parseStr2Date(geData.StatusEffectiveDateFrom, false);
+        Date oneStart = prd.MaterialStatus_one_Start__c;
+        Date oneEnd = prd.MaterialStatus_one_End__c;
+        Date twoStart = prd.MaterialStatus_two_Start__c;
+        Date twoEnd = prd.MaterialStatus_two_End__c ;
+
+        String campState = String.isBlank( geData.NMPAStatus) ? 'Z1' : geData.NMPAStatus;
+        if (prd == null) {
+
+            prd.NMPAStatus_one__c = campState;
+            prd.MaterialStatus_one_Start__c = dateFrom;
+            prd.MaterialStatus_one_End__c = NFMUtil.parseStr2Date('40001231', true);
+        } else if ( oneStart == null || oneEnd < Date.today() || oneStart == dateFrom) {
+
+            //if (twoEnd != null) {
+            //    prd.MaterialStatus_two_End__c = dateFrom.addDays(-1);
+            //}
+            if (twoEnd != null && twoStart != dateFrom) {
+                prd.MaterialStatus_two_End__c = dateFrom.addDays(-1);
+            } else if (twoEnd != null && twoStart == dateFrom) {
+                prd.MaterialStatus_two_Start__c = dateFrom.addDays(-1);
+                prd.MaterialStatus_two_End__c = dateFrom.addDays(-1);
+
+            }
+            prd.NMPAStatus_one__c = campState;
+            prd.MaterialStatus_one_Start__c = dateFrom;
+            prd.MaterialStatus_one_End__c = NFMUtil.parseStr2Date('40001231', true);
+        } else if (twoStart == null || twoEnd < Date.today() || twoStart == dateFrom) {
+
+            prd.NMPAStatus_two__c = campState;
+            prd.MaterialStatus_one_End__c = dateFrom.addDays(-1);
+            prd.MaterialStatus_two_Start__c = dateFrom;
+            prd.MaterialStatus_two_End__c = NFMUtil.parseStr2Date('40001231', true);
+        } else {
+
+            if ( (oneStart <= Date.today()) && (Date.today() <= oneEnd)) {
+                prd.MaterialStatus_one_End__c = dateFrom.addDays(-1);
+                prd.NMPAStatus_two__c = campState;
+                prd.MaterialStatus_two_Start__c = dateFrom;
+                prd.MaterialStatus_two_End__c = NFMUtil.parseStr2Date('40001231', true);
+            } else if ( (twoStart <= Date.today()) && (Date.today() <= twoEnd)) {
+                prd.MaterialStatus_two_End__c = dateFrom.addDays(-1);
+                prd.NMPAStatus_one__c = campState;
+                prd.MaterialStatus_one_Start__c = dateFrom;
+                prd.MaterialStatus_one_End__c = NFMUtil.parseStr2Date('40001231', true);
+            }
+        }
+        return prd;
+
+    }
+
+    public static String FieldTransformation(String bpCode, Map<String, String> transformation, String api, String toConvertStr, BatchIF_Log__c iflog, String receivesField ) {
+        String afterTransformation = NFMUtil.getMapValue(transformation, api, toConvertStr, iflog);
+
+        if (String.isNotBlank(afterTransformation) && !afterTransformation.equals(toConvertStr)) {
+
+            return afterTransformation;
+        } else {
+
+            iflog.ErrorLog__c += 'BPCode[ ' + bpCode + ' ] of ' + receivesField + ' [ ' + toConvertStr + ' ]' + ' is  Invalid,This data is skipped.\n';
+            return 'Invalid';
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBGITMRestNew.cls-meta.xml b/scr/classes/SBGITMRestNew.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBGITMRestNew.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGITMRestNewTest.cls b/scr/classes/SBGITMRestNewTest.cls
new file mode 100644
index 0000000..27622f3
--- /dev/null
+++ b/scr/classes/SBGITMRestNewTest.cls
@@ -0,0 +1,348 @@
+@isTest
+private class SBGITMRestNewTest {
+    public static Product2 prd1;
+    public static Product2 prd2;
+    public static Product2 prd3;
+    public static Product2 prd4;
+    public static Product2 prd5;
+
+    static void inittransfersData() { 
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'SBGITMTst1';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+        prd1.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd1.MaterialStatus_one_End__c = Date.today().addDays(-1);
+        prd1.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd1.MaterialStatus_two_End__c = Date.today().addDays(-1);
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'SBGITMTst2';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        prd2.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd2.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd2.MaterialStatus_two_End__c = Date.today().addDays(-1);
+
+        prd3 = new Product2();
+        prd3.Product_ECCode__c      = 'testSBG002';
+        prd3.ProductCode            = 'SBGITMTst22';
+        prd3.Name                   = 'testSBG002';
+        prd3.IsActive               = true;
+        prd3.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd3.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd3.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd3.MaterialStatus_two_End__c = Date.today().addDays(122);
+
+        prd4 = new Product2();
+        prd4.Product_ECCode__c      = 'testSBG002';
+        prd4.ProductCode            = 'SBGITMTst222';
+        prd4.Name                   = 'testSBG002';
+        prd4.IsActive               = true;
+        prd4.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd4.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd4.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd4.MaterialStatus_two_End__c = Date.today().addDays(21);
+
+        prd5 = new Product2();
+        prd5.Product_ECCode__c      = 'testSBG002';
+        prd5.ProductCode            = 'SBGITMTst222';
+        prd5.Name                   = 'testSBG002';
+        prd5.IsActive               = true;
+        prd5.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd5.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd5.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd5.MaterialStatus_two_End__c = Date.today().addDays(21);
+        insert new Product2[] {prd1, prd2,prd3,prd4};
+
+        List<BatchIF_Transfer__c> transfers = new List<BatchIF_Transfer__c>();
+        BatchIF_Transfer__c transfer = new BatchIF_Transfer__c();
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Product2';
+        transfer.Column__c         = 'RadiationType__c';
+        transfer.External_Value__c = 'D';
+        transfer.Internal_Value__c = 'Delta';
+        transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Product2';
+        transfer.Column__c         = 'RadiationType__c';
+        transfer.External_Value__c = 'V';
+        transfer.Internal_Value__c = 'Venta';
+        transfers.add(transfer);
+
+        //transfer = new BatchIF_Transfer__c();
+        //transfer.Table__c          = 'Product2';
+        //transfer.Column__c         = 'RadiationType__c';
+        //transfer.External_Value__c = 'DV';
+        //transfer.Internal_Value__c = 'Delta+Venta';
+        //transfers.add(transfer);
+
+        transfer = new BatchIF_Transfer__c();
+        transfer.Table__c          = 'Product2';
+        transfer.Column__c         = 'RadiationType__c';
+        transfer.External_Value__c = 'F';
+        transfer.Internal_Value__c = 'FOX-IQ';
+        transfers.add(transfer);
+
+        insert transfers;
+    }
+    @isTest
+    static void testSBGITM_insert() {
+        inittransfersData();
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRestNew.GeDatas GeDatas = new SBGITMRestNew.GeDatas();
+        SBGITMRestNew.GeData GeData = new SBGITMRestNew.GeData();
+        SBGITMRestNew.GeData GeData2 = new SBGITMRestNew.GeData();
+        SBGITMRestNew.GeData GeData3 = new SBGITMRestNew.GeData();
+        SBGITMRestNew.GeData GeData4 = new SBGITMRestNew.GeData();
+        SBGITMRestNew.GeData GeData5 = new SBGITMRestNew.GeData();
+        GeDatas.GeData = new SBGITMRestNew.GeData[] { GeData, GeData2,GeData3,GeData4,GeData5 };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst3';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        GeData.ZCHG_STATUS = '9';
+        GeData.ProSerial = 'D';
+
+
+        // insert2
+        GeData2.ProductCode                = 'SBGITMTst4';
+        GeData2.ProductDescription                 = 'ABCD12345:ABC';
+        GeData2.ProductStatus                    = '0';
+        GeData2.EffectiveDateTo                      = '20121101';
+        GeData2.Exemption = '1';
+        GeData2.IsRadiant = '1';
+        GeData2.ZCHG_STATUS = '1';
+        GeData2.ProSerial = 'D';
+        // insert3
+        GeData3.ProductCode                = 'SBGITMTst5';
+        GeData3.ProductDescription                 = 'ABCD123456:ABC';
+        GeData3.ProductStatus                    = '0';
+        GeData3.EffectiveDateTo                      = '20121101';
+        GeData3.Exemption = '1';
+        GeData3.IsRadiant = '1';
+        GeData3.ZCHG_STATUS = '2';
+        GeData3.ProSerial = 'D';
+
+        // insert4
+        GeData4.ProductCode                = 'SBGITMTst6';
+        GeData4.ProductDescription                 = 'ABCD1234567:ABC';
+        GeData4.ProductStatus                    = '0';
+        GeData4.EffectiveDateTo                      = '20121101';
+        GeData4.Exemption = '1';
+        GeData4.IsRadiant = '1';
+        GeData4.ZCHG_STATUS = '3';
+        GeData4.ProSerial = 'D';
+
+        // insert5
+        GeData5.ProductCode                = 'SBGITMTst7';
+        GeData5.ProductDescription                 = '';
+        GeData5.ProductStatus                    = '1';
+        GeData5.EffectiveDateTo                      = '20121101';
+        GeData5.Exemption = '1';
+        GeData5.IsRadiant = '1';
+        GeData5.StatusEffectiveDateFrom = '20200522';
+        GeData5.ZCHG_STATUS = '1';
+        GeData5.ProSerial = 'D';
+
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRestNew.executefuture(rowData.Id);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id, Name,
+                            ProductCode,
+                            Product_ECCode__c,
+                            EffectiveDateTo__c,
+                            ProductModels__c,
+                            ProductStatus__c
+                            from Product2
+                            where Product_ECCode__c = 'ABCD1234'];
+        //System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst3', rslts[0].ProductCode);
+        }
+        rslts = [select Id,
+                 ProductCode, Name,
+                 Product_ECCode__c,
+                 EffectiveDateTo__c,
+                 ProductModels__c,
+                 ProductStatus__c
+                 from Product2
+                 where Product_ECCode__c = 'ABCD12345'];
+        //System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst4', rslts[0].ProductCode);
+            System.assertEquals('ABC', rslts[0].Name);
+        }
+    }
+
+    @isTest
+    static void testSBGITM_update() {
+        inittransfersData();
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRestNew.GeDatas GeDatas = new SBGITMRestNew.GeDatas();
+        SBGITMRestNew.GeData GeData = new SBGITMRestNew.GeData();
+        GeDatas.GeData = new SBGITMRestNew.GeData[] { GeData };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        GeData.ZCHG_STATUS = '3';
+        GeData.ProSerial = 'D';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst2';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        GeData.ZCHG_STATUS = '3';
+        GeData.ProSerial = 'D';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst22';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        GeData.ZCHG_STATUS = '3';
+        GeData.ProSerial = 'D';
+
+        GeData.ProductCode                = 'SBGITMTst222';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        GeData.ZCHG_STATUS = '3';
+        GeData.ProSerial = 'D';
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRestNew.executefuture(rowData.Id);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id,
+                            ProductCode,
+                            Product_ECCode__c,
+                            EffectiveDateTo__c,
+                            ProductModels__c,
+                            ProductStatus__c
+                            from Product2
+                            where Product_ECCode__c = 'ABCD1234'];
+        //System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst222', rslts[0].ProductCode);
+        }
+    }
+
+    @isTest
+    static void testSBGITM_resend() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRestNew.GeDatas GeDatas = new SBGITMRestNew.GeDatas();
+        SBGITMRestNew.GeData GeData = new SBGITMRestNew.GeData();
+        GeDatas.GeData = new SBGITMRestNew.GeData[] { GeData };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+
+
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRestNew.executefuture(rowData.Id);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id,
+                            ProductCode,
+                            Product_ECCode__c,
+                            EffectiveDateTo__c,
+                            ProductModels__c,
+                            ProductStatus__c
+                            from Product2
+                            where Product_ECCode__c = 'ABCD1234'];
+        //System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst1', rslts[0].ProductCode);
+        }
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                      ErrorLog__c
+                                      from BatchIF_Log__c
+                                      where RowDataFlg__c = true
+                                              and Type__c = 'SBGITM'
+                                                      order by CreatedDate desc];
+        List<BatchIF_Log__c> rowbl1 = [Select Id, Log__c,
+                                       ErrorLog__c
+                                       from BatchIF_Log__c
+                                       where RowDataFlg__c = true
+                                               order by CreatedDate desc];
+        System.debug(rowbl1);
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        SBGITMRestNew.executefuture(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                                   Type__c, Log__c, ErrorLog__c, retry_cnt__c
+                                   from BatchIF_Log__c
+                                   where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        // System.assertEquals(1, bl[0].retry_cnt__c);
+    }
+
+
+
+    @isTest static void test_method_Seven() {
+
+        Test.startTest();
+
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+
+        String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBGITM","MessageGroupNumber": 331591,"NumberOfRecord": 1,"TransmissionDateTime": 201903251115},"GeData": [{"ProductStatus": "1","ProductDescription": "SP-KIT-WEDGE-MQIV1072:111 ","ProductCode":"U8831946","Other3": "","Other2": "","Other1": "","EffectiveDateTo": "99991231"}]}}';
+        req.requestURI = 'services/apexrest/SBGITM/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response = res;
+
+        SBGITMRestNew.execute();
+
+        Test.stopTest();
+
+        }
+}
\ No newline at end of file
diff --git a/scr/classes/SBGITMRestNewTest.cls-meta.xml b/scr/classes/SBGITMRestNewTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBGITMRestNewTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGITMRestTest.cls b/scr/classes/SBGITMRestTest.cls
new file mode 100644
index 0000000..73534ba
--- /dev/null
+++ b/scr/classes/SBGITMRestTest.cls
@@ -0,0 +1,262 @@
+@isTest
+private class SBGITMRestTest {
+    public static Product2 prd1;
+    public static Product2 prd2;
+    public static Product2 prd3;
+    public static Product2 prd4;
+
+    static void inittransfersData() { 
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'SBGITMTst1';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+        prd1.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd1.MaterialStatus_one_End__c = Date.today().addDays(-1);
+        prd1.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd1.MaterialStatus_two_End__c = Date.today().addDays(-1);
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'SBGITMTst2';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        prd2.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd2.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd2.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd2.MaterialStatus_two_End__c = Date.today().addDays(-1);
+
+        prd3 = new Product2();
+        prd3.Product_ECCode__c      = 'testSBG002';
+        prd3.ProductCode            = 'SBGITMTst22';
+        prd3.Name                   = 'testSBG002';
+        prd3.IsActive               = true;
+        prd3.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd3.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd3.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd3.MaterialStatus_two_End__c = Date.today().addDays(122);
+
+        prd4 = new Product2();
+        prd4.Product_ECCode__c      = 'testSBG002';
+        prd4.ProductCode            = 'SBGITMTst222';
+        prd4.Name                   = 'testSBG002';
+        prd4.IsActive               = true;
+        prd4.MaterialStatus_one_Start__c = Date.today().addDays(-2);
+        prd4.MaterialStatus_one_End__c = Date.today().addDays(22);
+        prd4.MaterialStatus_two_Start__c = Date.today().addDays(-3);
+        prd4.MaterialStatus_two_End__c = Date.today().addDays(21);
+        insert new Product2[] {prd1, prd2,prd3,prd4};
+    }
+    //@isTest
+    static void testSBGITM_insert() {
+        inittransfersData();
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        SBGITMRest.GeData GeData2 = new SBGITMRest.GeData();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData, GeData2 };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst3';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+
+
+        // insert2
+        GeData2.ProductCode                = 'SBGITMTst4';
+        GeData2.ProductDescription                 = 'ABCD12345:ABC';
+        GeData2.ProductStatus                    = '0';
+        GeData2.EffectiveDateTo                      = '20121101';
+
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRest.executefuture(rowData.Id);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id, Name,
+                            ProductCode,
+                            Product_ECCode__c,
+                            EffectiveDateTo__c,
+                            ProductModels__c,
+                            ProductStatus__c
+                            from Product2
+                            where Product_ECCode__c = 'ABCD1234'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst3', rslts[0].ProductCode);
+        }
+        rslts = [select Id,
+                 ProductCode, Name,
+                 Product_ECCode__c,
+                 EffectiveDateTo__c,
+                 ProductModels__c,
+                 ProductStatus__c
+                 from Product2
+                 where Product_ECCode__c = 'ABCD12345'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst4', rslts[0].ProductCode);
+            System.assertEquals('ABC', rslts[0].Name);
+        }
+    }
+
+    //@isTest
+    static void testSBGITM_update() {
+        inittransfersData();
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst2';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst22';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        
+        GeData.ProductCode                = 'SBGITMTst222';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+        GeData.Exemption = '1';
+        GeData.IsRadiant = '1';
+        GeData.StatusEffectiveDateFrom = '20200522';
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRest.executefuture(rowData.Id);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id,
+                            ProductCode,
+                            Product_ECCode__c,
+                            EffectiveDateTo__c,
+                            ProductModels__c,
+                            ProductStatus__c
+                            from Product2
+                            where Product_ECCode__c = 'ABCD1234'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst222', rslts[0].ProductCode);
+        }
+    }
+
+    //@isTest
+    static void testSBGITM_resend() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMRest.GeDatas GeDatas = new SBGITMRest.GeDatas();
+        SBGITMRest.GeData GeData = new SBGITMRest.GeData();
+        GeDatas.GeData = new SBGITMRest.GeData[] { GeData };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+
+
+        System.Test.startTest();
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(GeDatas.Monitoring, 'SBGITM', GeDatas.GeData);
+        SBGITMRest.executefuture(rowData.Id);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id,
+                            ProductCode,
+                            Product_ECCode__c,
+                            EffectiveDateTo__c,
+                            ProductModels__c,
+                            ProductStatus__c
+                            from Product2
+                            where Product_ECCode__c = 'ABCD1234'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst1', rslts[0].ProductCode);
+        }
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                      ErrorLog__c
+                                      from BatchIF_Log__c
+                                      where RowDataFlg__c = true
+                                              and Type__c = 'SBGITM'
+                                                      order by CreatedDate desc];
+        List<BatchIF_Log__c> rowbl1 = [Select Id, Log__c,
+                                       ErrorLog__c
+                                       from BatchIF_Log__c
+                                       where RowDataFlg__c = true
+                                               order by CreatedDate desc];
+        System.debug(rowbl1);
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        SBGITMRest.executefuture(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                                   Type__c, Log__c, ErrorLog__c, retry_cnt__c
+                                   from BatchIF_Log__c
+                                   where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        // System.assertEquals(1, bl[0].retry_cnt__c);
+    }
+
+
+
+    @isTest static void test_method_Seven() {
+
+        Test.startTest();
+
+        RestRequest req = new RestRequest();
+        RestResponse res = new RestResponse();
+
+        String JsonMsg = '{"GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBGITM","MessageGroupNumber": 331591,"NumberOfRecord": 1,"TransmissionDateTime": 201903251115},"GeData": [{"ProductStatus": "1","ProductDescription": "SP-KIT-WEDGE-MQIV1072:111 ","ProductCode":"U8831946","Other3": "","Other2": "","Other1": "","EffectiveDateTo": "99991231"}]}}';
+        req.requestURI = 'services/apexrest/SBGITM/execute';
+        req.httpMethod = 'POST';
+        req.requestBody = Blob.valueof(JsonMsg);
+        RestContext.request = req;
+        RestContext.response = res;
+
+        SBGITMRest.execute();
+
+        Test.stopTest();
+
+        // { "GeDatas": {"Monitoring": {"Tag": "MSGH","Sender": 1330,"Receiver": 1592,"MessageType": "SBG017", "MessageGroupNumber": 331591, "NumberOfRecord": 1, "TransmissionDateTime": 201903251115 },"GeData": [{ "StockAnswer": "OK111","SAPQuotationCode": "20022780  ", "Other3": "", "Other2": "", "Other1": "",  "OpportunityCode": "O-2018-067607"}]}}
+
+        //Test.setMock(HttpCalloutMock.class, new NFM205RestCalloutMock());
+        //NFM205Rest.execute1('{"Monitoring":{"TransmissionDateTime":"201812201320","Text":"","Tag":"MSGH","Sender":"SFDC","Receiver":"SPO","NumberOfRecord":"1","MessageType":"NFM205","MessageGroupNumber":"20180001722190"},"GeData":[{"Opportunity_Code":"HKBJ-GI-BJ0588881","Bidding_No":"as123121","Bidding_Content":"鎷涙爣鍐呭","Bid_Project_Name":"鎷涙爣椤圭洰鍚�","Bid_Date":"20181203","Authorized_Status":"1","Authorized_Finish_Sales":"30033","Authorized_DB_No":"MGZWESQHN201812001","Authorized_Date":"20190316","Autholization_Activated_Date":"20190415"}]}');
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBGITMRestTest.cls-meta.xml b/scr/classes/SBGITMRestTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SBGITMRestTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGITMWebService.cls b/scr/classes/SBGITMWebService.cls
new file mode 100644
index 0000000..6f292a4
--- /dev/null
+++ b/scr/classes/SBGITMWebService.cls
@@ -0,0 +1,266 @@
+global class SBGITMWebService {
+
+    global class GeDatas {
+        webservice NFMUtil.Monitoring Monitoring;
+        webservice SBGITMWebService.GeData[] GeData;
+    }
+    global class GeData {
+        webservice String  ProductCode;
+        webservice String  ProductDescription;
+        webservice String  ProductStatus;
+        webservice String  EffectiveDateTo;
+        webservice String  Other1;
+        webservice String  Other2;
+        webservice String  Other3;
+    }
+    webservice static void SBGITM(GeDatas geDatas) {
+        if (geDatas == null) {
+            return;
+        }
+        NFMUtil.Monitoring Monitoring = GeDatas.Monitoring;
+        if (Monitoring == null) {
+            return;
+        }
+        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'SBGITM', GeDatas.GeData);
+        if (String.isBlank(rowData.Log__c) == false) executefuture(rowData.Id);
+    }
+
+    @future
+    global static void executefuture(String rowData_Id) {
+        execute(rowData_Id);
+    }
+
+    global static void execute(String rowData_Id) {
+        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
+        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
+        String logstr = rowData.MessageGroupNumber__c + ' start\n';
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'SBGITM';
+        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
+        iflog.Log__c = logstr;
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        String rowDataStr = NFMUtil.getRowDataStr(rowData);
+        List<GeData> itemMasterList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
+        if (itemMasterList == null || itemMasterList.size() == 0) {
+            return;
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            // 鏇存柊瀵惧繙閰嶅垪銇∕ap銇仼銈掋偦銉冦儓
+            List<String> productCodeList = new List<String>();
+            for (SBGITMWebService.GeData GeData : itemMasterList) {
+                if (GeData.ProductCode == null || GeData.ProductCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    continue;
+                }
+                productCodeList.add(GeData.ProductCode);
+            }
+            List<Product2> prdList = [select Id,
+                                            ProductCode,
+                                            Description,
+                                            ProductStatus__c,
+                                            EffectiveDateTo__c
+                                        from Product2
+                                       where ProductModels__c = false and ProductCode in :productCodeList];
+            Map<String, Product2> prdsMap = new Map<String, Product2>();
+            for (Product2 prd : prdList) {
+                prdsMap.put(prd.ProductCode, prd);
+            }
+
+            // 鏇存柊瀵惧繙閰嶅垪銈掋偦銉冦儓
+            prdList = new List<Product2>();
+            Map<String, Product2> prdUpdateMap = new Map<String, Product2>();
+            for (SBGITMWebService.GeData GeData : itemMasterList) {
+                if (GeData.ProductCode == null || GeData.ProductCode == '') {
+                    // 蹇呴爤闋呯洰銇屻仾銇勫牬鍚堛�佸嚘鐞嗐仺椋涖伆銇�
+                    iflog.ErrorLog__c += 'MaterialNumber is required\n';
+                    continue;
+                }
+
+                if(String.isBlank(GeData.ProductDescription)){
+                    iflog.ErrorLog__c += 'Description is required:' + GeData.ProductCode  + ' \n';
+                    continue;
+                }
+
+                Product2 prd = prdsMap.get(GeData.ProductCode);
+                String prdName = null;
+                if (prd == null) {
+                    prd = new Product2();
+                }
+                // 闋呯洰杌㈤�併伄銈汇儍銉�
+                prd.ProductCode        = GeData.ProductCode;
+                prd.IsActive = true;
+                if (prdUpdateMap.get(prd.ProductCode) == null) {
+                    prdList.add(prd);
+                    prdUpdateMap.put(prd.ProductCode, prd);
+                    //logstr += GeData.MaterialNumber + ' ';               // 渚℃牸琛ㄣ伄銇ㄣ亾銈嶃伨銇ㄣ倎銇og銈掑嚭銇�
+                } else {
+                    prd = prdUpdateMap.get(prd.ProductCode);
+                }
+
+                // 涓枃鍚嶇О銇岃虎閫併仐銇︺亶銇熷牬鍚�
+                prdName = GeData.ProductDescription;
+                if (prdName != null) {
+                    // 銉囥儠銈┿儷銉堝��
+                    prd.Name = prdName;
+                    String alternative_Products = null;
+                    String nDM_Model_No = null; 
+                    prd.Name = prdName.trim();
+
+                    // 鍨嬬暘:浠f浛鍝�::涓枃鍚嶇О 銇儜銈裤兗銉�
+                    //Pattern pt = Pattern.compile('(.*):(.*)::(.*)');
+                    //Matcher mc = pt.matcher(prdName);
+                    //if (mc.matches() == false
+                    //        && ((prd.Name.indexOf(':') >= 0 && prd.Name.indexOf(':') != prd.Name.indexOf('::'))
+                    //                || (prd.Name.indexOf('锛�') >= 0 && prd.Name.indexOf('锛�') != prd.Name.indexOf('锛氾細'))
+                    //           )
+                    //) {
+                    //    // 鍨嬬暘::涓枃鍚嶇О 銇儜銈裤兗銉�
+                    //    pt = Pattern.compile('(.*):(.*)');
+                    //    mc = pt.matcher(prdName);
+                    //    if (mc.matches()) {
+                    //        nDM_Model_No = mc.group(1).trim(); 
+                    //        prd.Name = mc.group(2).trim();
+                    //        prd.Product_ECCode__c = nDM_Model_No;
+                    //        System.debug('mc is1' + mc);
+                    //        System.debug('prdName is1' + prdName);
+                    //        System.debug('nDM_Model_No is1' + nDM_Model_No);
+                    //    } else {
+                    //        pt = Pattern.compile('(.*)锛�(.*)');
+                    //        mc = pt.matcher(prdName);
+                    //        if (mc.matches()) {
+                    //            nDM_Model_No = mc.group(1).trim();
+                    //            prd.Name =  mc.group(2).trim();
+                    //            prd.Product_ECCode__c = nDM_Model_No;
+                    //            System.debug('mc is2' + mc);
+                    //            System.debug('prdName is2' + prdName);
+                    //            System.debug('nDM_Model_No is2' + nDM_Model_No);
+                    //        }
+                    //    }
+                    //}
+                    
+                    if(prdName.indexOf(':') < 0 && prdName.indexOf('锛�') < 0){
+                        prd.Product_ECCode__c = GeData.ProductCode;
+                    }
+                    else{
+                        Integer max = -1;
+                        Integer min = 100000;
+                        Integer starh = prdName.indexOf(':');
+                        if(starh >= 0){
+                            if(min > starh){
+                                min = starh;
+                            }
+                        }
+                        Integer stara = prdName.indexOf('锛�');
+                        if(stara >= 0){
+                            if(min > stara){
+                                min = stara;
+                            }
+                        }
+                        Integer endh = prdName.lastIndexOf(':');
+                        if(endh >= 0){
+                            if(max < endh){
+                                max = endh;
+                            }
+                        }
+                        Integer enda = prdName.lastIndexOf('锛�');
+                        if(enda >= 0){
+                            if(max < enda){
+                                max = enda;
+                            }
+                        }
+                        prd.Product_ECCode__c = prdName.substring(0,min);
+                        prd.Name =  prdName.substring(max+1,prdName.length());
+                    }
+                    if (GeData.ProductCode != null) {
+                        prd.ProductCode = GeData.ProductCode;
+                    }
+                    if (GeData.ProductDescription != null) {
+                        prd.Description = GeData.ProductDescription;
+                    }
+                    if (GeData.ProductStatus != null) {
+                        prd.ProductStatus__c = GeData.ProductStatus;
+                    }
+                    if (GeData.EffectiveDateTo != null) {
+                        prd.EffectiveDateTo__c = NFMUtil.parseStr2Date(GeData.EffectiveDateTo, true);
+                    }
+                }
+            }
+            if (prdList.size() > 0) {
+                logstr += 'Execute Record:' + prdList.size() + '\n';
+                upsert prdList;
+                // PricebookEntry銇儑銉笺偪銇屻仾銇勫牬鍚坕nsert銇欍倠銆丆NY銇║SD銇伩
+                Pricebook2 pricebook = ControllerUtil.getStandardPricebook();
+         
+                    String pricebookId = pricebook.Id;
+                    List<PricebookEntry> pbeList = [Select Product2Id, CurrencyIsoCode, UnitPrice, Pricebook2Id From PricebookEntry where Product2Id in: prdList and Pricebook2Id = :pricebookId order by Product2Id, CurrencyIsoCode];
+                    List<PricebookEntry> pbeInsertList = new List<PricebookEntry>();
+                    Map<String, PricebookEntry> rmbMap = new Map<String, PricebookEntry>();
+                    Map<String, PricebookEntry> usdMap = new Map<String, PricebookEntry>();
+                    for (PricebookEntry pbe : pbeList) {
+                        if (pbe.CurrencyIsoCode == 'CNY') {
+                            rmbMap.put(pbe.Product2Id, pbe);
+                        } else if (pbe.CurrencyIsoCode == 'USD') {
+                            usdMap.put(pbe.Product2Id, pbe);
+                        }
+                    }
+                    for (Product2 prd : prdList) {
+                        logstr += prd.ProductCode;
+                        if (rmbMap.get(prd.Id) == null) {
+                            PricebookEntry pbe = new PricebookEntry();
+                            pbe.Pricebook2Id    = pricebookId;
+                            pbe.Product2Id      = prd.Id;
+                            pbe.CurrencyIsoCode = 'CNY';
+                            pbe.UnitPrice       = 0;
+                            pbe.IsActive        = prd.IsActive;
+                            pbeInsertList.add(pbe);
+                            logstr += ' add(CNY_0)';
+                        }
+                        if (usdMap.get(prd.Id) == null) {
+                            PricebookEntry pbe = new PricebookEntry();
+                            pbe.Pricebook2Id    = pricebookId;
+                            pbe.Product2Id      = prd.Id;
+                            pbe.CurrencyIsoCode = 'USD';
+                            pbe.UnitPrice       = 0;
+                            pbe.IsActive        = prd.IsActive;
+                            pbeInsertList.add(pbe);
+                            logstr += ' add(USD_0)';
+                        }
+                        logstr += ' ';
+                    }
+                    if (pbeInsertList.size() > 0) {
+                        logstr += 'Execute Record2:' + pbeInsertList.size() + '\n';
+                        insert pbeInsertList;
+                    }
+            }
+            logstr += '\nend';
+            rowData.retry_cnt__c = 0;
+        }catch(Exception ex){
+            // 銈ㄣ儵銉笺亴鐧虹敓銇椼仧鍫村悎
+            Database.rollback(sp);
+            System.debug(Logginglevel.ERROR, 'SBGITM_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
+            System.debug(Logginglevel.ERROR, 'SBGITM_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
+            logstr += '\n' + ex.getMessage();
+            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
+            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
+            if (rowData.retry_cnt__c < batch_retry_max_cnt){
+                rowData.retry_cnt__c++;
+                LogAutoSendSchedule.assignOneMinute();
+            }
+            if (rowData.retry_cnt__c >= batch_retry_max_cnt){
+                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c+'閿欒娆℃暟宸茬粡瓒呰繃鑷姩鏀朵俊璁惧畾鐨勬渶澶ф鏁帮紝璇锋墜鍔ㄦ敹淇�';
+            }
+        }
+        update rowData;
+        iflog.Log__c = logstr;
+        if (iflog.Log__c.length() > 131072) {
+            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
+        }
+        if (iflog.ErrorLog__c.length() > 32768) {
+            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
+        }
+        update iflog;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBGITMWebService.cls-meta.xml b/scr/classes/SBGITMWebService.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBGITMWebService.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SBGITMWebServiceTest.cls b/scr/classes/SBGITMWebServiceTest.cls
new file mode 100644
index 0000000..c72a273
--- /dev/null
+++ b/scr/classes/SBGITMWebServiceTest.cls
@@ -0,0 +1,185 @@
+@isTest
+private class SBGITMWebServiceTest {
+        @isTest
+	static void testSBDITM_void() {
+	Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMWebService.GeData GeData = new SBGITMWebService.GeData();
+        SBGITMWebService.GeDatas GeDatas = new SBGITMWebService.GeDatas();
+        GeDatas.GeData = new SBGITMWebService.GeData[] { GeData };
+        // 绌恒仯銇�1
+        SBGITMWebService.SBGITM(GeDatas);
+
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '01';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        SBGITMWebService.SBGITM(GeDatas);
+
+        // 蹇呴爤闋呯洰銈掋偦銉冦儓銇椼仾銇�
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '02';
+        GeData.EffectiveDateTo                            = '29121103';
+        GeData.ProductCode                = 'SBGITMTst1';
+        SBGITMWebService.SBGITM(GeDatas);
+
+        // ZH銇с伅銇亜
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '03';
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription      = 'GIF-X0261:stop2012.8::Gastroscopy';
+        SBGITMWebService.SBGITM(GeDatas);
+
+        Product2[] rslts = [select Id from Product2 where ProductCode = :GeData.ProductCode];
+        System.assertEquals(0, rslts.size());
+	}
+        @isTest
+        static void testSBGITM_insert() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMWebService.GeDatas GeDatas = new SBGITMWebService.GeDatas();
+        SBGITMWebService.GeData GeData = new SBGITMWebService.GeData();
+        SBGITMWebService.GeData GeData2 = new SBGITMWebService.GeData();
+        GeDatas.GeData = new SBGITMWebService.GeData[] { GeData, GeData2 };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+
+        // insert2
+        GeData2.ProductCode                = 'SBGITMTst2';
+        GeData2.ProductDescription                 = 'ABCD12345:ABC';
+        GeData2.ProductStatus                    = '0';
+        GeData2.EffectiveDateTo                      = '20121101';
+
+        System.Test.startTest();
+        SBGITMWebService.SBGITM(GeDatas);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id,Name,
+                                ProductCode,
+                                Product_ECCode__c,
+                                EffectiveDateTo__c,
+                                ProductModels__c,
+                                ProductStatus__c
+                              from Product2
+                             where Product_ECCode__c = 'ABCD1234'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst1', rslts[0].ProductCode);
+        }
+        rslts = [select Id, 
+                        ProductCode,Name,
+                        Product_ECCode__c,
+                        EffectiveDateTo__c,
+                        ProductModels__c,
+                        ProductStatus__c
+                from Product2
+                where Product_ECCode__c = 'ABCD12345'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst2', rslts[0].ProductCode);
+            System.assertEquals('ABC', rslts[0].Name);
+        }
+    }
+
+    @isTest
+        static void testSBGITM_update() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMWebService.GeDatas GeDatas = new SBGITMWebService.GeDatas();
+        SBGITMWebService.GeData GeData = new SBGITMWebService.GeData();
+        GeDatas.GeData = new SBGITMWebService.GeData[] { GeData };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+
+
+        System.Test.startTest();
+        SBGITMWebService.SBGITM(GeDatas);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id, 
+                                ProductCode, 
+                                Product_ECCode__c,
+                                EffectiveDateTo__c,
+                                ProductModels__c,
+                                ProductStatus__c
+                              from Product2
+                             where Product_ECCode__c = 'ABCD1234'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst1', rslts[0].ProductCode);
+        }
+    }
+
+    @isTest
+        static void testSBGITM_resend() {
+        Id pricebookId = ControllerUtil.getStandardPricebook().Id;
+        SBGITMWebService.GeDatas GeDatas = new SBGITMWebService.GeDatas();
+        SBGITMWebService.GeData GeData = new SBGITMWebService.GeData();
+        GeDatas.GeData = new SBGITMWebService.GeData[] { GeData };
+        // Monitoring銇ō瀹�
+        Datetime nowDT = Datetime.now();
+        String nowStr = nowDT.format('yyyyMMddHHmm');
+        GeDatas.Monitoring = new NFMUtil.Monitoring();
+        GeDatas.Monitoring.MessageGroupNumber = nowStr + '11';
+
+        // insert
+        GeData.ProductCode                = 'SBGITMTst1';
+        GeData.ProductDescription                 = 'ABCD1234:ABC';
+        GeData.ProductStatus                    = '1';
+        GeData.EffectiveDateTo                      = '20121101';
+
+
+        System.Test.startTest();
+        SBGITMWebService.SBGITM(GeDatas);
+        System.Test.stopTest();
+        Product2[] rslts = [select Id, 
+                                ProductCode, 
+                                Product_ECCode__c,
+                                EffectiveDateTo__c,
+                                ProductModels__c,
+                                ProductStatus__c
+                              from Product2
+                             where Product_ECCode__c = 'ABCD1234'];
+        System.assertEquals(1, rslts.size());
+        if (rslts.size() == 1) {
+            System.assertEquals('SBGITMTst1', rslts[0].ProductCode);
+        }
+        List<BatchIF_Log__c> rowbl = [Select Id, Log__c,
+                                            ErrorLog__c
+                                        from BatchIF_Log__c
+                                        where RowDataFlg__c = true
+                                        and Type__c = 'SBGITM'
+                                        order by CreatedDate desc];
+        List<BatchIF_Log__c> rowbl1 = [Select Id, Log__c,
+                                            ErrorLog__c
+                                        from BatchIF_Log__c
+                                        where RowDataFlg__c = true
+                                        order by CreatedDate desc];
+        System.debug(rowbl1);
+        System.assertEquals(1, rowbl.size());
+        rowbl[0].retry_cnt__c = 1;
+        update rowbl;
+
+        SBGITMWebService.execute(rowbl[0].id);
+
+        List<BatchIF_Log__c> bl = [Select Id, Is_Error__c,
+                Type__c, Log__c, ErrorLog__c,retry_cnt__c
+                from BatchIF_Log__c
+                where Id = :rowbl[0].id];
+        System.assertEquals(1, bl.size());
+        System.assertEquals(0, bl[0].retry_cnt__c);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SBGITMWebServiceTest.cls-meta.xml b/scr/classes/SBGITMWebServiceTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SBGITMWebServiceTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SSOpporToSSBDallRepBatch.cls b/scr/classes/SSOpporToSSBDallRepBatch.cls
new file mode 100644
index 0000000..c5b4ebd
--- /dev/null
+++ b/scr/classes/SSOpporToSSBDallRepBatch.cls
@@ -0,0 +1,59 @@
+global class SSOpporToSSBDallRepBatch implements Database.Batchable<sObject> {
+	/*鎵цBatch锛屽缓绔婼S_璇环浜у搧娓呭崟锛圫S_Opportunity_detail_product__c锛夊拰SSBD_All_Report锛圫SBD_All_Report__c锛�
+	鐨勫搴斿叧绯�:
+		浠嶴SBD_All_Report__c涓嫹璐濆嚭璇环Id鍜孲SBD_All_Report__c.id锛岄�氳繃SSBD_All_Report__c鍜孲S_璇环浜у搧娓呭崟鍏辨湁鐨�
+		璇环id鏉ュ缓绔嬩袱鑰呬箣闂寸殑瀵瑰簲鍏崇郴
+	*/
+	String query;
+	List<Id> OppoIDList;
+	global SSOpporToSSBDallRepBatch(List<id> elementID) {
+		
+	}
+	global SSOpporToSSBDallRepBatch(boolean Single) {
+		
+	}
+	global SSOpporToSSBDallRepBatch() {
+		
+	}
+	global Database.QueryLocator start(Database.BatchableContext BC) {
+		query	=	'SELECT Id,OpportunityName__c, OpportunityID__c FROM SSBD_All_Report__c';
+		return Database.getQueryLocator(query);
+	}
+
+	global void execute(Database.BatchableContext BC, List<sObject> scope) {
+		List<SSBD_All_Report__c>	SARList	=	new	List<SSBD_All_Report__c>();
+		SARList	=	scope;
+		Map<id,id>	SAR_id_Map	=	new	Map<id,id>();
+		List<id>	OppoIdBatchList	=	new	List<id>();
+		for(SSBD_All_Report__c	ssr	:	SARList){
+			OppoIdBatchList.add(ssr.OpportunityID__c);
+			SAR_id_Map.put(ssr.OpportunityID__c, ssr.id);
+		}
+		system.debug('OppoIdBatchList::::'+OppoIdBatchList);
+		List<SS_Opportunity_detail_product__c>	SSopdList	=	new	List<SS_Opportunity_detail_product__c>();
+		List<SS_Opportunity_detail_product__c>	SSopdListUpdate	=	new	List<SS_Opportunity_detail_product__c>();
+		
+		SSopdList	=	[SELECT	
+								Id, 
+								OpportunityName__c, 
+								SSBD_All_Report_ID__c, 
+								OpportunityID__c
+						FROM
+								SS_Opportunity_detail_product__c
+						where	
+								OpportunityName__c	in:	OppoIdBatchList
+						];
+		system.debug('SSopdList::::'+SSopdList);
+		for(	SS_Opportunity_detail_product__c	sodp	:	SSopdList	){
+			sodp.SSBD_All_Report_ID__c	=	SAR_id_Map.get(sodp.OpportunityID__c);
+			SSopdListUpdate.add(sodp);
+		}
+		update	SSopdListUpdate;
+
+	}
+	
+	global void finish(Database.BatchableContext BC) {
+		
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/SSOpporToSSBDallRepBatch.cls-meta.xml b/scr/classes/SSOpporToSSBDallRepBatch.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SSOpporToSSBDallRepBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SSOpportunityBatch.cls b/scr/classes/SSOpportunityBatch.cls
new file mode 100644
index 0000000..2200912
--- /dev/null
+++ b/scr/classes/SSOpportunityBatch.cls
@@ -0,0 +1,214 @@
+public without sharing class SSOpportunityBatch implements Database.Batchable<SObject>, Database.Stateful {
+    public static Integer FIELDMAX = 30;
+    private final List<Id> TEST_ID = null;
+    private BatchIF_Log__c iflog;
+
+    /**
+     * 銈炽兂銈广偪銉炽儓銆併儜銉┿儭銉笺偪銈掑彈銇戝彇銈�
+     */
+    public SSOpportunityBatch(List<Id> testId) {
+        TEST_ID = testId;
+        System.debug('TEST_ID=' + TEST_ID);
+        iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'PushNotification';
+        iflog.Log__c  = 'SSOpportunityBatch start\n';
+        iflog.ErrorLog__c = '';
+        insert iflog;
+    }
+    
+    public static String makeSql(SS_Batch_Column_Mapping__c setting, Set<String> apiTempSet) {
+        apiTempSet.add('Id');
+        for (Integer i = 1; i <= FIELDMAX; i++) {
+            String fromColumn = 'From_Column_' + ('00' + i).right(3) + '__c';
+            String apiStr = String.valueOf(setting.get(fromColumn));
+            if (String.isBlank(apiStr) == false && apiTempSet.contains(apiStr) == false) {
+                apiTempSet.add(apiStr);
+            }
+        }
+        String soql = 'Select ' + String.join(new List<String>(apiTempSet), ',') + ' from ' + setting.Name;
+        return soql;
+    }
+
+    public static Object getValue(SObject sobj, String field) {
+        List<String> fieldPathList = field.split('\\.');
+        Object rtn = null;
+        for (Integer i = 0; i < fieldPathList.size(); i++) {
+            String fieldPath = fieldPathList[i];
+            if (i == fieldPathList.size() - 1) {
+                rtn = sobj.get(fieldPath);
+System.debug(rtn + '=*** sobj.get(' + fieldPath + ')');
+            } else {
+                sobj = sobj.getSObject(fieldPath);
+                if (sobj == null) {
+                    break;
+                }
+System.debug(sobj + '=### sobj.getSObject(' + fieldPath + ')');
+            }
+        }
+        return rtn;
+    }
+
+    /**
+     * start銇伅銆乹uery銈掑疅琛屻�佸紩鍚堝叏浠�
+     */
+    public Database.QueryLocator start(Database.BatchableContext BC) {
+        // select闋呯洰銈� oppMapping 銈堛倞鐢熸垚
+        SS_Batch_Column_Mapping__c oppMapping = SS_Batch_Column_Mapping__c.getValues('Opportunity');
+        Set<String> apiTempSet = new Set<String>();
+        apiTempSet.add('StageName');
+        for (Integer i = 1; i <= FIELDMAX; i++) {
+            String lpadI = ('00' + i).right(3);
+            String fromColumn = 'From_Column_' + lpadI + '__c';
+            String apiStr = String.valueOf(oppMapping.get(fromColumn));
+            if (String.isBlank(apiStr) == false) {
+                String ssColumn = 'SS_Column_' + lpadI + '__c';
+                String ssApiStr = String.valueOf(oppMapping.get(ssColumn));
+                if (ssApiStr.toLowerCase().startsWith('opportunity.')) {
+                    // 鍟嗚珖銇爡鐩倰鏇存柊銆佸鏇淬亴銇傘倠銇嬨仼銇嗐亱鍒ゆ柇銇欍倠銇熴倎銆佸厓銉囥兗銈裤倐鍙栧緱
+                    System.debug('ssApiStr=' + ssApiStr + ', substring(12)=' + ssApiStr.substring(12));
+                    apiTempSet.add(ssApiStr.substring(12));
+                }
+            }
+        }
+        String soql = makeSql(oppMapping, apiTempSet);
+        if (TEST_ID <> null) {
+            soql += ' where Id IN: TEST_ID';
+        } else {
+// SS_Prospect_5days_list__c  銇璞°亱銇┿亞銇嬨�乴oop銇腑鍗樼嫭鍒ゆ柇
+//            soql += ' where StageName = \'寮曞悎\'';
+        }
+        System.debug('soql=' + soql);
+        return Database.getQueryLocator(soql);
+    }
+    
+    public void execute(Database.BatchableContext BC, List<Opportunity> oppList) {
+        List<Opportunity> updSelfList = new List<Opportunity>();
+        List<SObject> insSSOppList = new List<SObject>();
+        List<Id> insSSOppId = new List<Id>();
+        List<SObject> insSSOliList = new List<SObject>();
+        //20161205Add
+        Map<id,id> SSBDreportToSSodp = new Map<id,id>();
+        // 鍟嗚珖
+        system.debug('===================111111111');
+        SS_Batch_Column_Mapping__c oppMapping = SS_Batch_Column_Mapping__c.getValues('Opportunity');
+        Schema.SObjectType ssOppType = Schema.getGlobalDescribe().get(String.valueOf(oppMapping.get('SS_TableName__c')));
+        for (Opportunity opp : oppList) {
+            Boolean updSelfFlg = false;
+            SObject insSSOpp = ssOppType.newSObject();
+            for (Integer i = 1; i <= FIELDMAX; i++) {
+                String lpadI = ('00' + i).right(3);
+                String fromColumn = 'From_Column_' + lpadI + '__c';
+                String apiStr = String.valueOf(oppMapping.get(fromColumn));
+                system.debug('======8888'+String.isBlank(apiStr));
+                if (String.isBlank(apiStr) == false) {
+                    String ssColumn = 'SS_Column_' + lpadI + '__c';
+                    String ssApiStr = String.valueOf(oppMapping.get(ssColumn));
+                     system.debug('===================77777'+ssApiStr.toLowerCase().startsWith('opportunity.')+ssApiStr.toLowerCase());
+                    if (ssApiStr.toLowerCase().startsWith('opportunity.')) {
+                        // 鍟嗚珖銇爡鐩倰鏇存柊銆佸鏇淬亴銇傘倠銇嬨仼銇嗐亱鍒ゆ柇銇欍倠
+                         system.debug('===================5555'+opp.get(ssApiStr.substring(12)) +'^^^^^^'+ opp.get(apiStr));
+                        if (opp.get(ssApiStr.substring(12)) != opp.get(apiStr)) {
+                            try {
+                                opp.put(ssApiStr.substring(12), opp.get(apiStr));
+                                updSelfFlg = true;
+                            } catch (Exception e) {
+                                iflog.ErrorLog__c = 'ERROR [' + apiStr + '] => [' + ssApiStr + ']' + e.getMessage() + '\n';
+                            }
+                        }
+                    } else {
+                        try {
+                            insSSOpp.put(ssApiStr, getValue(opp, apiStr));
+                        } catch (Exception e) {
+                            iflog.ErrorLog__c = 'ERROR ' + String.valueOf(oppMapping.get('SS_TableName__c')) + ' [' + apiStr + '] => [' + ssApiStr + ']' + e.getMessage() + '\n';
+                        }
+                    }
+                }
+            }
+            system.debug('===================222222222'+insSSOpp);
+            if (updSelfFlg) {
+                updSelfList.add(opp);
+            }
+            system.debug(updSelfList);
+            // SS_Prospect_5days_list__c  銇璞°亱銇┿亞銇嬨�乴oop銇腑鍗樼嫭鍒ゆ柇
+            //if (opp.StageName == '寮曞悎') {
+                insSSOppList.add(insSSOpp);
+                insSSOppId.add(opp.Id);
+                
+            //}
+        }
+        insert insSSOppList;
+        system.debug('===================888888888'+insSSOppList[0].id);
+        for(integer i = 0; i< insSSOppList.size();i++){
+            SSBDreportToSSodp.put(insSSOppId[i],insSSOppList[i].id);
+        }
+        // 鍟嗚珖鍟嗗搧
+        SS_Batch_Column_Mapping__c oliMapping = SS_Batch_Column_Mapping__c.getValues('OpportunityLineItem');
+        // select闋呯洰銈� oliMapping 銈堛倞鐢熸垚
+        Set<String> apiTempSet = new Set<String>();
+        String oliSql = makeSql(oliMapping, apiTempSet);
+        oliSql += ' where OpportunityId IN :insSSOppId';
+        Schema.SObjectType ssOliType = Schema.getGlobalDescribe().get(String.valueOf(oliMapping.get('SS_TableName__c')));
+        for (OpportunityLineItem oli : Database.query(oliSql)) {
+            SObject insSSOli = ssOliType.newSObject();
+            insSSOliList.add(insSSOli);
+            for (Integer i = 1; i <= FIELDMAX; i++) {
+                String lpadI = ('00' + i).right(3);
+                String fromColumn = 'From_Column_' + lpadI + '__c';
+                String apiStr = String.valueOf(oliMapping.get(fromColumn));
+                if (String.isBlank(apiStr) == false) {
+                    String ssColumn = 'SS_Column_' + lpadI + '__c';
+                    String ssApiStr = String.valueOf(oliMapping.get(ssColumn));
+                    try {
+                        insSSOli.put(ssApiStr, getValue(oli, apiStr));
+                    } catch (Exception e) {
+                        iflog.ErrorLog__c = 'ERROR ' + String.valueOf(oppMapping.get('SS_TableName__c')) + ' [' + apiStr + '] => [' + ssApiStr + ']' + e.getMessage() + '\n';
+                    }
+                }
+            }
+            insSSOli.put('SSBD_All_Report_ID__c', SSBDreportToSSodp.get(oli.ID_test1__c));
+            System.debug('insSSOli:' + insSSOli);
+        }
+        
+
+        // 銈ㄣ儵銉笺倰log銇浉銇嶅嚭銇�
+        if (updSelfList.size() > 0) {
+System.debug('updSelfList:' + updSelfList);
+            Database.SaveResult[] lsr = Database.update(updSelfList, false);
+            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
+                Database.SaveResult sr = lsr[tIdx];
+System.debug('sr.isSuccess:' + sr.isSuccess());
+                if (!sr.isSuccess()) {
+                    Database.Error emsg = sr.getErrors()[0];
+                    iflog.ErrorLog__c += 'ERROR Opportunity:' + emsg + '\n';
+                }
+            }
+        }
+        
+        
+        insert insSSOliList;
+        //SSBD_ALL_Report to 
+        //**************************************************************************************************************
+        //
+        //**************************************************************************************************************
+        //**************************************************************************************************************
+        //
+        //**************************************************************************************************************
+        
+    }
+    
+    public void finish(Database.BatchableContext BC) {
+
+        if (Test.isRunningTest() == false && TEST_ID == null) {
+          //  Database.executeBatch(new SSOpporToSSBDallRepBatch(), 100);
+        }
+
+        iflog.Log__c += '\nSSOpportunityBatch 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;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SSOpportunityBatch.cls-meta.xml b/scr/classes/SSOpportunityBatch.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/SSOpportunityBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SSOpportunitySchedule.cls b/scr/classes/SSOpportunitySchedule.cls
new file mode 100644
index 0000000..0a682ce
--- /dev/null
+++ b/scr/classes/SSOpportunitySchedule.cls
@@ -0,0 +1,5 @@
+global class SSOpportunitySchedule implements Schedulable {
+    global void execute(SchedulableContext SC) {
+            Id execBTId = Database.executeBatch(new SSOpportunityBatch(null), 100);
+        }
+}
\ No newline at end of file
diff --git a/scr/classes/SSOpportunitySchedule.cls-meta.xml b/scr/classes/SSOpportunitySchedule.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/SSOpportunitySchedule.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOController.cls b/scr/classes/SWOController.cls
new file mode 100644
index 0000000..5c6dbe2
--- /dev/null
+++ b/scr/classes/SWOController.cls
@@ -0,0 +1,753 @@
+public with sharing class SWOController {
+
+	public SWO__c swo {get; set;}
+
+	public String swoid {get; set;}
+	public String accId {get; set;}
+	public String conId {get; set;}
+	public List<EmailInfo> mailList {get; set;}
+
+	public String baseUrl {get; set;}
+	public String type {get; set;}
+	public String caseId {get; set;}
+
+	public String name {get; set;}
+
+	public List<Quotes_item__c> qiList {get; set;}
+
+	public List<RepairPart__c> rpList {get; set;}
+
+	public List<Attachment> attachmentList {get; set;}
+
+	public List<diagnosisInfo> diagnosisList {get; set;} 
+
+	public String errorMessageInfo{get;set;}
+
+	public String assignedUser{get;set;}
+
+	public Integer lineCount{get; set;}
+	//RepairPart 鑷紑鍙戦〉闈繚瀛樿繑鍥炴帴鏀�
+	public String repairId{get;set;}
+	//RepairPart 鑷紑鍙戦〉闈繚瀛樿繑鍥炲悗鏌ヨ鏇存柊
+	public RepairPart__c repairPart{get;set;}
+
+	private String SwoStatus;
+	//ASSIGNEDTO__c
+	public SWOController() {
+		
+	}
+
+	public SWOController(ApexPages.StandardController stdController) {
+		swoid = System.currentPageReference().getParameters().get('id');
+		caseId = System.currentPageReference().getParameters().get('caseId');
+		accId = System.currentPageReference().getParameters().get('accId');
+		conId = System.currentPageReference().getParameters().get('conId');
+		type = System.currentPageReference().getParameters().get('type');
+		System.debug(caseId);
+	}
+
+	public void init() {
+		lineCount = 0;
+		//鑾峰彇鍒濆URL
+		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+		String path = URL.getCurrentRequestUrl().getPath();
+		if (path.indexOf('/apex') > 0) {
+			baseUrl += path.substring(0, path.indexOf('/apex'));
+		} else if (path.indexOf('production/') > 0) {
+			baseUrl += '/production';
+		}
+		//鍒濆鍖栧叏灞�鍙橀噺
+		swo = new SWO__c();
+		mailList = new List<EmailInfo>();
+		if(String.isBlank((type))){
+			type = 'Product';
+		}
+		//濡傛灉ID涓嶄负绌哄垵濮嬪寲SWO鍜岀浉鍏冲垪琛�
+		User_FaultInfo__c ca = new User_FaultInfo__c();
+		List<SWO__c> temp = new List<SWO__c>();
+		if (caseId != null) {
+			ca = [select id, NUMBER__c,COMPANY__c,CONTACT__c,SUBJECT__c from User_FaultInfo__c where id = : caseId];
+			temp = [select id from SWO__c where CASE_NUMBER__c = :caseId];
+		}
+		System.debug('ca' + ca.NUMBER__c);
+		System.debug('temp' + temp.size());
+		if (swoid != null) {
+			//鍒濆鍖朣WO
+			Schema.DescribeSobjectResult d_swo = SWO__c.sObjectType.getDescribe();
+			Map<String, Schema.SObjectField> d_swo_map = d_swo.fields.getMap();
+			String soql_swo = 'select ';
+			String fields_odr = '';
+			for (String field : d_swo_map.keySet()) {
+				if (fields_odr.length() > 0) {
+					fields_odr += ', ';
+				}
+				fields_odr += field;
+			}
+			soql_swo += fields_odr;
+			soql_swo += ' from SWO__c where Id = \'' + swoid + '\'';
+			List<SWO__c> swoList = Database.query(soql_swo);
+			if (swoList.size() > 0) {
+				swo = swoList[0];
+			}
+			//鍒濆鍖栬褰昐WO 鍘熷ASSIGNED TO锛屼繚瀛樻椂鍒ゆ柇鐢ㄦ埛鏄惁鍙樻洿锛屽鏋滃彉鏇寸粰鐢ㄦ埛鍙戦�侀偖浠�
+			assignedUser = swo.ASSIGNEDTO__c;
+			//鍒濆鍖朚ail Merge
+			List<String> mailIdList = new List<String>();
+
+			List<Attachment> attList = new List<Attachment>();
+			Map<String, List<Attachment>> attMap = new Map<String, List<Attachment>>();
+
+			Map<String, Mail_Merge__c> mailMap = new Map<String, Mail_Merge__c>([select id, FROM__c, ccName__c, SUBJECT__c, MESSAGE__c, DATE__c, toName__c, EMAIL_SENT__c from Mail_Merge__c where SWO__c = :swoid order by id]);
+			//mailMap = [select id,FROM__c,ccName__c,SUBJECT__c,MESSAGE__c from Mail_Merge__c where SWO__c = :id order by id];
+
+			if (mailMap != null) {
+				mailIdList.addAll(mailMap.keySet());
+
+				attList =  [select id, Name, ParentId from Attachment where ParentId in :mailIdList order by ParentId, id];
+				if (attList.size() > 0) {
+					for (Attachment att : attList) {
+						if (attMap.containsKey(att.ParentId)) {
+							attMap.get(att.ParentId).add(att);
+						} else {
+							List<Attachment> a = new List<Attachment>();
+							a.add(att);
+							attMap.put(att.ParentId, a);
+						}
+					}
+				}
+
+				for (String id : mailMap.keySet()) {
+					if (attMap.containsKey(id)) {
+						mailList.add(new EmailInfo(mailMap.get(id), attMap.get(id)));
+					} else {
+						mailList.add(new EmailInfo(mailMap.get(id), null));
+					}
+				}
+			}
+
+			//鍒濆鍖朡uote
+
+			Map<String, Quotes__c> quoMap = new Map<String, Quotes__c>( [select id from Quotes__c where SWO__c = :swoid order by id]);
+			if (quoMap.size() > 0) {
+				qiList = [select id, QUOTE__r.id, QUOTE__r.Name, QUOTE__r.STATUS__c, QuotesItemProduct__c, PART_NUMBERNew__c, QUANTITY__c, CURRENCY__c, AMOUNT__c,QUOTE__r.InvalidData__c from Quotes_item__c where QUOTE__r.InvalidData__c = false And QUOTE__c in : quoMap.keySet() order by QUOTE__c, id];
+			}
+
+			//鍒濆鍖杛pList
+			rpList = new List<RepairPart__c>();
+			rpList = [select Id, Name, Product__c, DescriptionNew__c, PART_NUMBERNew__c, INST_SERIAL__c, QUANTITY__c, DEFECT_PART_NUMBER__c, DEFECT_SERIAL_NUMBER__c, ANI_DEFECT_CATEGORY__c, HOURS__c, LOCATION__c, BILL_AT_0_VALUE__c, ECN__c, QTY_PICKED__c,
+			Product__r.Description,Product__r.Product_ECCode__c,Product__r.ProductCode from RepairPart__c where SWO_ID__c = :swoid order by Id];
+			//鍒濆鍖栭檮浠�
+			attachmentList = [select Id, Name, CreatedDate, BodyLength from Attachment where ParentId = :swoid];
+
+			//鍒濆鍖杁iagnosis
+			List<Diagnosis_Part__c> diList = new List<Diagnosis_Part__c>();
+
+			diList = [select Id,SWO__c,DELIVERED__c,DESCRIPTION__c,HOLD_REASON__c,INST_SERIAL__c,PART_NUMBER__c,QUANTITY__c,REMARK__c,RETURN_DATE__c,RETURNED__c,STATUS__c,Product__c,ITEM__c,DeliveredDate__c,
+			Product__r.Description,Product__r.Product_ECCode__c,Product__r.ProductCode from Diagnosis_Part__c where SWO__c = :swoid];
+			if(diList.size() > 0){
+				diagnosisList = new List<diagnosisInfo>();
+				for(Diagnosis_Part__c di : diList){
+					diagnosisList.add(new diagnosisInfo(di,lineCount));
+					lineCount++;
+				}
+			}
+		} else {
+			//娌℃湁swoId鐨勫垵濮嬪寲鍐呭
+			swo = new SWO__c();
+			if(caseId != null){
+				swo.COMPANY__c = ca.COMPANY__c;
+				swo.CONTACT__c = ca.CONTACT__c;
+				swo.Name = ca.NUMBER__c + '-' + (temp.size() + 1);
+				swo.CASE_NUMBER__c = caseId;
+				swo.SUBJECT__c = ca.SUBJECT__c;
+			}
+			if(accId != null){
+				swo.COMPANY__c = accId;
+			}
+			if(conId != null){
+				swo.CONTACT__c = conId;
+			}
+			swo.SWO_STATUS__c = 'Not Started';
+		}
+		SwoStatus = swo.SWO_STATUS__c;
+	}
+
+	/**
+	 * 淇濆瓨鏂规硶
+	 * @return [description]
+	 */
+	public PageReference save() {
+		System.debug('save');
+		//errorMessage = '';
+		
+		//褰揝WO Status 鏀瑰彉涓篞uotation for approval鏃�,姝ゆ椂闂寸偣鑷姩鎶撳彇濉厖姝ゅ锛�
+		if(mustData() == false){
+			return null;
+		}
+		//ASSIGNED_TO_TECHNICIAN_DATE__c
+		/*if(swo.SWO_STATUS__c == 'Delivered to Technician'){
+			swo.ASSIGNED_TO_TECHNICIAN_DATE__c = Datetime.now();
+		}*/
+		errorMessageInfo = '';
+		//Days-in-house 鐢� instruments ship date瑁呰繍鏃堕棿 涓巌nstrument receive date绛炬敹鏃堕棿 璁$畻
+		String dateTimeErrorMessage = '';
+		/*Boolean dateJudge = true;*/
+		if(swo.INSTRUMENT_RECEIVE_DATE__c != null && swo.INSTRUMENT_SHIP_DATE__c != null){
+			swo.DAYS_IN_HOUSE__c = getTimeLongStr(swo.INSTRUMENT_SHIP_DATE__c,swo.INSTRUMENT_RECEIVE_DATE__c);
+			/*if(swo.INSTRUMENT_SHIP_DATE__c>swo.INSTRUMENT_RECEIVE_DATE__c){
+				swo.DAYS_IN_HOUSE__c = getTimeLongStr(swo.INSTRUMENT_SHIP_DATE__c,swo.INSTRUMENT_RECEIVE_DATE__c);
+			}else{
+				errorMessageInfo += 'DAYS IN HOUSE 寮�濮嬫椂闂村ぇ浜庣粨鏉熸椂闂�;-';
+				dateJudge = false;
+			}*/
+		}
+		//Diagnosis time 鐢眃iagnosis end 涓巇iagnosis start璁$畻
+		if (swo.DIAGNOSIS_START__c!=null && swo.DIAGNOSIS_END__c!=null) {
+			swo.DIAGNOSIS_TIME__c = getTimeLongStr(swo.DIAGNOSIS_START__c,swo.DIAGNOSIS_END__c);
+			/*if(swo.DIAGNOSIS_START__c < swo.DIAGNOSIS_END__c){
+				swo.DIAGNOSIS_TIME__c = getTimeLongStr(swo.DIAGNOSIS_START__c,swo.DIAGNOSIS_END__c);
+			}else{
+				errorMessageInfo += 'DIAGNOSIS TIME 寮�濮嬫椂闂村ぇ浜庣粨鏉熸椂闂�;-';
+				dateJudge = false;
+			}*/
+		}
+		//Time awaiting PO鐢盤O received date 涓巕uotation send 璁$畻
+		if (swo.PO_RECEIVE_DATE__c != null && swo.Quotation_send__c!=null) {
+			swo.TIME_AWAITING_PO__c = getTimeLongStr(swo.PO_RECEIVE_DATE__c,swo.Quotation_send__c);
+			/*if(swo.PO_RECEIVE_DATE__c < swo.Quotation_send__c){
+				swo.TIME_AWAITING_PO__c = getTimeLongStr(swo.PO_RECEIVE_DATE__c,swo.Quotation_send__c);
+			} else {
+				errorMessageInfo += 'PO received date 蹇呴』灏忎簬 quotation send;-';
+				dateJudge = false;
+			}*/
+		}
+		//REPAIR_TIME__c
+		if(swo.REPAIR_START__c!=null && swo.REPAIR_END__c!=null){
+			swo.REPAIR_TIME__c = getTimeLongStr(swo.REPAIR_START__c,swo.REPAIR_END__c);
+			/*if(swo.REPAIR_START__c < swo.REPAIR_END__c){
+				swo.REPAIR_TIME__c = getTimeLongStr(swo.REPAIR_START__c,swo.REPAIR_END__c);
+			}else{
+				errorMessageInfo += 'REPAIR TIME 寮�濮嬫椂闂村ぇ浜庣粨鏉熸椂闂�;-';
+				dateJudge = false;
+			}*/
+		}
+		//Calibration time鐢眂alibration end 涓巆alibration start璁$畻
+		if(swo.CALIBRATION_START__c != null && swo.CALIBRATION_END__c != null){
+			//swo.CALIBRATION_TIME__c = swo.CALIBRATION_END__c - CALIBRATION_START__c;
+			swo.CALIBRATION_TIME__c = getTimeLongStr(swo.CALIBRATION_START__c,swo.CALIBRATION_END__c);
+			/*if(swo.CALIBRATION_START__c < swo.CALIBRATION_END__c){
+				swo.CALIBRATION_TIME__c = getTimeLongStr(swo.CALIBRATION_START__c,swo.CALIBRATION_END__c);
+			}else{
+				errorMessageInfo += 'CALIBRATION TIME 寮�濮嬫椂闂村ぇ浜庣粨鏉熸椂闂�;-';
+				dateJudge = false;
+			}*/
+		}
+		//FQC time 鐢盕QC end 涓嶧QC start璁$畻
+		if (swo.FQC_START__c!=null && swo.FQC_end__c!=null) {
+			//swo.FQC_TIME__c = swo.FQC_end__c - swo.FQC_START__c;
+			swo.FQC_TIME__c = getTimeLongStr(swo.FQC_START__c,swo.FQC_end__c);
+			/*if(swo.FQC_START__c < swo.FQC_end__c){
+				swo.FQC_TIME__c = getTimeLongStr(swo.FQC_START__c,swo.FQC_end__c);
+			}else{
+				errorMessageInfo += 'FQC TIME 寮�濮嬫椂闂村ぇ浜庣粨鏉熸椂闂�;-';
+				dateJudge = false;
+			}*/
+		}
+		/*if(!dateJudge){
+			return null;
+		}*/
+		//
+		if(swo.Repair_DateTime__c!=null && swo.DELIVERED_TO_SERVICE__c!=null){
+			swo.TIME_IN_QUEUE__c = getTimeLongStr(swo.Repair_DateTime__c,swo.DELIVERED_TO_SERVICE__c);
+		}
+		
+		if(swo.SWO_STATUS__c != SwoStatus){
+			// if (swo.SWO_STATUS__c == 'Closed') {
+			// 	SWOSTATUS_Closed_AddAttachment();//SWOSTATUS_Closed_AddAttachment
+			// }
+		}
+		if (swoid == null) {
+			swo.CASE_NUMBER__c = caseId;
+			insert swo;
+			swoid = swo.id;
+			//ASSIGNED TO 瀛楁鍙樻洿锛岀粰鍙樻洿鍚庣殑鐢ㄦ埛鍙戦偖浠�
+			/*if(swo.ASSIGNEDTO__c!=null && swo.ASSIGNEDTO__c!=assignedUser){
+				assignedUser = swo.ASSIGNEDTO__c;
+				sendEmail(swo.ASSIGNEDTO__c);
+			}*/
+			// PageReference ref = new Pagereference('/apex/SWOPageRead?id=' + swo.Id +'&type='+type);
+			// ref.setRedirect(true);
+			// return ref;
+		} else {
+			//ASSIGNED TO 瀛楁鍙樻洿锛岀粰鍙樻洿鍚庣殑鐢ㄦ埛鍙戦偖浠�
+			/*if(swo.ASSIGNEDTO__c!=null && swo.ASSIGNEDTO__c!=assignedUser){
+				assignedUser = swo.ASSIGNEDTO__c;
+				sendEmail(swo.ASSIGNEDTO__c);
+			}*/
+			//LATE REASON 娣诲姞閫昏緫锛氬綋INSTRUMENT SHIP DATE 鏅氫簬ESTIMATED PROMISE DATE鏃讹紝姝ら」蹇呭~銆�
+			update swo;
+		}
+
+		if (String.isNotBlank(swo.CASE_NUMBER__c) && (swo.SWO_STATUS__c == 'Close cancel' || swo.SWO_STATUS__c == 'Closed' || swo.SWO_STATUS__c == 'Close Denied')) {
+			
+
+			User_FaultInfo__c updateUserFaultInfo = new User_FaultInfo__c();
+			updateUserFaultInfo.Id = swo.CASE_NUMBER__c;
+			updateUserFaultInfo.STATUS__c = 'Closed';
+
+			update updateUserFaultInfo;
+
+		}
+
+		List<Diagnosis_Part__c> deleteList = new List<Diagnosis_Part__c>();
+		// List<Diagnosis_Part__c> insertList = new List<Diagnosis_Part__c>();
+		// deleteList = [select Id from Diagnosis_Part__c where SWO__c = :swoid];
+		// if(deleteList.size() > 0) delete deleteList;
+		// if(diagnosisList != null && diagnosisList.size() > 0){
+		// 	for(diagnosisInfo dia : diagnosisList){
+		// 		Diagnosis_Part__c dipa = dia.di.clone();
+		// 		if(dipa.ITEM__c != null && dipa.Product__c != null){
+		// 			if(dipa.SWO__c == null){
+		// 				dipa.SWO__c = swoid;
+		// 			}
+		// 			dipa.id = null;
+		// 			insertList.add(dipa);
+		// 		}
+		// 	}
+		// }
+		// if(insertList.size() > 0 ) insert insertList;
+
+		PageReference ref = new Pagereference('/apex/SWOPageRead?id=' + swo.Id +'&type='+type);
+			ref.setRedirect(true);
+			return ref;
+	}
+	/**
+	*鏁版嵁楠岃瘉
+	**/
+	public Boolean mustData(){
+		errorMessageInfo = '';
+		Boolean temp = true;
+		if(swo.OFFICE__c == null){
+			System.debug('swo.OFFICE__c:'+swo.OFFICE__c);
+			swo.OFFICE__c.addError(errorMessageInfo('OFFICE'));
+			//errorMessageInfo += 'OFFICE,';
+			temp = false;
+		}
+		if(swo.SWO_PRIORITY__c == null){
+			swo.SWO_PRIORITY__c.addError(errorMessageInfo('SWO PRIORITY'));
+			temp = false;
+		}
+		if(swo.SWO_STATUS__c == null){
+			swo.SWO_STATUS__c.addError(errorMessageInfo('SWO STATUS'));
+			//errorMessageInfo += 'SWO STATUS,';
+			temp = false;
+		}
+		/*if(swo.SWO_STAGE__c == null){
+			//errorMessageInfo += 'SWO STAGE,';
+			swo.SWO_STAGE__c.addError(errorMessageInfo('SWO STAGE'));
+			temp = false;
+		}*/
+		if(swo.TYPE__c == null){
+			//errorMessageInfo += 'TYPE,';
+			swo.TYPE__c.addError(errorMessageInfo('TYPE'));
+			temp = false;
+		}
+		if(swo.ASSIGNEDTO__c == null){
+			//errorMessageInfo += 'ASSIGNED TO,';
+			swo.ASSIGNEDTO__c.addError(errorMessageInfo('ASSIGNED TO'));
+			temp = false;
+		}
+		if(swo.DEPARTMENT__c == null){
+			//errorMessageInfo += 'DEPARTMENT,';
+			swo.DEPARTMENT__c.addError(errorMessageInfo('DEPARTMENT'));
+			temp = false;
+		}
+		if(swo.REASON__c == null){
+			//errorMessageInfo += 'REASON,';
+			swo.REASON__c.addError(errorMessageInfo('REASON'));
+			temp = false;
+		}
+		if(swo.PRODUCT_TYPE__c == null){
+			//errorMessageInfo += 'PRODUCT TYPE';
+			swo.PRODUCT_TYPE__c.addError(errorMessageInfo('PRODUCT TYPE'));
+			temp = false;
+		}
+		if(swo.ITEM__c == null){
+			//errorMessageInfo += 'ITEM,';
+			swo.ITEM__c.addError(errorMessageInfo('ITEM'));
+			temp = false;
+		}
+		if(swo.QUANTITY__c == null){
+			//errorMessageInfo += 'QUANTITY,';
+			swo.QUANTITY__c.addError(errorMessageInfo('QUANTITY'));
+			temp = false;
+		}
+		/*if (swo.ESTIMATED_MATERIAL_COST__c == null) {
+			swo.ESTIMATED_MATERIAL_COST__c.addError(errorMessageInfo('ESTIMATED MATERIAL (COST)'));
+			temp = false;
+		}*/
+		/*if (swo.ESTIMATED_LABOUR_HOURS__c == null) {
+			swo.ESTIMATED_LABOUR_HOURS__c.addError(errorMessageInfo('ESTIMATED LABOUR (HOURS)'));
+			temp = false;
+		}*/
+		/*if (swo.ESTIMATED_EXPENSES_COSTS__c == null) {
+			swo.ESTIMATED_EXPENSES_COSTS__c.addError(errorMessageInfo('ESTIMATED EXPENSES (COSTS)'));
+			temp = false;
+		}*/
+ 		if ((swo.INSTRUMENT_SHIP_DATE__c > swo.ESTIMATED_PROMISE_DATE__c) && swo.LATE_REASON__c == null) {
+			//errorMessageInfo = 'INSTRUMENT SHIP DATE 鏃堕棿鏅氫簬 ESTIMATED PROMISE DATE 鏃堕棿 LATE REASON 蹇呭~銆�';
+			//errorMessageInfo += 'INSTRUMENT SHIP DATE 鏃堕棿鏅氫簬 ESTIMATED PROMISE DATE 鏃堕棿 LATE REASON 蹇呭~銆�';
+			swo.LATE_REASON__c.addError(errorMessageInfo('LATE REASON'));
+ 		}
+		if(!temp){
+			return temp;
+		}
+
+		if(swo.REPEAT_REPAIR__c && swo.REPEAT_REPAIR_ORIGINAL_NOTES__c == null){
+			//errorMessageInfo += 'REPEAT REPAIR Check REPEAT REPAIR ORIGINAL NOTES 鏂囨湰妗嗗繀濉�';
+			//System.debug('errorMessageInfo:'+errorMessageInfo);
+			swo.REPEAT_REPAIR_ORIGINAL_NOTES__c.addError(errorMessageInfo('REPEAT REPAIR Check REPEAT REPAIR ORIGINAL NOTES'));
+			return false;
+		}
+
+		if(swo.INSTRUMENT_RECEIVE_DATE__c == null && swo.ASSIGNED_TO_TECHNICIAN_DATE__c !=null){
+			//errorMessageInfo += 'ASSIGNED TO TECHNICIAN DATE 鏈夊�� INSTRUMENT RECEIVE DATE 涓嶅彲涓虹┖锛�';
+			swo.INSTRUMENT_RECEIVE_DATE__c.addError(errorMessageInfo('ASSIGNED TO TECHNICIAN DATE has a value INSTRUMENT RECEIVE DATE'));
+			temp = false;
+		}else if((swo.INSTRUMENT_RECEIVE_DATE__c != null && swo.ASSIGNED_TO_TECHNICIAN_DATE__c !=null) && (swo.INSTRUMENT_RECEIVE_DATE__c.getTime() > swo.ASSIGNED_TO_TECHNICIAN_DATE__c.getTime())){
+			//errorMessageInfo += 'INSTRUMENT RECEIVE DATE 涓嶅彲浠ュぇ浜� ASSIGNED TO TECHNICIAN DATE锛�';
+			swo.INSTRUMENT_RECEIVE_DATE__c.addError('INSTRUMENT RECEIVE DATE cannot be greater than ASSIGNED TO TECHNICIAN DATE');
+			temp = false;
+		}
+		if((swo.ASSIGNED_TO_TECHNICIAN_DATE__c!=null && swo.TECHNICIAN_COMPLETION_DATE__c!=null)&&(swo.ASSIGNED_TO_TECHNICIAN_DATE__c.getTime() > swo.TECHNICIAN_COMPLETION_DATE__c.getTime())){
+			//errorMessageInfo += 'ASSIGNED TO TECHNICIAN DATE 涓嶅彲浠ュぇ浜� TECHNICIAN COMPLETION DATE锛�';
+			swo.ASSIGNED_TO_TECHNICIAN_DATE__c.addError('ASSIGNED TO TECHNICIAN DATE cannot be greater than TECHNICIAN COMPLETION DATE');
+			temp = false;
+		}
+		if(!temp){
+			return temp;
+		}
+
+		if(swo.SWO_STATUS__c == 'Ready to Ship' && swo.PO_RECEIVE_DATE__c == null){
+			//errorMessageInfo = '璇疯緭鍏� PO Receive Date';
+			swo.PO_RECEIVE_DATE__c.addError(errorMessageInfo('PO Receive Date'));
+			return false;
+		}
+
+		if(swo.SWO_STATUS__c == 'Closed'){
+			if(swo.INSTRUMENT_RECEIVE_DATE__c == null){
+				//errorMessageInfo += 'INSTRUMENT RECEIVE DATE,'; 
+				swo.INSTRUMENT_RECEIVE_DATE__c.addError(errorMessageInfo('INSTRUMENT RECEIVE DATE'));
+				temp = false;
+			}
+			if(swo.INSTRUMENT_SHIP_DATE__c == null){
+				//errorMessageInfo += 'INSTRUMENT SHIP DATE,'; 
+				swo.INSTRUMENT_SHIP_DATE__c.addError(errorMessageInfo('INSTRUMENT SHIP DATE'));
+				temp = false;
+			}
+			if(swo.ASSIGNED_TO_TECHNICIAN_DATE__c == null){
+				//errorMessageInfo += 'ASSIGNED TO TECHNICIAN DATE,'; 
+				swo.ASSIGNED_TO_TECHNICIAN_DATE__c.addError(errorMessageInfo('ASSIGNED TO TECHNICIAN DATE'));
+				temp = false;
+			}
+			if(swo.TECHNICIAN_COMPLETION_DATE__c == null){
+				//errorMessageInfo += 'TECHNICIAN COMPLETION DATE,'; 
+				swo.TECHNICIAN_COMPLETION_DATE__c.addError(errorMessageInfo('TECHNICIAN COMPLETION DATE'));
+				temp = false;
+			}
+			if(swo.UNIT_POWERS_UP__c == null){
+				//errorMessageInfo += 'UNIT POWERS UP?,'; 
+				swo.UNIT_POWERS_UP__c.addError(errorMessageInfo('UNIT POWERS UP?'));
+				temp = false;
+			}
+			if(swo.BATTERY_MORE_THAN_3_YRS_OLD__c == null){
+				//errorMessageInfo += 'BATTERY MORE THAN 3-YRS OLD?,'; 
+				swo.BATTERY_MORE_THAN_3_YRS_OLD__c.addError(errorMessageInfo('BATTERY MORE THAN 3-YRS OLD?'));
+				temp = false;
+			}
+			if(swo.CONFIRMED_RECEIPT_WITH_CUSTOMER__c == null){
+				//errorMessageInfo += 'CONFIRMED RECEIPT WITH CUSTOMER?,'; 
+				swo.CONFIRMED_RECEIPT_WITH_CUSTOMER__c.addError(errorMessageInfo('CONFIRMED RECEIPT WITH CUSTOMER?'));
+				temp = false;
+			}
+			if(swo.INCOMING_INSPECTION_COMPLETED_BY__c == null){
+				//errorMessageInfo += 'INCOMING INSPECTION COMPLETED BY:,'; 
+				swo.INCOMING_INSPECTION_COMPLETED_BY__c.addError(errorMessageInfo('INCOMING INSPECTION COMPLETED BY:'));
+				temp = false;
+			}
+			if(swo.CUSTOM_SETUPS_PRESENT__c == null){
+				//errorMessageInfo += 'CUSTOM SETUPS PRESENT?,'; 
+				swo.CUSTOM_SETUPS_PRESENT__c.addError(errorMessageInfo('CUSTOM SETUPS PRESENT?'));
+				temp = false;
+			}
+			if(swo.CUSTOM_SETUPS_INCLUDED__c == null){
+				//errorMessageInfo += 'CUSTOM SETUPS INCLUDED?,'; 
+				swo.CUSTOM_SETUPS_INCLUDED__c.addError(errorMessageInfo('CUSTOM SETUPS INCLUDED?'));
+				temp = false;
+			}
+			if(swo.KEYPAD_FUNCTIONS_CORRECTLY__c == null){
+				//errorMessageInfo += 'KEYPAD FUNCTIONS CORRECTLY?,'; 
+				swo.KEYPAD_FUNCTIONS_CORRECTLY__c.addError(errorMessageInfo('KEYPAD FUNCTIONS CORRECTLY?'));
+				temp = false;
+			}
+			if(swo.OUTGOING_INSPECTION_COMPLETED_BY__c == null){
+				//errorMessageInfo += 'OUTGOING INSPECTION COMPLETED BY:,'; 
+				swo.OUTGOING_INSPECTION_COMPLETED_BY__c.addError(errorMessageInfo('OUTGOING INSPECTION COMPLETED BY:'));
+				temp = false;
+			}
+			if(swo.SERIAL_MATCHES_SO__c == null){
+				//errorMessageInfo += 'SERIAL# MATCHES SO?,'; 
+				swo.SERIAL_MATCHES_SO__c.addError(errorMessageInfo('SERIAL# MATCHES SO?'));
+				temp = false;
+			}
+			if(swo.FACTORY_WARRANTY__c == false && swo.SO_NUMBER__c == null && swo.OAI_WARRANTY__c == false){
+				//errorMessageInfo += 'SO NUMBER,';
+				swo.SO_NUMBER__c.addError(errorMessageInfo('SO NUMBER'));
+				temp = false;
+			}
+		}
+		return temp;
+	}
+	//鎷兼帴閿欒淇℃伅
+	public String errorMessageInfo(String type) {
+        String result = type + ' can not be empty';
+        return result;
+    }
+	/**
+	 * 涓婁紶闄勪欢
+	 * @return [description]
+	 */
+	public PageReference uploadFile() {
+
+		PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + swoid + '&retURL=%2Fapex/SWOPage?id=' + swoid);
+		ref.setRedirect(true);
+		return ref;
+	}
+
+	public Pagereference edit(){
+		PageReference ref = new Pagereference('/apex/SWOPage?id=' + swo.Id +'&type='+type);
+		ref.setRedirect(true);
+		return ref;
+	}
+
+	public void addDiagnosisInfo(){
+		if(diagnosisList == null){
+			diagnosisList = new List<diagnosisInfo>();
+		}
+		diagnosisList.add(new diagnosisInfo(lineCount));
+		lineCount++;
+	}
+
+	/**
+	 * 鍒囨崲椤甸潰鏂规硶銆�
+	 */
+	public void setMail() {
+		type = 'mail';
+	}
+	public void setFault() {
+		type = 'Fault';
+	}
+	public void setCase() {
+		type = 'Case';
+	}
+	public void setProduct() {
+		type = 'Product';
+	}
+
+	public void setQuotes() {
+		type = 'Quotes';
+	}
+
+	public void setRepair() {
+		type = 'Repair';
+	}
+
+	public void setTracking() {
+		type = 'Tracking';
+	}
+	public void setTechnical() {
+		type = 'Technical';
+	}
+
+	public void setEstimation() {
+		type = 'Estimation';
+	}
+
+	public void setGeneral() {
+		type = 'General';
+	}
+
+	public void setIncoming() {
+		type = 'Incoming';
+	}
+
+	public void setOutgoing() {
+		type = 'Outgoing';
+	}
+
+	public void setDiagnosis() {
+		type = 'Diagnosis';
+	}
+
+	/**
+	 * 閭欢鏁版嵁缁撴瀯
+	 */
+	public class EmailInfo {
+
+		public Mail_Merge__c mm {get; set; }
+		public List<Attachment> attList {get; set; }
+		public String haveAtt {get; set;}
+		public EmailInfo() {
+
+		}
+		public EmailInfo(Mail_Merge__c mm_in, List<Attachment> attList_in) {
+			mm = mm_in;
+			if (attList_in == null || attList_in.size() == 0) {
+				haveAtt = 'No';
+				attList = new List<Attachment>();
+			} else {
+				attList = attList_in;
+				haveAtt = 'Yes';
+			}
+		}
+
+	}
+
+	public class diagnosisInfo{
+		public Diagnosis_Part__c di{get; set;}
+		public Integer lineNumber {get; set;}
+
+		public diagnosisInfo(Integer line){
+			di = new Diagnosis_Part__c();
+			lineNumber = line;
+		}
+		public diagnosisInfo(Diagnosis_Part__c in_di,Integer line){
+			di = in_di;
+			lineNumber = line;
+		}
+	}
+
+	//鍙戦�侀偖浠�
+	public void sendEmail(String id){
+
+		if(String.isBlank(id)){
+			return;
+		}
+		User user = [select Name,Email from User where id=:id];
+		if(user!=null && String.isNotBlank(user.Email)){
+			String subject = 'Service Work Order ~SWO:'+swo.Name;
+			String message = 'SWO status Changed to: '+ swo.SWO_STATUS__c+', Please continue to proceed this SWO.'+'\r';
+			message += (baseUrl+'/'+swo.Id);
+			List<String> ccAddresses = new List<String>();
+			List<String> toAddresses = new List<String>();
+			Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
+			toAddresses.add(user.Email);
+	        sendMail.setToAddresses(toAddresses);
+	        sendMail.setSubject(subject);
+	        sendMail.setPlainTextBody(message);
+	        sendMail.setBccSender(false);
+	        sendMail.setUseSignature(false);
+	        // ccAddresses.add('swo_listen@z-23gt0jbtzuxf7uka2keyfl65gxjqimwuqbl07g9u0govga7hm6.0t-8aptuaq.cs112.apex.sandbox.salesforce.com');
+	        ccAddresses.add(System.label.EmailComeBackListen);
+	        ccAddresses.add('dai_Prectech@olympus.com.cn');
+	        sendMail.setCcAddresses(ccAddresses);
+			Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
+		}
+
+	}
+	//repair parts 椤甸潰杩斿洖璋冪敤
+	public void repairReturn(){
+		if(String.isNotBlank(repairId)){
+			/*RepairPart__c repairPart = new RepairPart__c();
+			Schema.DescribeSobjectResult repairPart = RepairPart__c.sObjectType.getDescribe();
+			Map<String, Schema.SObjectField> repairPart_fields = d_swo.fields.getMap();
+			String soql_repair = 'select ';
+			String fields = '';
+			for (String field : repairPart_fields.keySet()) {
+				if (fields.length() > 0) {
+					fields += ', ';
+				}
+				fields += field;
+			}
+			soql_repair += fields;
+			soql_repair += ' from RepairPart__c where SWO_ID__c = \'' + repairId + '\'';
+			rpList = Database.query(soql_repair);*/
+			System.debug('鏂板缓RepairPart 杩斿洖');
+			rpList = new List<RepairPart__c>();
+			rpList = [select Id, Name, Product__c, DescriptionNew__c, PART_NUMBERNew__c, INST_SERIAL__c, QUANTITY__c, DEFECT_PART_NUMBER__c, DEFECT_SERIAL_NUMBER__c, ANI_DEFECT_CATEGORY__c, HOURS__c, LOCATION__c, BILL_AT_0_VALUE__c, ECN__c, QTY_PICKED__c from RepairPart__c where SWO_ID__c = :swoid order by Id];
+			return;
+		}
+	}
+
+	// 璁$畻涓や釜dateTime涔嬮棿鐨勬椂闂撮棿闅� 杩斿洖涓哄嚑澶╁嚑灏忔椂鍑犲垎閽熺殑瀛楃涓�
+	public String getTimeLongStr(Datetime startTime,Datetime endTime){
+		if(startTime>endTime){
+			Datetime a = startTime;
+			startTime = endTime;
+			endTime = a;
+		}
+		String str = '';
+		Decimal timeLong = Decimal.valueOf(endTime.getTime()) - Decimal.valueOf(startTime.getTime());
+		Decimal day = 0;
+		Decimal hour = 0;
+		Decimal second = timeLong/1000;
+		//math.round() 鍥涜垗浜斿叆
+		//math.floor() 鍙栧埌涓�涓皬鏁扮殑鏁存暟閮ㄥ垎
+		Decimal minute = math.round(second/60);
+		if(minute >= 60){
+			hour = minute/60;
+			if(hour >= 24){
+				day = hour/24;
+				hour = (day-math.floor(day))*24;
+				minute = (hour - math.floor(hour))*60;
+				minute = math.round(minute);
+				hour = math.floor(hour);
+				day = math.floor(day);
+				str = day+' Day '+hour+' Hour '+minute+' Minute';
+			}else{
+				minute = (hour-math.floor(hour))*60;
+				minute =  math.round(minute);
+				hour = math.floor(hour);
+				str = hour+' Hour '+math.round(minute)+' Minute';
+			}
+		}else{
+			str = minute+' Minute';
+		}
+		System.debug(str);
+		return str;
+	}
+	//鎵撳紑瀛愰〉闈㈠厛淇濆瓨锛岄槻姝㈣繑鍥濻WO椤甸潰鏃舵暟鎹鍒锋柊
+	public void openPageSave(){
+		upsert swo;
+		return;
+	}
+	// SWO鐨勭姸鎬佸彉鎴怌losed鏃讹紝鍒涘缓csv骞舵坊鍔犲埌闄勪欢涓�
+	/*public void SWOSTATUS_Closed_AddAttachment() {
+		String repairParts = '';
+		if ( rpList.size() > 0) {
+			for(RepairPart__c repairPart:rpList){
+
+				if (String.isBlank(repairParts)) {
+					repairParts = repairPart.Product__r.ProductCode;
+				} else {
+					repairParts += '/' + repairPart.Product__r.ProductCode;
+				}
+			}
+		}
+		repairParts = String.isBlank(repairParts)  ? '\"\"':repairParts.replaceAll('"', '');
+		String claim = String.isBlank(swo.CLAIM__c)  ? '\"\"':swo.CLAIM__c.replaceAll('"', '');
+        String serial = String.isBlank(swo.SERIAL__c)  ? '\"\"':swo.SERIAL__c.replaceAll('"', '');
+        String description = String.isBlank(swo.DESCRIPTION_F__c)?'': swo.DESCRIPTION_F__c.replaceAll('"', '');
+        String strblob = '"swo name","factory warranty","product type","claim#","DESCRIPTION","serial #","repair parts","ESTIMATED LABOUR (HOURS)"\n';
+        
+        strblob += swo.name +',' + swo.FACTORY_WARRANTY__c + ','+swo.PRODUCT_TYPE__c +','+claim+','+description+','+serial+ ','+repairParts+','+swo.ESTIMATED_LABOUR_HOURS__c;
+
+        Attachment tmpAttachment = new Attachment();
+        tmpAttachment.Name = swo.name +'鍑哄簱鍗�.csv';
+        tmpAttachment.Body = Blob.valueOf(strblob);
+        tmpAttachment.ParentId = swo.Id;
+        insert tmpAttachment;
+        
+    }
+    */
+}
\ No newline at end of file
diff --git a/scr/classes/SWOController.cls-meta.xml b/scr/classes/SWOController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOControllerTest.cls b/scr/classes/SWOControllerTest.cls
new file mode 100644
index 0000000..53a5778
--- /dev/null
+++ b/scr/classes/SWOControllerTest.cls
@@ -0,0 +1,349 @@
+@isTest
+private class SWOControllerTest {
+    
+
+    public static User UserD(){
+        User user2 = new User();
+        user2.LastName = 'test2';
+        user2.FirstName = 'test2';
+        user2.Alias = 'test2';
+        user2.Email = 'test2@test.com';
+        user2.Username = 'Xin_Prectech@olympus.com.cn';
+        user2.CommunityNickname = 'test2';
+        user2.IsActive = true;
+        user2.EmailEncodingKey = 'ISO-2022-JP';
+        user2.TimeZoneSidKey = 'Asia/Tokyo';
+        user2.LocaleSidKey = 'ja_JP';
+        user2.LanguageLocaleKey = 'ja';
+        user2.ProfileId = '00e28000001sZE6';//System.Label.SystemAdmin;
+        insert user2;
+
+        return user2;
+    }    
+
+    static testMethod void testMethod1() {
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert product1;
+
+        User_FaultInfo__c uf = new User_FaultInfo__c();
+        // uf.Name = 'Test';
+        insert uf;
+
+        // User user = new User();
+        // user.LastName = 'test3';
+        // user.FirstName = 'test3';
+        // user.Alias = 'test3';
+        // user.Email = 'test3@test.com';
+        // user.Username = 'test111@test222.com';
+        // user.CommunityNickname = 'test3';
+        // user.IsActive = true;
+        // user.EmailEncodingKey = 'ISO-2022-JP';
+        // user.TimeZoneSidKey = 'Asia/Tokyo';
+        // user.LocaleSidKey = 'ja_JP';
+        // user.LanguageLocaleKey = 'ja';
+        // user.ProfileId = '00e28000001sZE6';//System.Label.SystemAdmin;
+        // insert user;
+
+        // User_FaultInfo__c uf = new User_FaultInfo__c();
+        // uf.Name = 'Test';
+        // insert uf;
+
+        PageReference page = new PageReference('apex/SWOPage?caseId='+uf.Id);
+        System.Test.setCurrentPage(page);
+        SWOController controller = new SWOController();
+        controller.init();
+        // controller.swo.REPEAT_REPAIR__c = true;
+        controller.swo.QUANTITY__c = 22;
+        controller.swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        controller.swo.LABOUR_RATE__c = 22;
+        controller.swo.OFFICE__c = 'Beijing';
+        controller.swo.SWO_PRIORITY__c = 'Medium';
+        controller.swo.SWO_STATUS__c = 'Closed';
+        controller.swo.TYPE__c = 'Service';
+        controller.swo.ASSIGNEDTO__c = UserD().Id;
+        controller.swo.DEPARTMENT__c = 'Field Service';
+        controller.swo.REASON__c = 'Replacement';
+        controller.swo.PRODUCT_TYPE__c = 'NDT';
+        controller.swo.ITEM__c = product1.Id;
+        // controller.swo.INSTRUMENT_RECEIVE_DATE__c = Datetime.now();
+        // controller.swo.ASSIGNED_TO_TECHNICIAN_DATE__c = Datetime.now().addDays(-1);
+        // TECHNICIAN_COMPLETION_DATE__c = 
+        // Datetime.
+        controller.save();
+
+
+
+    }
+
+    static testMethod void updateTest() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert product1;
+
+        User_FaultInfo__c uf = new User_FaultInfo__c();
+        // uf.Name = 'Test';
+        insert uf;
+
+         List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        Contact core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        User testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = '00e28000001sZE6',TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+
+        User user2 = UserD();//new User();
+        // user2.LastName = 'test2';
+        // user2.FirstName = 'test2';
+        // user2.Alias = 'test2';
+        // user2.Email = 'test2@test.com';
+        // user2.Username = 'Xin_Prectech@olympus.com.cn';
+        // user2.CommunityNickname = 'test2';
+        // user2.IsActive = true;
+        // user2.EmailEncodingKey = 'ISO-2022-JP';
+        // user2.TimeZoneSidKey = 'Asia/Tokyo';
+        // user2.LocaleSidKey = 'ja_JP';
+        // user2.LanguageLocaleKey = 'ja';
+        // user2.ProfileId = '00e28000001sZE6';//System.Label.SystemAdmin;
+        // insert user2;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        swo.OFFICE__c = 'Beijing';
+        swo.SWO_PRIORITY__c = 'Medium';
+        swo.SWO_STATUS__c = 'Close Denied';
+        swo.TYPE__c = 'Service';
+        swo.ASSIGNEDTO__c = user2.Id;
+        swo.DEPARTMENT__c = 'Field Service';
+        swo.REASON__c = 'Replacement';
+        swo.PRODUCT_TYPE__c = 'NDT';
+        swo.ITEM__c = product1.Id;
+        swo.INSTRUMENT_RECEIVE_DATE__c = Datetime.now();
+        swo.INSTRUMENT_SHIP_DATE__c = Datetime.now().addDays(1);
+        swo.DIAGNOSIS_START__c = Datetime.now();
+        swo.DIAGNOSIS_END__c = Datetime.now().addDays(1);
+        swo.PO_RECEIVE_DATE__c = Datetime.now();
+        swo.Quotation_send__c = Datetime.now().addDays(1);
+        swo.REPAIR_START__c = Datetime.now();
+        swo.REPAIR_END__c = Datetime.now().addDays(1);
+
+        swo.CALIBRATION_START__c = Datetime.now();
+        swo.CALIBRATION_END__c = Datetime.now().addDays(1);
+
+        swo.FQC_START__c = Datetime.now();
+        swo.FQC_end__c = Datetime.now().addDays(1);
+
+        swo.Repair_DateTime__c = Datetime.now();
+        swo.DELIVERED_TO_SERVICE__c = Datetime.now().addDays(1);
+        swo.CASE_NUMBER__c = uf.Id;
+
+        // swo.REPAIR_START__c = Datetime.now();
+        // swo.REPAIR_END__c = Datetime.now().addDays(1);
+
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        quotes.DATE__c = Date.today();
+        quotes.LEAD_TIME__c = '1 week';
+        quotes.STATUS__c = 'Qualifying';
+        quotes.LOCATION__c = 'China - Service';
+        quotes.TERMS__c = '1% 10 Net 30';
+        quotes.EXPIRES__c = Date.today();
+        quotes.EXP_CLOSE__c = Date.today();
+        quotes.ORDER_TYPE__c = 'LS Core Clinical';
+
+        insert quotes;
+
+        Diagnosis_Part__c diagnosisPart = new Diagnosis_Part__c();
+        diagnosisPart.SWO__c = swo.Id;
+        insert diagnosisPart;
+
+        Mail_Merge__c  mailMerge = new Mail_Merge__c(); 
+        mailMerge.SWO__c = swo.Id;
+        insert mailMerge;
+        Attachment att = new Attachment(
+            Name = 'ORDER-123456.pdf',
+            parentId = mailMerge.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+
+        PageReference page = new PageReference('apex/SWOPage?id='+swo.Id +'&type=Product');
+        System.Test.setCurrentPage(page);
+        SWOController controller = new SWOController(new ApexPages.StandardController(swo));
+        controller.init();
+        controller.save();
+        controller.sendEmail(swo.ASSIGNEDTO__c);
+
+        controller.init();
+        // Integer num = Integer.valueOf('Test--->'+controller.SwoStatus);
+        // controller.SwoStatus = '1111';
+        controller.swo.SWO_STATUS__c = 'Quotation for approval';
+        controller.swo.ASSIGNEDTO__c = user2.Id;
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Quotation approved';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Ready for Quote';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Parts Hold';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Delivered to Technician';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Ready to Quote';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Ready for Sales order';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'Repair';
+        controller.save();
+
+        controller.init();
+        swo.SWO_STATUS__c = 'In Queue';
+        controller.save();
+
+
+        controller.setMail();
+        controller.setFault();
+        controller.setCase();
+        controller.setProduct();
+        controller.setQuotes();
+        controller.setRepair();
+        controller.setTracking();
+        controller.setTechnical();
+        controller.setEstimation();
+        controller.setGeneral();
+        controller.setIncoming();
+        controller.setOutgoing();
+        controller.setDiagnosis();
+
+        controller.uploadFile();
+        controller.edit();
+        controller.addDiagnosisInfo();
+        controller.openPageSave();
+        controller.repairReturn();
+
+    }
+
+    
+    static testMethod void testMethod3() {
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert product1;
+
+        User_FaultInfo__c uf = new User_FaultInfo__c();
+        // uf.Name = 'Test';
+        insert uf;
+
+        // User user = new User();
+        // user.LastName = 'test';
+        // user.FirstName = 'test';
+        // user.Alias = 'test';
+        // user.Email = 'test@test.com';
+        // user.Username = 'test111@test222.com';
+        // user.CommunityNickname = 'test';
+        // user.IsActive = true;
+        // user.EmailEncodingKey = 'ISO-2022-JP';
+        // user.TimeZoneSidKey = 'Asia/Tokyo';
+        // user.LocaleSidKey = 'ja_JP';
+        // user.LanguageLocaleKey = 'ja';
+        // user.ProfileId = '00e28000001sZE6';//System.Label.SystemAdmin;
+        // insert user;
+
+
+        PageReference page = new PageReference('apex/SWOPage?caseId='+uf.Id);
+        System.Test.setCurrentPage(page);
+        SWOController controller = new SWOController();
+        controller.init();
+
+        controller.save();
+
+
+
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SWOControllerTest.cls-meta.xml b/scr/classes/SWOControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOSearchProductContaroller.cls b/scr/classes/SWOSearchProductContaroller.cls
new file mode 100644
index 0000000..548d0eb
--- /dev/null
+++ b/scr/classes/SWOSearchProductContaroller.cls
@@ -0,0 +1,96 @@
+public with sharing class SWOSearchProductContaroller {
+    public Integer quoteEntryMaxSet {get; private set;}
+
+    public List<ProductInfo> productInfoList { get; set; }
+
+    public Integer ProductInfoListSize {get; set;}
+   
+    public String searchMode;                         // 妞滅储銉€兗銉�
+    public String lineNo {get;set;}                   // 瑕敾闈€伄閬告姙銇椼仧琛�
+    public String val {get;set;}
+    public String type {get;set;}                     //涓绘暟鎹被鍨�
+    public String SearchName {get;set;}               // 妞滅储鏂囧瓧鍒�
+    
+    public SWOSearchProductContaroller(ApexPages.StandardController controller){
+        this();
+    }
+
+    public SWOSearchProductContaroller() {
+        this.quoteEntryMaxSet = Integer.valueOf(System.Label.QuoteEntryMaxSet);
+        
+        this.lineNo = Apexpages.currentPage().getParameters().get('lineno');
+        this.val = Apexpages.currentPage().getParameters().get('val');
+        this.type = Apexpages.currentPage().getParameters().get('type');
+        if (String.isNotBlank(val)) {
+            SearchName = val;
+            val = null;
+        }
+        productInfoList = new  List<ProductInfo>();
+        ProductInfoListSize = 1;
+    }
+
+    public void init () {
+        system.debug('init==========> start');
+        system.debug('SearchName==========>' + SearchName);
+        if (SearchName != null && SearchName != '') {
+            serProduct();
+        }
+
+        system.debug('init==========> end');
+
+    }
+
+    public PageReference serProduct(){
+        productInfoList = new  List<ProductInfo>();
+        ProductInfoListSize = 1;
+        if (String.isNotBlank(SearchName)) {
+
+             String sql = 'Select Id,Name,ProductCode,Description,PART_NUMBER__c,ProductInventory__c,ProductReferencePrice__c,Product_ECCode__c from Product2 Where Id != null ';
+            String likename = String.escapeSingleQuotes(SearchName);
+            String prdcd = String.escapeSingleQuotes(SearchName);
+            String prdec = String.escapeSingleQuotes(SearchName);
+            if (likename.indexOf('*') >= 0) {
+                likename = likename.replace('*', '%');
+            } else {
+                likename = '%' + likename + '%';
+            }
+            if (prdcd.indexOf('*') >= 0) {
+                prdcd = prdcd.replace('*', '%');
+            } else {
+                prdcd = '%' + prdcd + '%';
+            }
+            if (prdec.indexOf('*') >= 0) {
+                prdec = prdcd.replace('*', '%');
+            } else {
+                prdec = '%' + prdec + '%';
+            }
+           
+            sql += ' and (Name Like ' + '\'' + likename + '\' or ProductCode Like ' + '\'' + prdcd + '\' or Product_ECCode__c like ' + '\'' + prdec + '\')';
+            sql += ' order by ProductCode,Name desc limit 200';
+            List<Product2> product2List = Database.query(sql);
+            if (product2List.size() > 0) {
+                for (Product2 product :product2List) {
+                    productInfoList.add(new ProductInfo(ProductInfoListSize,product));
+                    ProductInfoListSize++;
+                }
+            }
+            
+        }
+        return null;
+    }
+    public class ProductInfo {
+
+        public Product2 productPage {get; set;}//浜у搧
+        public String productId {get; set;} //浜у搧Id
+        public Integer lineNumber {get; set;}//琛屽彿
+        
+        public ProductInfo (Integer productNo){
+            lineNumber = productNo;
+        }
+        public ProductInfo ( Integer productNo,Product2 product) {
+            productPage = product;
+            lineNumber = productNo;
+            productId = product.Id;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SWOSearchProductContaroller.cls-meta.xml b/scr/classes/SWOSearchProductContaroller.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOSearchProductContaroller.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOSearchProductContarollerTest.cls b/scr/classes/SWOSearchProductContarollerTest.cls
new file mode 100644
index 0000000..50af6f3
--- /dev/null
+++ b/scr/classes/SWOSearchProductContarollerTest.cls
@@ -0,0 +1,34 @@
+@isTest
+private class SWOSearchProductContarollerTest {
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+
+        insert product1;
+
+        PageReference page = new PageReference('/apex/SWOSearchProduct?Type=Quotes&lineno=1&val=product1');
+        System.Test.setCurrentPage(page);
+        SWOSearchProductContaroller controller = new SWOSearchProductContaroller();
+        controller.init();    
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SWOSearchProductContarollerTest.cls-meta.xml b/scr/classes/SWOSearchProductContarollerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOSearchProductContarollerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOTriggerHandler.cls b/scr/classes/SWOTriggerHandler.cls
new file mode 100644
index 0000000..0d878f9
--- /dev/null
+++ b/scr/classes/SWOTriggerHandler.cls
@@ -0,0 +1,113 @@
+public without sharing class SWOTriggerHandler {
+    public static void setDateTimeSendEmail(List<SWO__C> newList, Map<Id, SWO__C> newMap, List<SWO__C> oldList, Map<Id, SWO__C> oldMap) {
+        for(SWO__C newSwo : newList){
+        	SWO__C oldSwo = (oldMap == null?null:oldMap.get(newSwo.Id));
+        	if(oldSwo == null || (oldSwo.SWO_STATUS__c != newSwo.SWO_STATUS__c)){
+        		if(newSwo.SWO_STATUS__c == 'Quotation for approval'){
+				newSwo.Quotation_for_Approval__c = Datetime.now();
+				}
+				//褰揝WO Status 鏀瑰彉涓篞uotation approved鏃�,姝ゆ椂闂寸偣鑷姩鎶撳彇骞跺~鍏呮澶�
+				if(newSwo.SWO_STATUS__c == 'Quotation approved'){
+					newSwo.Quotation_Approved__c = Datetime.now();
+				}
+				//璋蜂紵绁庢柊鍔犱笁涓椂闂存 start
+				//褰揝WO Status 鏀瑰彉涓篜arts request for diagnosis鏃�,姝ゆ椂闂寸偣鑷姩鎶撳彇骞跺~鍏呮澶�
+				if(newSwo.SWO_STATUS__c == 'Parts request for diagnosis'){
+					newSwo.Parts_request_for_diagnosis_date__c = Datetime.now();
+				}
+				//褰揝WO Status 鏀瑰彉涓篜arts ready for diagnosis鏃�,姝ゆ椂闂寸偣鑷姩鎶撳彇骞跺~鍏呮澶�
+				if(newSwo.SWO_STATUS__c == 'Parts ready for diagnosis'){
+					newSwo.Parts_ready_for_diagnosis_date__c = Datetime.now();
+				}
+				//褰揝WO Status 鏀瑰彉涓篟eady to ship鏃�,姝ゆ椂闂寸偣鑷姩鎶撳彇骞跺~鍏呮澶�
+				if(newSwo.SWO_STATUS__c == 'Ready to ship'){
+					newSwo.Ready_to_ship_date__c = Datetime.now();
+				}
+				//璋蜂紵绁庢柊鍔犱笁涓椂闂存 end
+				//宸ョ▼甯堟妸SWO鐘舵�佹敼涓篟eady for Quote 鏃讹紝鏁版嵁鑷姩濉厖璇ユ棩鏈熴��
+				if(newSwo.SWO_STATUS__c == 'Ready for Quote'){
+					newSwo.Ready_for_Quote__c = Datetime.now();
+				}
+				//宸ョ▼甯堟妸SWO鐘舵�佹敼涓篜arts Hold 鏃讹紝鏁版嵁鑷姩濉厖璇ユ棩鏈熴��
+				if(newSwo.SWO_STATUS__c == 'Parts Hold'){
+					newSwo.Part_Hold_Date__c = Datetime.now();
+				}
+				//Delivered to service鐢� SWO 鐘舵�佽缃负deliver to technician 鏃舵姄鍙栥��
+				if (newSwo.SWO_STATUS__c == 'Delivered to Technician') {
+					newSwo.DELIVERED_TO_SERVICE__c = Datetime.now();
+				}
+				//Ready to Quote鐢盨WO 鐘舵�佽缃负ready to quote鏃舵姄鍙�
+				if (newSwo.SWO_STATUS__c == 'Ready to Quote') {
+					newSwo.READY_TO_QUOTE__c = Datetime.now();
+				}
+				//Ready for Sales order鐢盨WO 鐘舵�佽缃负ready for sales order鏃舵姄鍙�
+				if (newSwo.SWO_STATUS__c == 'Ready for Sales order') {
+					newSwo.READY_FOR_SALES_ORDER__c = Datetime.now();
+				}
+				//repair SWO 鐘舵�佽缃负 repair 鏃舵姄鍙�
+				if(newSwo.SWO_STATUS__c == 'Repair'){
+					newSwo.Repair_DateTime__c = Datetime.now();
+					//鍝釜鎶�鏈汉鍛樻妸SWO鐘舵�佹洿鏀逛负Repair 鐘舵�侊紝鎶婅鎶�鏈汉鍛樼殑鍚嶅瓧濉叆璇ヤ綅缃�
+					newSwo.TECHNICIAN__c = UserInfo.getUserId();
+				}
+				//宸ョ▼甯堟妸SWO鐘舵�佹敼涓篒n Queue 鏃讹紝鏁版嵁鑷姩濉厖璇ユ棩鏈�
+				if(newSwo.SWO_STATUS__c == 'In Queue'){
+					newSwo.In_Queue_Date__c = Datetime.now();
+				}
+				//濡傛灉璇WO鏈夎璁剧疆涓� Close cancel鎴栬�卌lose denied鐨勭姸鎬�, 鎶婄姸鎬佸�� close cancel 鎴栬�卌lose denied 濉叆鍒拌浣嶇疆銆�
+				if (newSwo.SWO_STATUS__c == 'Close cancel') {
+					newSwo.Returned_Without_Repair_Flag__c = 'Close cancel';
+				}
+				//濡傛灉璇WO鏈夎璁剧疆涓� Close cancel鎴栬�卌lose denied鐨勭姸鎬�, 鎶婄姸鎬佸�� close cancel 鎴栬�卌lose denied 濉叆鍒拌浣嶇疆銆�
+				if (newSwo.SWO_STATUS__c == 'Close Denied') {
+					newSwo.Returned_Without_Repair_Flag__c = 'Close Denied';
+				}
+				//濡傛灉璇WO鏈夎璁剧疆涓� Ready for customer pick up鐨勭姸鎬�, 鎶婄姸鎬佸�糝eady for customer pick up 濉叆鍒拌浣嶇疆銆�
+				if (newSwo.SWO_STATUS__c == 'Ready for Customer pickup') {
+					newSwo.Specified_Delivery_Flag__c = 'Ready for Customer pickup';
+				}
+        	}
+        	if(oldSwo != null && (oldSwo.ASSIGNEDTO__c != newSwo.ASSIGNEDTO__c)){
+				doSendEmail(newSwo.ASSIGNEDTO__c,newSwo);
+        	}
+        }
+    }
+
+    public static void sendEmail(List<SWO__C> newList, Map<Id, SWO__C> newMap, List<SWO__C> oldList, Map<Id, SWO__C> oldMap) {
+    	for(SWO__C newSwo : newList){
+    		if(String.isNotBlank(newSwo.ASSIGNEDTO__c)){
+    			doSendEmail(newSwo.ASSIGNEDTO__c,newSwo);
+    		}
+    	}
+    }
+
+    //鍙戦�侀偖浠�
+	private static void doSendEmail(String id,SWO__c swo){
+		if(String.isBlank(id)){
+			return;
+		}
+		User user = [select Name,Email from User where id=:id];
+		if(user!=null && String.isNotBlank(user.Email)){
+			String subject = 'Service Work Order ~SWO:'+swo.Name;
+			String message = 'SWO status Changed to: '+ swo.SWO_STATUS__c+', Please continue to proceed this SWO.'+'\r';
+			//涓婄嚎姝e紡鐜鏃堕摼鎺ラ渶瑕佷慨鏀逛负姝e紡鐜閾炬帴
+			//message += ('https://ssbg--ssbgtest--c.visualforce.com/apex/SWOPageRead?id='+swo.Id);
+			//姝e紡鐜閾炬帴鍦板潃 https://ssbg--c.ap6.visual.force.com/apex/SWOPageRead?id=a0r0K00006aylRy&sfdc.override=1
+			message += ('https://ssbg--c.ap6.visual.force.com/apex/SWOPageRead?id='+swo.Id);
+			List<String> ccAddresses = new List<String>();
+			List<String> toAddresses = new List<String>();
+			Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
+			toAddresses.add(user.Email);
+	        sendMail.setToAddresses(toAddresses);
+	        sendMail.setSubject(subject);
+	        sendMail.setPlainTextBody(message);
+	        sendMail.setBccSender(false);
+	        sendMail.setUseSignature(false);
+	        // ccAddresses.add('swo_listen@z-23gt0jbtzuxf7uka2keyfl65gxjqimwuqbl07g9u0govga7hm6.0t-8aptuaq.cs112.apex.sandbox.salesforce.com');
+	        ccAddresses.add(System.label.EmailComeBackListen);
+	        ccAddresses.add('dai_Prectech@olympus.com.cn');
+	        sendMail.setCcAddresses(ccAddresses);
+			Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
+		}
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/SWOTriggerHandler.cls-meta.xml b/scr/classes/SWOTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOTriggerHandlerTest.cls b/scr/classes/SWOTriggerHandlerTest.cls
new file mode 100644
index 0000000..0b3818c
--- /dev/null
+++ b/scr/classes/SWOTriggerHandlerTest.cls
@@ -0,0 +1,133 @@
+@isTest
+private class SWOTriggerHandlerTest {
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectOpp = [select Id from RecordType where IsActive = true and SobjectType = 'Opportunity' and Name = 'SSBD'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            CurrencyIsoCode = 'CNY'
+        );
+        insert pricebook;
+        
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductCode = 'product1';
+        product1.ProductStatus__c = '1';
+        product1.NMPAStatus_one__c = 'Z1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        insert product1;
+
+        User_FaultInfo__c uf = new User_FaultInfo__c();
+        // uf.Name = 'Test';
+        insert uf;
+
+         List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        Contact core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        User testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = '00e28000001sZE6',TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+
+        User user2 = new User();
+        user2.LastName = 'test2';
+        user2.FirstName = 'test2';
+        user2.Alias = 'test2';
+        user2.Email = 'test2@test.com';
+        user2.Username = 'Xin_Prectech@olympus.com.cn';
+        user2.CommunityNickname = 'test2';
+        user2.IsActive = true;
+        user2.EmailEncodingKey = 'ISO-2022-JP';
+        user2.TimeZoneSidKey = 'Asia/Tokyo';
+        user2.LocaleSidKey = 'ja_JP';
+        user2.LanguageLocaleKey = 'ja';
+        user2.ProfileId = '00e28000001sZE6';//System.Label.SystemAdmin;
+        insert user2;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        swo.OFFICE__c = 'Beijing';
+        swo.SWO_PRIORITY__c = 'Medium';
+        swo.SWO_STATUS__c = 'Close Denied';
+        swo.TYPE__c = 'Service';
+        swo.ASSIGNEDTO__c = user2.Id;
+        swo.DEPARTMENT__c = 'Field Service';
+        swo.REASON__c = 'Replacement';
+        swo.PRODUCT_TYPE__c = 'NDT';
+        swo.ITEM__c = product1.Id;
+        swo.INSTRUMENT_RECEIVE_DATE__c = Datetime.now();
+        swo.INSTRUMENT_SHIP_DATE__c = Datetime.now().addDays(1);
+        swo.DIAGNOSIS_START__c = Datetime.now();
+        swo.DIAGNOSIS_END__c = Datetime.now().addDays(1);
+        swo.PO_RECEIVE_DATE__c = Datetime.now();
+        swo.Quotation_send__c = Datetime.now().addDays(1);
+        swo.REPAIR_START__c = Datetime.now();
+        swo.REPAIR_END__c = Datetime.now().addDays(1);
+
+        swo.CALIBRATION_START__c = Datetime.now();
+        swo.CALIBRATION_END__c = Datetime.now().addDays(1);
+
+        swo.FQC_START__c = Datetime.now();
+        swo.FQC_end__c = Datetime.now().addDays(1);
+
+        swo.Repair_DateTime__c = Datetime.now();
+        swo.DELIVERED_TO_SERVICE__c = Datetime.now().addDays(1);
+        swo.CASE_NUMBER__c = uf.Id;
+
+        insert swo;
+        swo.SWO_STATUS__c = 'Quotation approved';
+        update swo;
+        swo.SWO_STATUS__c = 'Quotation for approval';
+        update swo;
+        swo.SWO_STATUS__c = 'Parts Hold';
+        update swo;
+        swo.SWO_STATUS__c = 'Delivered to Technician';
+        update swo;
+        swo.SWO_STATUS__c = 'Ready to Quote';
+        update swo;
+        swo.SWO_STATUS__c = 'Ready for Sales order';
+        update swo;
+        swo.SWO_STATUS__c = 'Repair';
+        update swo;
+        swo.SWO_STATUS__c = 'In Queue';
+        update swo;
+        swo.SWO_STATUS__c = 'Close cancel';
+        update swo;
+        swo.SWO_STATUS__c = 'Close Denied';
+        update swo;
+        swo.SWO_STATUS__c = 'Parts request for diagnosis';
+        update swo;
+        swo.SWO_STATUS__c = 'Parts ready for diagnosis';
+        update swo;
+        swo.SWO_STATUS__c = 'Ready to ship';
+        update swo;
+        swo.SWO_STATUS__c = 'Ready for Customer pickup';
+        update swo;
+        User user3 = user2;
+        user3.Id = null;
+        user3.LastName = 'test3';
+        user3.FirstName = 'test3';
+        user3.Alias = 'test3';
+        user3.Email = 'test3@test.com';
+        user3.Username = 'Dai_Prectech@olympus.com.cn';
+        user3.CommunityNickname = 'test3';
+        insert user3;
+        swo.ASSIGNEDTO__c = user3.Id;
+        update swo;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SWOTriggerHandlerTest.cls-meta.xml b/scr/classes/SWOTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SWOUtil.cls b/scr/classes/SWOUtil.cls
new file mode 100644
index 0000000..01553da
--- /dev/null
+++ b/scr/classes/SWOUtil.cls
@@ -0,0 +1,3 @@
+public with sharing class SWOUtil {
+    
+}
\ No newline at end of file
diff --git a/scr/classes/SWOUtil.cls-meta.xml b/scr/classes/SWOUtil.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SWOUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/Sbg001Sync.cls b/scr/classes/Sbg001Sync.cls
new file mode 100644
index 0000000..c666f72
--- /dev/null
+++ b/scr/classes/Sbg001Sync.cls
@@ -0,0 +1,84 @@
+//Generated by wsdl2apex
+
+public class Sbg001Sync {
+    public class HTTPS_Port {
+        public String endpoint_x = 'https://pit0u.is.olympus.global:50001/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
+        public Map<String,String> inputHttpHeaders_x;
+        public Map<String,String> outputHttpHeaders_x;
+        public String clientCertName_x;
+        public String clientCert_x;
+        public String clientCertPasswd_x;
+        public Integer timeout_x;
+        private String[] ns_map_type_info = new String[]{'http://olympus.co.jp/gpi/SBG001', 'Sbg001Sync', 'http://olympus.co.jp/common/message', 'OlympusCoJpCommonMessage'};
+        public OlympusCoJpCommonMessage.LOG_element[] SBG001_Sync_BC2GPI(Sbg001Sync.SSBDCustomerContacts_element[] SSBDCustomerContacts) {
+            Sbg001Sync.SBG001 request_x = new Sbg001Sync.SBG001();
+            request_x.SSBDCustomerContacts = SSBDCustomerContacts;
+            OlympusCoJpCommonMessage.Response response_x;
+            Map<String, OlympusCoJpCommonMessage.Response> response_map_x = new Map<String, OlympusCoJpCommonMessage.Response>();
+            response_map_x.put('response_x', response_x);
+            WebServiceCallout.invoke(
+              this,
+              request_x,
+              response_map_x,
+              new String[]{endpoint_x,
+              'http://sap.com/xi/WebService/soap1.1',
+              'http://olympus.co.jp/gpi/SBG001',
+              'SBG001',
+              'http://olympus.co.jp/common/message',
+              'Response',
+              'OlympusCoJpCommonMessage.Response'}
+            );
+            response_x = response_map_x.get('response_x');
+            return response_x.LOG;
+        }
+    }
+
+    public class SSBDCustomerContact_element {
+        public String CustomerCode;
+        public String CustomerDescription;
+        public String CustomerDescription2Description3;
+        public String CustomerAreaCity;
+        public String TelephoneMobile;
+        public String FaxEmail;
+        public String PostalCode;
+        public String Address;
+        public String CustomerCategory;
+        public String Industry;
+        public String ContactOffice;
+        public String ContactCode;
+        public String ContactEffectiveDateFrom;
+        public String PurposeOfAdvice;
+        private String[] CustomerCode_type_info = new String[]{'CustomerCode','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] CustomerDescription_type_info = new String[]{'CustomerDescription','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] CustomerDescription2Description3_type_info = new String[]{'CustomerDescription2Description3','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] CustomerAreaCity_type_info = new String[]{'CustomerAreaCity','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] TelephoneMobile_type_info = new String[]{'TelephoneMobile','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] FaxEmail_type_info = new String[]{'FaxEmail','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] PostalCode_type_info = new String[]{'PostalCode','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] Address_type_info = new String[]{'Address','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] CustomerCategory_type_info = new String[]{'CustomerCategory','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] Industry_type_info = new String[]{'Industry','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] ContactOffice_type_info = new String[]{'ContactOffice','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] ContactCode_type_info = new String[]{'ContactCode','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] ContactEffectiveDateFrom_type_info = new String[]{'ContactEffectiveDateFrom','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] PurposeOfAdvice_type_info = new String[]{'PurposeOfAdvice','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG001','false','false'};
+        private String[] field_order_type_info = new String[]{'CustomerCode','CustomerDescription','CustomerDescription2Description3','CustomerAreaCity','TelephoneMobile','FaxEmail','PostalCode','Address','CustomerCategory','Industry','ContactOffice','ContactCode','ContactEffectiveDateFrom','PurposeOfAdvice'};
+    }
+
+    public class SSBDCustomerContacts_element {
+        public OlympusCoJpCommonMessage.Monitoring Monitoring;
+        public Sbg001Sync.SSBDCustomerContact_element[] SSBDCustomerContact;
+        private String[] Monitoring_type_info = new String[]{'Monitoring','http://olympus.co.jp/gpi/SBG001',null,'1','1','false'};
+        private String[] SSBDCustomerContact_type_info = new String[]{'SSBDCustomerContact','http://olympus.co.jp/gpi/SBG001',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG001','false','false'};
+        private String[] field_order_type_info = new String[]{'Monitoring','SSBDCustomerContact'};
+    }
+
+    public class SBG001 {
+        public Sbg001Sync.SSBDCustomerContacts_element[] SSBDCustomerContacts;
+        private String[] SSBDCustomerContacts_type_info = new String[]{'SSBDCustomerContacts','http://olympus.co.jp/gpi/SBG001',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG001','false','false'};
+        private String[] field_order_type_info = new String[]{'SSBDCustomerContacts'};
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/Sbg001Sync.cls-meta.xml b/scr/classes/Sbg001Sync.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/Sbg001Sync.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/Sbg007Sync.cls b/scr/classes/Sbg007Sync.cls
new file mode 100644
index 0000000..843f0ff
--- /dev/null
+++ b/scr/classes/Sbg007Sync.cls
@@ -0,0 +1,91 @@
+public class Sbg007Sync {
+    public class GeData_element {
+        public String OpportunityCode;
+        public String SalesAccountCode;
+        public String ProductSegment;
+        public String TradeType;
+        public String MachineParts;
+        public String SalesChannel;
+        public String ExpectedDeliveryDate;
+        public String DealerCode;
+        public String DealerSalesStaffName;
+        public String ForeignTradeCompany;
+        public String SpecialDeliveryAddress;
+        public String Other1;
+        public String Other2;
+        public String Other3;
+        public Sbg007Sync.GeDataDetails_element[] GeDataDetails;
+        private String[] OpportunityCode_type_info = new String[]{'OpportunityCode','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] SalesAccountCode_type_info = new String[]{'SalesAccountCode','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] ProductSegment_type_info = new String[]{'ProductSegment','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] TradeType_type_info = new String[]{'TradeType','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] MachineParts_type_info = new String[]{'MachineParts','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] SalesChannel_type_info = new String[]{'SalesChannel','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] ExpectedDeliveryDate_type_info = new String[]{'ExpectedDeliveryDate','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] DealerCode_type_info = new String[]{'DealerCode','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] DealerSalesStaffName_type_info = new String[]{'DealerSalesStaffName','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] ForeignTradeCompany_type_info = new String[]{'ForeignTradeCompany','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] SpecialDeliveryAddress_type_info = new String[]{'SpecialDeliveryAddress','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] Other1_type_info = new String[]{'Other1','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] Other2_type_info = new String[]{'Other2','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] Other3_type_info = new String[]{'Other3','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] GeDataDetails_type_info = new String[]{'GeDataDetails','http://olympus.co.jp/gpi/SBG007',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG007','false','false'};
+        private String[] field_order_type_info = new String[]{'OpportunityCode','SalesAccountCode','ProductSegment','TradeType','MachineParts','SalesChannel','ExpectedDeliveryDate','DealerCode','DealerSalesStaffName','ForeignTradeCompany','SpecialDeliveryAddress','Other1','Other2','Other3','GeDataDetails'};
+    }
+    public class GeDatas_element {
+        public OlympusCoJpCommonMessage.Monitoring Monitoring;
+        public Sbg007Sync.GeData_element[] GeData;
+        private String[] Monitoring_type_info = new String[]{'Monitoring','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] GeData_type_info = new String[]{'GeData','http://olympus.co.jp/gpi/SBG007',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG007','false','false'};
+        private String[] field_order_type_info = new String[]{'Monitoring','GeData'};
+    }
+    public class GeDataDetails_element {
+        public Integer DetailLine;
+        public String ItemCode;
+        public Integer ItemQuantity;
+        private String[] DetailLine_type_info = new String[]{'DetailLine','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] ItemCode_type_info = new String[]{'ItemCode','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] ItemQuantity_type_info = new String[]{'ItemQuantity','http://olympus.co.jp/gpi/SBG007',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG007','false','false'};
+        private String[] field_order_type_info = new String[]{'DetailLine','ItemCode','ItemQuantity'};
+    }
+    public class SBG007 {
+        public Sbg007Sync.GeDatas_element[] GeDatas;
+        private String[] GeDatas_type_info = new String[]{'GeDatas','http://olympus.co.jp/gpi/SBG007',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG007','false','false'};
+        private String[] field_order_type_info = new String[]{'GeDatas'};
+    }
+    public class HTTPS_Port {
+        public String endpoint_x = 'https://pit0u.is.olympus.global:50001/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
+        public Map<String,String> inputHttpHeaders_x;
+        public Map<String,String> outputHttpHeaders_x;
+        public String clientCertName_x;
+        public String clientCert_x;
+        public String clientCertPasswd_x;
+        public Integer timeout_x;
+        private String[] ns_map_type_info = new String[]{'http://olympus.co.jp/common/message', 'OlympusCoJpCommonMessage', 'http://olympus.co.jp/gpi/SBG007', 'Sbg007Sync'};
+        public OlympusCoJpCommonMessage.LOG_element[] SBG007_Sync_BC2GPI(Sbg007Sync.GeDatas_element[] GeDatas) {
+            Sbg007Sync.SBG007 request_x = new Sbg007Sync.SBG007();
+            request_x.GeDatas = GeDatas;
+            OlympusCoJpCommonMessage.Response response_x;
+            Map<String, OlympusCoJpCommonMessage.Response> response_map_x = new Map<String, OlympusCoJpCommonMessage.Response>();
+            response_map_x.put('response_x', response_x);
+            WebServiceCallout.invoke(
+              this,
+              request_x,
+              response_map_x,
+              new String[]{endpoint_x,
+              'http://sap.com/xi/WebService/soap1.1',
+              'http://olympus.co.jp/gpi/SBG007',
+              'SBG007',
+              'http://olympus.co.jp/common/message',
+              'Response',
+              'OlympusCoJpCommonMessage.Response'}
+            );
+            response_x = response_map_x.get('response_x');
+            return response_x.LOG;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/Sbg007Sync.cls-meta.xml b/scr/classes/Sbg007Sync.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/Sbg007Sync.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/Sbg027Sync.cls b/scr/classes/Sbg027Sync.cls
new file mode 100644
index 0000000..2bd0a41
--- /dev/null
+++ b/scr/classes/Sbg027Sync.cls
@@ -0,0 +1,109 @@
+public class Sbg027Sync {
+    public class GeData_element {
+        public String OpportunityCode;
+        public String OrderCode;
+        public String SalesAccountCode;
+        public String EndUser;
+        public String ProductSegment;
+        public String TradeType;
+        public String MachineParts;
+        public String SalesChannel;
+        public String DealerCode;
+        public String DealerSalesStaffName;
+        public String DeliveryDate;
+        public String PaymentCondition;
+        public String SpecialWarranty;
+        public Decimal OlympusContractPrices;
+        public Decimal Discount;
+        public Decimal OlympusPriceBeforeDiscount;
+        public Decimal ServiceFee;
+        public String ForeignTradeCompany;
+        public String SpecialDeliveryAddress;
+        public String PurposeOfAdvice;
+        public String Other1;
+        public String Other2;
+        public String Other3;
+        public Sbg027Sync.GeDataDetails_element[] GeDataDetails;
+        private String[] OpportunityCode_type_info = new String[]{'OpportunityCode','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] OrderCode_type_info = new String[]{'OrderCode','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] SalesAccountCode_type_info = new String[]{'SalesAccountCode','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] EndUser_type_info = new String[]{'EndUser','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] ProductSegment_type_info = new String[]{'ProductSegment','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] TradeType_type_info = new String[]{'TradeType','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] MachineParts_type_info = new String[]{'MachineParts','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] SalesChannel_type_info = new String[]{'SalesChannel','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] DealerCode_type_info = new String[]{'DealerCode','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] DealerSalesStaffName_type_info = new String[]{'DealerSalesStaffName','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] DeliveryDate_type_info = new String[]{'DeliveryDate','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] PaymentCondition_type_info = new String[]{'PaymentCondition','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] SpecialWarranty_type_info = new String[]{'SpecialWarranty','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] OlympusContractPrices_type_info = new String[]{'OlympusContractPrices','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] Discount_type_info = new String[]{'Discount','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] OlympusPriceBeforeDiscount_type_info = new String[]{'OlympusPriceBeforeDiscount','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] ServiceFee_type_info = new String[]{'ServiceFee','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] ForeignTradeCompany_type_info = new String[]{'ForeignTradeCompany','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] SpecialDeliveryAddress_type_info = new String[]{'SpecialDeliveryAddress','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] PurposeOfAdvice_type_info = new String[]{'PurposeOfAdvice','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] Other1_type_info = new String[]{'Other1','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] Other2_type_info = new String[]{'Other2','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] Other3_type_info = new String[]{'Other3','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] GeDataDetails_type_info = new String[]{'GeDataDetails','http://olympus.co.jp/gpi/SBG027',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG027','false','false'};
+        private String[] field_order_type_info = new String[]{'OpportunityCode','OrderCode','SalesAccountCode','EndUser','ProductSegment','TradeType','MachineParts','SalesChannel','DealerCode','DealerSalesStaffName','DeliveryDate','PaymentCondition','SpecialWarranty','OlympusContractPrices','Discount','OlympusPriceBeforeDiscount','ServiceFee','ForeignTradeCompany','SpecialDeliveryAddress','PurposeOfAdvice','Other1','Other2','Other3','GeDataDetails'};
+    }
+    public class GeDatas_element {
+        public OlympusCoJpCommonMessage.Monitoring Monitoring;
+        public Sbg027Sync.GeData_element[] GeData;
+        private String[] Monitoring_type_info = new String[]{'Monitoring','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] GeData_type_info = new String[]{'GeData','http://olympus.co.jp/gpi/SBG027',null,'0','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG027','false','false'};
+        private String[] field_order_type_info = new String[]{'Monitoring','GeData'};
+    }
+    public class SBG027 {
+        public Sbg027Sync.GeDatas_element[] GeDatas;
+        private String[] GeDatas_type_info = new String[]{'GeDatas','http://olympus.co.jp/gpi/SBG027',null,'1','-1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG027','false','false'};
+        private String[] field_order_type_info = new String[]{'GeDatas'};
+    }
+    public class GeDataDetails_element {
+        public Integer DetailLine;
+        public String ItemCode;
+        public Integer ItemQuantity;
+        private String[] DetailLine_type_info = new String[]{'DetailLine','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] ItemCode_type_info = new String[]{'ItemCode','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] ItemQuantity_type_info = new String[]{'ItemQuantity','http://olympus.co.jp/gpi/SBG027',null,'1','1','false'};
+        private String[] apex_schema_type_info = new String[]{'http://olympus.co.jp/gpi/SBG027','false','false'};
+        private String[] field_order_type_info = new String[]{'DetailLine','ItemCode','ItemQuantity'};
+    }
+    public class HTTPS_Port {
+        public String endpoint_x = 'https://pit0u.is.olympus.global:50001/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
+        public Map<String,String> inputHttpHeaders_x;
+        public Map<String,String> outputHttpHeaders_x;
+        public String clientCertName_x;
+        public String clientCert_x;
+        public String clientCertPasswd_x;
+        public Integer timeout_x;
+        private String[] ns_map_type_info = new String[]{'http://olympus.co.jp/common/message', 'OlympusCoJpCommonMessage', 'http://olympus.co.jp/gpi/SBG027', 'Sbg027Sync'};
+        public OlympusCoJpCommonMessage.LOG_element[] SBG027_Sync_BC2GPI(Sbg027Sync.GeDatas_element[] GeDatas) {
+            Sbg027Sync.SBG027 request_x = new Sbg027Sync.SBG027();
+            request_x.GeDatas = GeDatas;
+            OlympusCoJpCommonMessage.Response response_x;
+            Map<String, OlympusCoJpCommonMessage.Response> response_map_x = new Map<String, OlympusCoJpCommonMessage.Response>();
+            response_map_x.put('response_x', response_x);
+            WebServiceCallout.invoke(
+              this,
+              request_x,
+              response_map_x,
+              new String[]{endpoint_x,
+              'http://sap.com/xi/WebService/soap1.1',
+              'http://olympus.co.jp/gpi/SBG027',
+              'SBG027',
+              'http://olympus.co.jp/common/message',
+              'Response',
+              'OlympusCoJpCommonMessage.Response'}
+            );
+            response_x = response_map_x.get('response_x');
+            return response_x.LOG;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/Sbg027Sync.cls-meta.xml b/scr/classes/Sbg027Sync.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/Sbg027Sync.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchManagementController.cls b/scr/classes/SearchManagementController.cls
new file mode 100644
index 0000000..0ecf8af
--- /dev/null
+++ b/scr/classes/SearchManagementController.cls
@@ -0,0 +1,118 @@
+public without sharing class SearchManagementController {
+
+    public String baseUrl { get; private set; }
+    public String baId { get; private set; }
+    public String tsRepairId { get; private set; }
+    public String ufId { get; private set; }
+    public Boolean ErrorFlag { get; private set; }
+
+    public String searchManagementCode {get;set;}
+
+    public User_FaultInfo__c  UserFaultInfo  {get;set;}  
+    public List<User_FaultInfo__c> UserFaultInfoList {get;set;}
+    public Integer ErrorNum {get;set;} 
+
+    public String fromUserFaultInfoId {get;set;}
+
+    public String lineno {get;set;}
+    public SearchManagementController() {
+        ErrorFlag = false;
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        // 寰呮洿鏂扮殑涓氬姟娲诲姩Id
+        baId = System.currentPageReference().getParameters().get('baId');
+        // TS鏃ユ姤Id
+        tsRepairId = System.currentPageReference().getParameters().get('repairId');
+        // 寰呮洿鏂扮殑鐢ㄦ埛鏁呴殰淇℃伅鐨処d
+        ufId = System.currentPageReference().getParameters().get('ufId');
+
+        lineno = System.currentPageReference().getParameters().get('lineno');
+    }
+    public void init () {
+        ErrorFlag = false;
+        ErrorNum = 0;
+        UserFaultInfoList = new List<User_FaultInfo__c>();
+        searchManagementCode = '';
+        UserFaultInfo = new User_FaultInfo__c();  
+        if (searchManagementCode != null && searchManagementCode != '' || UserFaultInfo.UserFaultInfoReportDate__c != null ) {
+            serUserFaultInfo();
+        }
+    }
+
+    public PageReference serUserFaultInfo(){
+        //褰撳墠鐢ㄦ埛ID
+        String userId = UserInfo.getUserId();
+        String soql = TSRepairUtil.UserFaultInfoBaseSQL();
+        String recordTypeId = System.label.Case_RecordTypeTSTSReport;
+        //绠$悊缂栧彿涓嶄负NULL
+        if(String.isNotBlank(searchManagementCode)){
+            soql += ' and UFManagementCode__c like \'%' + String.escapeSingleQuotes(searchManagementCode.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        //鎶ュ憡鏃ユ湡涓嶄负NULL
+        if(UserFaultInfo.UserFaultInfoReportDate__c != null ){
+           
+            soql += ' and UserFaultInfoReportDate__c = '+ String.valueOf(UserFaultInfo.UserFaultInfoReportDate__c);
+        }
+        //鏌ユ壘瀹㈡埛涓嶄负null
+        if(UserFaultInfo.UFAccount__c !=null){
+            String accountId = UserFaultInfo.UFAccount__c;
+            soql += ' and UFAccount__c  =\''+ accountId +'\'';
+            // soql += ' AND ' + TSRepairUtil.AccountBaseRecordTypeIdSQL2();
+        }
+
+        soql +=  ' and OwnerId = \'' + userId + '\'' ;
+        soql +=  ' AND UserFaultInfoCompletionDate__c = null ';  
+        soql +=  ' AND RecordTypeId = \'' + recordTypeId + '\''; 
+        soql +=  ' order by Id' ;
+        System.debug('soql------>222->'+soql);
+        UserFaultInfoList = Database.query(soql);
+
+        return null;
+    }
+
+    public void save(){
+
+        // 涓氬姟娲诲姩
+        ErrorFlag = true;
+        String errorMessages = '';
+        Map<String, User_FaultInfo__c> userFaultInfoMap = new Map<String, User_FaultInfo__c>();
+        if (UserFaultInfoList != null && UserFaultInfoList.size() > 0) {
+
+            for (User_FaultInfo__c uf :UserFaultInfoList) {
+                if (uf.UserFaultInfoBeSelected__c) {
+                    uf.UserFaultInfoBeSelected__c = false;
+                    userFaultInfoMap.put(uf.UFManagementCode__c, uf);
+                }
+            }
+            if (userFaultInfoMap != null && userFaultInfoMap.size() == 1) {
+                ErrorNum = userFaultInfoMap.size();
+                ErrorFlag = false;
+            } else if (userFaultInfoMap.size() > 1) {
+                
+                errorMessages = '鍙兘閫夋嫨涓�涓笟鍔℃椿鍔紝璇风‘璁�';
+            } else if (userFaultInfoMap.size() < 1) {
+                errorMessages = '璇烽�夋嫨涓�涓笟鍔℃椿鍔紝璇风‘璁�';
+            }
+
+            if (ErrorFlag) {
+                ErrorNum = userFaultInfoMap.size();
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, errorMessages));
+            } else {
+
+                Savepoint sp = Database.setSavepoint();
+                try {
+                    for (String uFManagementCode : userFaultInfoMap.keySet()) {
+                        User_FaultInfo__c updateUserFaultInfo = userFaultInfoMap.get(uFManagementCode);
+                        fromUserFaultInfoId = updateUserFaultInfo.Id;
+                    }
+                
+                }catch (Exception e) {
+                    ApexPages.addMessages(e);
+                    Database.rollback(sp);
+                }
+            }
+        }
+
+
+        
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SearchManagementController.cls-meta.xml b/scr/classes/SearchManagementController.cls-meta.xml
new file mode 100644
index 0000000..db9bf8c
--- /dev/null
+++ b/scr/classes/SearchManagementController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>48.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchManagementControllerTest.cls b/scr/classes/SearchManagementControllerTest.cls
new file mode 100644
index 0000000..85353c2
--- /dev/null
+++ b/scr/classes/SearchManagementControllerTest.cls
@@ -0,0 +1,86 @@
+@isTest
+private class SearchManagementControllerTest {
+
+    public static TS_Repair__c tsr;
+
+    public static User_FaultInfo__c uf;
+    public static User_FaultInfo__c uf2;
+
+    public static BusinessActivity__c ba;
+
+    static void basicData() {
+        System.runAs(new User(Id = Userinfo.getUserId())) {
+            uf = new User_FaultInfo__c();
+            uf.UserFaultInfoReportDate__c = Date.today();
+            uf.RecordTypeId = System.label.Case_RecordTypeTSTSReport;
+            insert uf;
+
+            uf2 = new User_FaultInfo__c();
+            uf2.RecordTypeId = System.label.Case_RecordTypeTSTSReport;
+            uf2.UserFaultInfoReportDate__c = Date.today();
+            insert uf2;
+            tsr = new TS_Repair__c();
+            insert tsr;
+
+            ba = new BusinessActivity__c();
+            insert ba;
+        }
+
+
+    }
+    // 閫夋嫨涓�涓� 鐢ㄦ埛/鏁呴殰淇℃伅
+    static testMethod void testMethod1() {
+        
+        basicData();
+        System.runAs(new User(Id = Userinfo.getUserId())) {
+            PageReference page = new PageReference('/apex/SearchManagementCode?lineno=0&baId='+ba.Id+'&repairId='+tsr.Id+'&ufId='+uf.Id);
+            List<User_FaultInfo__c> ufList = [select Id,Name from User_FaultInfo__c];
+            System.Test.setCurrentPage(page);
+            SearchManagementController controller = new SearchManagementController();
+            controller.init(); 
+            //controller.searchManagementCode = ufList[0].Name;
+            controller.UserFaultInfo.UserFaultInfoReportDate__c = Date.today();
+
+            controller.serUserFaultInfo();
+            controller.UserFaultInfoList[0].UserFaultInfoBeSelected__c = true;
+            controller.save();
+        }
+        
+    }
+    // 閫夋嫨涓や釜 鐢ㄦ埛/鏁呴殰淇℃伅 鎶ラ敊
+    static testMethod void testMethod2() {
+        
+        basicData();
+        System.runAs(new User(Id = Userinfo.getUserId())) {
+            PageReference page = new PageReference('/apex/SearchManagementCode?lineno=0&baId='+ba.Id+'&repairId='+tsr.Id+'&ufId='+uf.Id);
+            
+            List<User_FaultInfo__c> ufList = [select Id,Name from User_FaultInfo__c];
+            System.Test.setCurrentPage(page);
+            SearchManagementController controller = new SearchManagementController();
+            controller.init(); 
+            controller.UserFaultInfo.UserFaultInfoReportDate__c = Date.today();
+            controller.serUserFaultInfo();
+            controller.UserFaultInfoList[0].UserFaultInfoBeSelected__c = true;
+            controller.UserFaultInfoList[1].UserFaultInfoBeSelected__c = true;
+            controller.save();
+        }
+        
+    }
+    // 涓嶉�夋嫨 鐢ㄦ埛/鏁呴殰淇℃伅 鎶ラ敊
+    static testMethod void testMethod3() {
+        
+        basicData();
+        System.runAs(new User(Id = Userinfo.getUserId())) {
+            PageReference page = new PageReference('/apex/SearchManagementCode?lineno=0&baId='+ba.Id+'&repairId='+tsr.Id+'&ufId='+uf.Id);
+            
+            List<User_FaultInfo__c> ufList = [select Id,Name from User_FaultInfo__c];
+            System.Test.setCurrentPage(page);
+            SearchManagementController controller = new SearchManagementController();
+            controller.init(); 
+            controller.UserFaultInfo.UserFaultInfoReportDate__c = Date.today();
+            controller.serUserFaultInfo();
+            controller.save();
+        }
+        
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SearchManagementControllerTest.cls-meta.xml b/scr/classes/SearchManagementControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SearchManagementControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchMemberPageController.cls b/scr/classes/SearchMemberPageController.cls
new file mode 100644
index 0000000..b3a6f71
--- /dev/null
+++ b/scr/classes/SearchMemberPageController.cls
@@ -0,0 +1,114 @@
+public with sharing class SearchMemberPageController {
+    //椤甸潰杈撳叆妫�绱㈡潯浠�
+    public String searchByName{get;set;}
+    public String searchByAccount{get;set;}
+    public String memberType{get;set;}
+    public List<LineMember> lineList{get;set;} 
+    public Integer lineNum{get;set;}
+    public String memberId{get;set;}
+    public String memberName{get;set;}
+    public String memberEmail{get;set;}
+    public Boolean isError{get;set;}
+
+    public SearchMemberPageController() {
+        lineNum = Integer.valueOf(System.currentPageReference().getParameters().get('lineNum'));
+    }
+    public void init(){
+        lineList = new List<LineMember>();
+        memberType = 'Contact';
+    }
+    //鍓嶅彴鐐瑰嚮鏌ヨ
+    public void SearchMember(){
+        lineList.clear();
+        System.debug('memberType:'+memberType);
+        String soql = '';
+        if(memberType == 'Contact'){
+
+            soql = 'select Id,Name,Email,Account.Name from Contact where Id!=null ';
+
+            if(String.isNotBlank(searchByName)){
+                soql += 'and Name like \'%'+searchByName.trim()+'%\' ';
+            }
+            if(String.isNotBlank(searchByAccount)){
+                soql += 'and Account.Name like \'%'+searchByAccount.trim()+'%\' ';
+            }
+            soql += 'limit 200';
+            List<Contact> conList = Database.query(soql);
+            if(conList!=null&&conList.size()!=0){
+                for(Contact con : conList){
+                    LineMember line = new LineMember();
+                    line.check = false;
+                    line.Id = con.Id;
+                    line.name = con.Name;
+                    line.email = con.Email;
+                    line.account = con.Account.Name;
+                    lineList.add(line);
+                }
+            }
+        }else if(memberType == 'User'){
+            
+            soql = 'select Id,UserFullName__c,Email,AccountId,Account.Name from User where Id!=null ';
+            if(String.isNotBlank(searchByName)){
+                soql += 'and UserFullName__c like \'%'+searchByName.replaceAll(' ', '')+'%\'';
+            }
+            soql += 'limit 200';
+            System.debug(soql);
+            List<User> userList = Database.query(soql);
+            if (userList!=null && userList.size()!=0) {
+                for (User user:userList) {
+                    LineMember line = new LineMember();
+                    line.check = false;
+                    line.Id = user.Id;
+                    line.name = user.UserFullName__c;
+                    line.email = user.Email;
+                    line.account = user.Account.Name;
+                    lineList.add(line);
+                }
+            }
+        }
+    }
+    //鍓嶅彴鐐瑰嚮淇濆瓨锛�
+    public void save(){
+        isError = false;
+        String errorMessage = '';
+        if(lineList!=null && lineList.size()!=0){
+            Integer i = 0;
+            for(LineMember line : lineList){
+                if(line.check){
+                    memberId = line.Id;
+                    memberName = line.name;
+                    memberEmail = line.email;
+                    System.debug(line.email);
+                    i++;
+                }
+                if(i>1){    
+                    isError = true;
+                    errorMessage = '閫夋嫨浜烘暟澶т簬1锛�';
+                }
+            }
+            if(i == 0){
+                isError = true;
+                errorMessage = '璇烽�夋嫨涓�鏉℃暟鎹�!';
+            }
+            if(isError){
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, errorMessage));
+            }
+        }
+
+    }
+
+    /*public List<SelectOption> getItems() {
+        List<SelectOption> options = new List<SelectOption>();
+        options.add(new SelectOption('Contact','Contact'));
+        options.add(new SelectOption('User','User'));
+        return options;
+    }*/
+
+    public class LineMember{
+        public Boolean check{get;set;}
+        public String Id{get;set;}
+        public String name{get;set;}
+        public String email{get;set;}
+        public String account{get;set;}
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SearchMemberPageController.cls-meta.xml b/scr/classes/SearchMemberPageController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SearchMemberPageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchMemberPageControllerTest.cls b/scr/classes/SearchMemberPageControllerTest.cls
new file mode 100644
index 0000000..d6a2289
--- /dev/null
+++ b/scr/classes/SearchMemberPageControllerTest.cls
@@ -0,0 +1,78 @@
+@isTest
+private class SearchMemberPageControllerTest {
+    static testMethod void testMethod1() {
+    	List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        
+        User user = new User();
+        user.LastName = 'test';
+        user.FirstName = 'test';
+        user.Alias = 'test';
+        user.Email = 'test@test.com';
+        user.Username = 'test111@test222.com';
+        user.CommunityNickname = 'test1111';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+        
+        Account acc = new Account();
+        acc.Name = 'test';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        acc.stautesD__c= 'Pass';
+        insert acc;
+        
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = acc.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+        insert con;
+
+        PageReference page = new PageReference('/apex/SearchMemberPage?lineNum=1');
+        System.Test.setCurrentPage(page);
+        SearchMemberPageController controller = new SearchMemberPageController();
+        controller.init();
+
+        controller.searchByName = 'test';
+        controller.SearchMember();
+
+        controller.searchByAccount = 'test';
+        controller.SearchMember();
+
+        controller.searchByName = 'test';
+        controller.searchByAccount = 'test';
+        controller.SearchMember();
+
+        controller.memberType = 'User';
+
+        controller.searchByName = 'test';
+        controller.SearchMember();
+
+        controller.searchByAccount = 'test';
+        controller.SearchMember();
+
+        controller.searchByName = 'test';
+        controller.searchByAccount = 'test';
+        controller.SearchMember();
+
+        controller.save();
+        controller.lineList[0].check = true;
+        controller.save();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SearchMemberPageControllerTest.cls-meta.xml b/scr/classes/SearchMemberPageControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SearchMemberPageControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchProductController.cls b/scr/classes/SearchProductController.cls
new file mode 100644
index 0000000..5c897e9
--- /dev/null
+++ b/scr/classes/SearchProductController.cls
@@ -0,0 +1,291 @@
+public with sharing class SearchProductController {
+
+    public Integer quoteEntryMaxSet {get; private set;}
+
+    public List<ProductLine> cl {get;set;}
+    public Boolean getHascl() {
+        Boolean rtn = true;
+        if (cl != null && cl.size() > 0) {
+            rtn = false;
+        }
+        return rtn;
+    }
+
+    public String searchMode;                         // 妞滅储銉€兗銉�
+    public String openFlag {get;set;}                 // 瑕敾闈lag
+    public String lineNo {get;set;}                   // 瑕敾闈€伄閬告姙銇椼仧琛�
+    public String val {get;set;}
+    public String setStr {get;set;}
+    public String oppId {get;set;}                    // 瑕敾闈€伄銇嬨倝銇绱㈡枃瀛楀垪
+    public String SearchName {get;set;}               // 妞滅储鏂囧瓧鍒�
+    public String baseUrl { get; set; }
+    public String productSetVal {get;set;}
+    public boolean oppflg {get;set;}
+
+    public String productSegment {get;set;}
+
+    public String openType {get;set;}
+
+    public List<SelectOption> productSet { get; set; }
+
+    public boolean is_hidden_user { get; set; }
+    public boolean is_dealer_user { get; set; }
+
+    public Boolean is_hidden_all { get; set; }
+
+    public Boolean specialDealer { get; set; }
+
+    public SearchProductController(ApexPages.StandardController controller){
+        this();
+    }
+
+    public SearchProductController() {
+        this.quoteEntryMaxSet = Integer.valueOf(System.Label.QuoteEntryMaxSet);
+        //XHL-20190428-UpdateStart
+        //this.productSetVal = Apexpages.currentPage().getParameters().get('set');
+        //if (productSetVal!=null || productSetVal!=''){
+        //} else {
+        //   this.productSetVal = '鍗曞搧';
+        //}
+        //XHL-20190428-UpdateEnd
+        is_hidden_user = false;
+        // String profileid = UserInfo.getProfileId().subString(0,15);
+
+        //鏂扮殑鑾峰彇绠�妗D  calendarUtil.getMemberProfileID  杩欓噷鐢ㄥ埌鐨勪汉鍛業D 鍜岃幏鍙栧埌鐨勭畝妗D閮芥槸15浣嶇殑
+        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
+
+        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {
+            is_hidden_user = true;
+        }
+        is_dealer_user = false;
+        if (UserInfo.getUserType() == 'PowerPartner') {
+            is_dealer_user = true;
+        }
+
+        //XHL-20190428-UpdateStart
+        //this.productSet = new List<SelectOption>();
+        //this.productSet.add(new SelectOption('鍗曞搧','鍗曞搧'));
+        //this.openType = Apexpages.currentPage().getParameters().get('openType');
+        //if (openType == 'service') {
+        //    this.productSet.add(new SelectOption('set01','闆朵欢璐圭敤'));
+        //    this.productSet.add(new SelectOption('set02','缁翠慨璐�'));
+        //    this.productSet.add(new SelectOption('set03','鍏朵粬璐圭敤'));
+        //} else {
+        //    for (Integer i = 0; i < this.quoteEntryMaxSet; i++) {
+        //        if (i < 9) {
+        //            this.productSet.add(new SelectOption('set0'+ String.valueOf(i+1),'濂楄0'+ String.valueOf(i+1)));
+        //        } else {
+        //            this.productSet.add(new SelectOption('set'+ String.valueOf(i+1),'濂楄'+ String.valueOf(i+1)));
+        //        }
+        //    }
+        //}
+        //XHL-20190428-UpdateEnd
+        this.openFlag = Apexpages.currentPage().getParameters().get('openFlag');
+        this.lineNo = Apexpages.currentPage().getParameters().get('lineno');
+        this.val = Apexpages.currentPage().getParameters().get('val');
+        this.oppId = Apexpages.currentPage().getParameters().get('oppId');
+
+        if (openFlag == 'opp') {
+            oppflg = false;
+        } else {
+            oppflg = true;
+        }
+
+        if (val!=null && val!=''){
+            SearchName = val;
+            val = null;
+        }
+
+        cl = new List<ProductLine>();
+    }
+
+    public void init () {
+        system.debug('init==========> start');
+        system.debug('SearchName==========>' + SearchName);
+        if (SearchName != null && SearchName != '') {
+            serContact();
+        }
+
+        system.debug('init==========> end');
+
+    }
+
+    public PageReference serContact(){
+        //is_hidden_all = false;
+        is_hidden_all = true;
+        List<Opportunity> oppList = [select Id,DealerId__c,RecordTypeId,CurrencyIsoCode,Pricebook2Id,ProductSegment__c,Machine_Parts__c,SalesChannel__c From Opportunity where Id = :oppid];
+        //List<Opportunity> oppList = [select Id,DealerId__c,RecordTypeId,CurrencyIsoCode,Pricebook2Id,ProductSegment__c,Machine_Parts__c,SalesChannel__c,DealerId__c From Opportunity where Id = :oppid];
+        //is_hidden_all = StaticParameter.specialDealerMap.containsKey(oppList[0].DealerId__c);
+        //is_hidden_all = !StaticParameter.specialDealerMap.containsKey(oppList[0].DealerId__c);
+        is_hidden_all = !IfspecialDealer(oppList[0].DealerId__c);
+        system.debug('is_hidden_all---->'+is_hidden_all);
+        String sCurrencyIsoCode = oppList[0].CurrencyIsoCode;
+        String sPricebook2Id = oppList[0].Pricebook2Id;
+        String sProductSegment = oppList[0].ProductSegment__c;
+        productSegment =  oppList[0].ProductSegment__c;   
+        boolean is_Parts_direct = false;
+        boolean is_Replacement = false;
+        if(oppList[0].RecordTypeId == System.Label.SSBD_Replacement){
+            is_Replacement = true;
+        }
+        if (oppList[0].Machine_Parts__c == 'Parts' && oppList[0].SalesChannel__c == 'direct') {
+            is_Parts_direct = true;
+        }
+        //if(StaticParameter.specialDealerMap.containsKey(oppList[0].DealerId__c)){
+        if(IfspecialDealer(oppList[0].DealerId__c)){
+            is_hidden_user = true;
+            specialDealer = true;
+        }
+        system.debug('sCurrencyIsoCode==========>' + sCurrencyIsoCode);
+        system.debug('sPricebook2Id==========>' + sPricebook2Id);
+
+        String searchSql = 'select Id,Product2Id,SalesPrice__c,SalesPriceA__c,SalesPriceB__c,SalesPriceC__c,CostPrice__c,Pricebook2Id,Product2.ProductModels__c,Hidden_flag__c from PricebookEntry';
+        //20191113-XHL---Start-灏嗕骇鍝佺姸鎬�(ProductStatus__c)鐢ㄤ骇鍝佺姸鎬�(鍏紡)(ProductStatusFormula__c)鏇挎崲
+        //String whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0 and (CostPrice__c > 0 or Product2.Dummy__c = true))) and Product2.ProductStatus__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode';
+        String whereStr = '';
+        if(is_Replacement){
+            boolean temp = !is_Replacement;
+            whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0 and (CostPrice__c > 0 or Product2.Dummy__c = true))) and Product2.ProductStatusFormula__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode and Product2.isMain__c =:temp';
+            //20191113-XHL---End-灏嗕骇鍝佺姸鎬�(ProductStatus__c)鐢ㄤ骇鍝佺姸鎬�(鍏紡)(ProductStatusFormula__c)鏇挎崲
+            //String whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0)) and Product2.ProductStatus__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode';
+        
+        }else{
+            whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0 and (CostPrice__c > 0 or Product2.Dummy__c = true))) and Product2.ProductStatusFormula__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode ';
+            //20191113-XHL---End-灏嗕骇鍝佺姸鎬�(ProductStatus__c)鐢ㄤ骇鍝佺姸鎬�(鍏紡)(ProductStatusFormula__c)鏇挎崲
+            //String whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0)) and Product2.ProductStatus__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode';
+        
+        }
+        /*String whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0 and (CostPrice__c > 0 or Product2.Dummy__c = true))) and Product2.ProductStatusFormula__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode and Product2.isReplacement__c =:is_Replacement';
+        //20191113-XHL---End-灏嗕骇鍝佺姸鎬�(ProductStatus__c)鐢ㄤ骇鍝佺姸鎬�(鍏紡)(ProductStatusFormula__c)鏇挎崲
+        //String whereStr = '  Where (Product2.ProductModels__c = true or (SalesPrice__c > 0)) and Product2.ProductStatus__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode';*/
+        if (is_Parts_direct) {
+            //20191113-XHL---Start-灏嗕骇鍝佺姸鎬�(ProductStatus__c)鐢ㄤ骇鍝佺姸鎬�(鍏紡)(ProductStatusFormula__c)鏇挎崲
+            //whereStr = '  Where Product2.ProductStatus__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode';
+            whereStr = '  Where Product2.ProductStatusFormula__c = \'1\' and Pricebook2Id = :sPricebook2Id and CurrencyIsoCode = :sCurrencyIsoCode';
+            //20191113-XHL---End-灏嗕骇鍝佺姸鎬�(ProductStatus__c)鐢ㄤ骇鍝佺姸鎬�(鍏紡)(ProductStatusFormula__c)鏇挎崲
+        }
+        String whereSql = ' and Product2.ManualHidden__c = false ' ;
+        if (SearchName != null && SearchName != '') {
+            String likename = String.escapeSingleQuotes(SearchName);
+            String prdcd = String.escapeSingleQuotes(SearchName);
+            String prdec = String.escapeSingleQuotes(SearchName);
+            if (likename.indexOf('*') >= 0) {
+                likename = likename.replace('*', '%');
+            } else {
+                likename = '%' + likename + '%';
+            }
+            if (prdcd.indexOf('*') >= 0) {
+                prdcd = prdcd.replace('*', '%');
+            } else {
+                prdcd = '%' + prdcd + '%';
+            }
+            if (prdec.indexOf('*') >= 0) {
+                prdec = prdcd.replace('*', '%');
+            } else {
+                prdec = '%' + prdec + '%';
+            }
+            whereSql += ' and (Product2.Name Like ' + '\'' + likename + '\' or Product2.ProductCode Like ' + '\'' + prdcd + '\' or Product2.Product_ECCode__c like ' + '\'' + prdec + '\')';
+        }
+
+        searchSql = searchSql + whereStr + whereSql;
+        searchSql += ' order by Product2.ProductModels__c desc, Product2.ProductCode limit 200';
+        System.debug('searchSql::::::' + searchSql);
+
+        List<PricebookEntry> pbes = Database.query(searchSql);
+
+        System.debug('pbes::::::' + pbes);
+
+        if (pbes.size() > 0) {
+
+            List<String> forSelect = new List<String>();
+
+            for (PricebookEntry pbe : pbes) {
+                forSelect.add(pbe.Product2Id);
+            }
+
+            System.debug('forSelect::::::' + forSelect);
+
+            List<Product_Search__c>  productSearchList = [select Id,Name,ProductCode__c,Product_ECCode__c,ProductModels1__c, ProductDescription__c,ProductStatus__c,Product__c
+                                                            from Product_Search__c
+                                                           where Product__c in : forSelect];
+
+            System.debug('productSearchList::::::' + productSearchList);
+
+            Map<String, Product_Search__c> tempMap = new Map<String, Product_Search__c>();
+
+            for (Product_Search__c productSearch : productSearchList) {
+                tempMap.put(productSearch.Product__c, productSearch);
+            }
+
+            System.debug('tempMap::::::' + tempMap);
+
+            Integer lineNo = 0;
+            cl = new List<ProductLine>();
+            for (Integer i = 0; i < pbes.size(); i++) {
+                System.debug('tempMap.get(pbes[i].Product2Id)::::::' + tempMap.get(pbes[i].Product2Id));
+                Product_Search__c ps = tempMap.get(pbes[i].Product2Id);
+                if (ps != null) {
+                    if (pbes[i].SalesPrice__c == null) {
+                        ProductLine pl = new ProductLine(lineNo, ps, pbes[i].Id,'0.00','0.00','0.00','0.00',pbes[i].Pricebook2Id,pbes[i].Hidden_flag__c);
+                        cl.add(pl);
+                    } else {
+                        ProductLine pl = new ProductLine(lineNo, ps,pbes[i].Id,
+                                                         String.valueOf(pbes[i].SalesPrice__c),
+                                                         String.valueOf(pbes[i].SalesPriceA__c),
+                                                         String.valueOf(pbes[i].SalesPriceB__c),
+                                                         String.valueOf(pbes[i].SalesPriceC__c),
+                                                         pbes[i].Pricebook2Id,
+                                                         pbes[i].Hidden_flag__c);
+                        if (is_hidden_user == true || is_dealer_user == true && pl.hiddenflg == true) {
+                            pl.salespriceR = '0.00';
+                        }
+                        cl.add(pl);
+                    }
+
+                    lineNo++;
+                    // 鏈�澶氭樉绀�100鏉�
+                    if (lineNo >= 100) {
+                        break;
+                    }
+                }
+            }
+        }   
+
+        return null;
+    }
+
+    public static Boolean IfspecialDealer(String oppDealerId){
+        if (String.isBlank(oppDealerId)) {
+            return false;
+        }
+        //return StaticParameter.specialDealerMap.containsKey(oppDealerId.substring(0,15));
+        return StaticParameter.specialDealerMap.containsKey(oppDealerId.substring(0,15)) && UserInfo.getUserType() == 'PowerPartner';
+    }
+
+    public class ProductLine {
+        public Integer idx {get; set;}
+        public Product_Search__c pbe {get; set;}
+        public String pbeId {get; set;}
+        public String pbId {get; set;}
+        public String salesprice {get; set;}
+        public String salespriceA {get; set;}
+        public String salespriceB {get; set;}
+        public String salespriceC {get; set;}
+        public boolean hiddenflg {get; set;}
+        public String salespriceR {get; set;}
+        
+        public ProductLine(Integer i, Product_Search__c pbe, String pbeId, String salespriceStr, String salespriceAStr, String salespriceBStr, String salespriceCStr, String pbId, boolean flag) {
+            this.idx = i;
+            this.pbe = pbe;
+            this.pbeId = pbeId;
+            this.pbId = pbId;
+            System.debug('pbeId=======>' +i+'==' + pbeId);
+            this.salesprice = salespriceStr;
+            this.salespriceA = salespriceAStr;
+            this.salespriceB = salespriceBStr;
+            this.salespriceC = salespriceCStr;
+            this.hiddenflg = flag;
+            this.salespriceR = salespriceStr;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SearchProductController.cls-meta.xml b/scr/classes/SearchProductController.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SearchProductController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchProductControllerTest.cls b/scr/classes/SearchProductControllerTest.cls
new file mode 100644
index 0000000..30cf9dd
--- /dev/null
+++ b/scr/classes/SearchProductControllerTest.cls
@@ -0,0 +1,151 @@
+@isTest
+private class SearchProductControllerTest {
+
+	@isTest static void test_init1() {
+		Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.ProductModels__c = true;
+        product1.ProductStatus__c = '1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product1.NMPAStatus_one__c = 'Z1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        Product_Search__c ps = new Product_Search__c(Product__c = product1.Id);
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        PageReference page = new PageReference('/apex/SearchProduct?oppId=' + opp.Id + '&val=product1');
+        System.Test.setCurrentPage(page);
+        SearchProductController controller = new SearchProductController();
+
+        controller.init();
+        controller.getHascl();
+	}
+
+    @isTest static void test_init2() {
+        NewReplacementOpportunityController.a();
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.ProductModels__c = true;
+        product1.ProductStatus__c = '1';
+        product1.MaterialStatus_one_Start__c = Date.today().addDays(-22);
+        product1.MaterialStatus_one_End__c = Date.today().addDays(22);
+        product1.NMPAStatus_one__c = 'Z1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        Product_Search__c ps = new Product_Search__c(Product__c = product1.Id);
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+
+        PageReference page = new PageReference('/apex/SearchProduct?oppId=' + opp.Id + '&val=product1&openType=service&openFlag=opp');
+        System.Test.setCurrentPage(page);
+        SearchProductController controller = new SearchProductController();
+
+        controller.init();
+        controller.getHascl();
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SearchProductControllerTest.cls-meta.xml b/scr/classes/SearchProductControllerTest.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/SearchProductControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchSetProductController.cls b/scr/classes/SearchSetProductController.cls
new file mode 100644
index 0000000..0b8cf1a
--- /dev/null
+++ b/scr/classes/SearchSetProductController.cls
@@ -0,0 +1,169 @@
+public class SearchSetProductController {
+	
+    public List<productSet__c> cl {get;set;}
+
+	public String SearchName {get;set;}
+	public String SearchCode {get;set;}
+
+	public Integer activitiesSize {get;set;}
+	public List<QELine> activities {get;set;}
+	public String setPFString {get;set;}
+    public String gainQuoteSetNameAndSetQty;
+    public Map<String,Decimal> setNameAndSetQtyMap;
+    public Map<String,Decimal> setNameAndSetDiscountMap;
+	public SearchSetProductController(){
+		this.setNameAndSetQtyMap = new Map<String,Decimal>();
+        this.setNameAndSetDiscountMap = new Map<String,Decimal>();
+        cl = new List<productSet__c>();
+        //鑾峰彇浠庡墠涓�涓〉闈紶杩囨潵鐨�"浜у搧閰嶅鍚嶇О"鍜�"浜у搧閰嶅鏁伴噺"
+        this.gainQuoteSetNameAndSetQty = Apexpages.currentPage().getParameters().get('gainQuoteSetNameAndSetQty');
+        system.debug('gainQuoteSetNameAndSetQty_Test_0_' + gainQuoteSetNameAndSetQty);
+        if (gainQuoteSetNameAndSetQty.length() >0) {
+
+            for (String setNameAndSetQty : gainQuoteSetNameAndSetQty.split(';')) {
+                setNameAndSetQtyMap.put(setNameAndSetQty.split(',')[0],Decimal.valueOf(setNameAndSetQty.split(',')[1]));
+                setNameAndSetDiscountMap.put(setNameAndSetQty.split(',')[0], Decimal.valueOf(setNameAndSetQty.split(',')[2]));
+            }
+        }
+        system.debug('setNameAndSetQtyMap_Test_0_' + setNameAndSetQtyMap);
+	}
+  public SearchSetProductController(ApexPages.StandardController controller){
+    this();    
+  }
+
+  public void init(){
+    system.debug('gainQuoteSetNameAndSetQty_Test' + gainQuoteSetNameAndSetQty);
+    system.debug('setNameAndSetQtyMap_Test' + setNameAndSetQtyMap);
+    activitiesSize = 0;
+    
+    searchproductSet();
+    activitiesSize = activities.size();
+  } 
+
+    public PageReference searchproductSet() {
+
+        //鏌ユ壘鏈夋晥鐨�"浜у搧閰嶅"
+        cl = [Select id, Name,Code__c From productSet__c Where  IsValid__c = true order by Name];
+
+        activities = new List<QELine>();
+        List<QELine> selectedActivities = new List<QELine>();
+        //灏嗕笂涓〉闈紶杩囨潵鐨勪骇鍝侀厤濂楅�変腑锛屽苟鏀惧埌鍓嶉潰
+        for(productSet__c psl : cl){            
+            if (setNameAndSetQtyMap.containsKey(psl.Name)) {
+                QELine a = new QELine(psl);
+                a.Quantity =  setNameAndSetQtyMap.get(psl.Name);
+                a.QuantityReference = setNameAndSetQtyMap.get(psl.Name);
+                a.Discount = setNameAndSetDiscountMap.get(psl.Name);
+                a.isSelected = true;
+                selectedActivities.add(a);  
+            } 
+        
+        }
+        for(productSet__c psl : cl){
+            
+            if (!setNameAndSetQtyMap.containsKey(psl.Name)) {
+                QELine a = new QELine(psl);
+                a.Quantity = 0;
+                a.QuantityReference = 0;
+                a.Discount = 0 ;
+                selectedActivities.add(a); 
+            } else {
+                continue;
+            } 
+        }
+        activities = selectedActivities;
+        return null;   
+    } 
+
+    public PageReference serContact(){
+        
+        String searchSql = 'Select id,Code__c,Name From productSet__c ';
+        String whereStr = 'Where  IsValid__c = true ';
+        String whereSql = '';
+
+        if(SearchName != null && SearchName != ''){
+            whereSql += ' and Name Like ' + '\'%' + SearchName + '%\' ';
+        }
+
+        if(SearchCode != null && SearchCode != ''){
+          whereSql += 'and Code__c like ' + '\'%' + SearchCode + '%\' ';
+        }
+
+        searchSql = searchSql + whereStr + whereSql;
+
+        searchSql += ' order by Code__c limit 500';
+
+        cl = Database.query(searchSql);
+
+        Map<String,QELine> selectedQELineMap = new Map<String,QELine>();
+        if (activities.size() >0 ) {
+            for (QELine  q :activities) {
+                if (q.isSelected == true) {
+                    selectedQELineMap.put(q.setProductidFull, q);
+                } 
+            }
+        }
+
+        for(productSet__c psl : cl){
+            
+            if (!setNameAndSetQtyMap.containsKey(psl.Name)) {
+                QELine a = new QELine(psl);
+                if (selectedQELineMap.containsKey(a.setProductidFull)) {
+                    continue;
+                } else {
+                    a.Quantity = 0 ;
+                    selectedQELineMap.put(a.setProductidFull, a);
+                }
+                
+            } else {
+                continue;
+            }
+            
+            
+        }
+        activities = selectedQELineMap.values();
+        return null;
+  }
+  public void SelectDone(){
+    setPFString = '';
+    String idAndQuantity ;
+
+    for (QELine arc :activities) {
+
+        if(arc.isSelected==true){
+            
+            if (arc.Quantity > 0) {
+                idAndQuantity = arc.setProductidFull +','+ arc.Quantity +','+ arc.Discount;
+                
+                if(String.isblank(setPFString)||setPFString==null){
+                    
+                    setPFString = idAndQuantity;
+                }else{
+                    
+                    setPFString = setPFString +';'+ idAndQuantity;
+                }
+            }
+            
+        }
+    }
+    
+  }
+
+    public class QELine {
+        public Boolean isSelected {get;set;}
+        public String setProductidFull { get; set; }
+        public Decimal Quantity { get; set; }
+        public Decimal QuantityReference { get; set; }
+        public Decimal Discount { get; set; }
+        public String Name { get; set; }       
+        public String Code { get; set; }
+
+        public QELine(productSet__c psl) {
+            isSelected = false;
+	        setProductidFull = psl.id;
+	        Name = psl.Name;
+            Code = psl.Code__c;
+	        
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SearchSetProductController.cls-meta.xml b/scr/classes/SearchSetProductController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SearchSetProductController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SearchSetProductControllerTest.cls b/scr/classes/SearchSetProductControllerTest.cls
new file mode 100644
index 0000000..c92ad59
--- /dev/null
+++ b/scr/classes/SearchSetProductControllerTest.cls
@@ -0,0 +1,106 @@
+@isTest
+private class SearchSetProductControllerTest {
+	
+	@isTest static void test_method_one() {
+		Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.ProductModels__c = true;
+        product1.ProductStatus__c = '1';
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        Product_Search__c ps = new Product_Search__c(Product__c = product1.Id);
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account user = new Account(
+            Name = '*',
+            FacilityName__c = 'user',
+            PostCode__c = '123456',
+            RecordTypeId = rectIE[0].Id
+        );
+        insert user;
+
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = user.Id,
+            StageName = 'Prospect Created',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            Machine_Parts__c = 'Machine',
+            Pricebook2Id = pricebook.Id
+        );
+        insert opp;
+         Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            SetName1__c = 'setname01',
+            SetQty1__c = 1
+        );
+        insert quo;
+        productSet__c proSet1 = new productSet__c();
+        proSet1.Code__c = 'IXP-7P2';
+        proSet1.Name = 'IXP-7P2';
+        proSet1.IsValid__c = true;
+        proSet1.Name = 'IXP-7P2';
+        insert proSet1;
+
+        productSet__c proSet2 = new productSet__c();
+        proSet2.Code__c = 'IXP-7P1SC';
+        proSet2.Name = 'IXP-7P1SC';
+        proSet2.IsValid__c = true;
+        proSet2.Name = 'IXP-7P1SC';
+        insert proSet2;
+        productSet__c proSet3 = new productSet__c();
+        proSet3.Code__c = 'IXSP-T7LED';
+        proSet3.Name = 'IXSP-T7LED';
+        proSet3.IsValid__c = true;
+        proSet3.Name = 'IXSP-T7LED';
+        insert proSet3;
+        //PageReference page = new PageReference('/apex/SearchProduct?oppId=' + opp.Id + '&val=product1');
+        //PageReference page = new PageReference('/apex/SearchSetProduct?Id=' + quo.Id );
+        PageReference page = new PageReference('/apex/SearchSetProduct?gainQuoteSetNameAndSetQty=IX73鍙屽眰鎵嬪姩%2C2%2C25%3BIX73鍙屽眰缂栫爜鏈烘灦%2C2%2C25%3BIX73鍙屽眰鎵嬪姩%2C2%2C25%3BIX73鍙屽眰缂栫爜鏈烘灦%2C2%2C25');
+        //PageReference page = new PageReference('/apex/SearchSetProduct??gainQuoteSetNameAndSetQty=');
+        
+        System.Test.setCurrentPage(page);
+        SearchSetProductController controller = new SearchSetProductController();
+        
+        controller.init();
+        controller.SearchName = 'IXSP-T7LED';
+        controller.SearchCode = 'IXSP-T7LED';
+        controller.serContact();
+        controller.SelectDone();
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/SearchSetProductControllerTest.cls-meta.xml b/scr/classes/SearchSetProductControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SearchSetProductControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SendEmailController.cls b/scr/classes/SendEmailController.cls
new file mode 100644
index 0000000..7025254
--- /dev/null
+++ b/scr/classes/SendEmailController.cls
@@ -0,0 +1,648 @@
+public without sharing class SendEmailController {
+
+    public Mail_Merge__c mail{get; set;}
+
+    public String id{get;set;}
+
+    public String openType{get;set;}
+
+    public String handleType{get;set;}
+
+    public String errorMessage{get;set;}
+
+    public Integer lineNum{get;set;}
+
+    public String fileId{get;set;}
+
+    public String type{get;set;}
+
+    public String typeid{get;set;}
+
+    public Integer allFileSize{get;set;}
+
+    public Attachment attachment{get;set;}
+
+    public List<Attachment> attachmentList{get;set;}
+
+    //SWO_Email_Member__c 杩欎釜瀵硅薄鍙槸涓轰簡鐢熸垚椤甸潰涓婄殑浜哄憳鏄庣粏琛�
+    // public List<SWO_Email_Member__c> lineDataList_new{get;set;}
+    public List<MemberLine> memberLineDatas{get;set;}
+    //鐢ㄤ簬鎺ユ敹浜哄憳鏌ユ壘椤甸潰鏌ユ壘杩斿洖鐨勬暟鎹�
+    public String memberName{get;set;}
+    //鐢ㄤ簬鎺ユ敹浜哄憳鏌ユ壘椤甸潰鏌ユ壘杩斿洖鐨勬暟鎹�
+    public String memberEmail{get;set;}
+    //鐢ㄤ簬鎺ユ敹浜哄憳鏌ユ壘椤甸潰鏌ユ壘杩斿洖鐨勬暟鎹�
+    public String memberId{get;set;}
+
+    public String baseUrl {get;set;}
+
+    public String name {get;set;}
+
+    public Boolean isOnClick{get;set;}
+
+
+    public List<String> toAddresses ;
+    public List<String> ccAddresses ;
+    public List<String> bccAddresses ;
+
+    public SendEmailController() {
+        id = System.currentPageReference().getParameters().get('id');
+        type = System.currentPageReference().getParameters().get('type');
+        typeid = System.currentPageReference().getParameters().get('typeid');
+        openType = System.currentPageReference().getParameters().get('openType');
+    }
+
+    public SendEmailController(ApexPages.StandardController stdController) {
+        id = System.currentPageReference().getParameters().get('id');
+        type = System.currentPageReference().getParameters().get('type');
+        typeid = System.currentPageReference().getParameters().get('typeid');
+        openType = System.currentPageReference().getParameters().get('openType');
+    }
+
+    public void init(){
+        //URL鑾峰彇
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+
+
+        attachment = new Attachment();
+        mail = new Mail_Merge__c();
+        mail.RECORD__c = typeid;
+        mail.RECORD_TYPE__c = type;
+        memberLineDatas = new List<MemberLine>();
+        if(id == null){
+            isOnClick = false;
+            mail.FROM__c = UserInfo.getUserEmail();
+            mail.TYPE__c = 'send';        
+            MemberLine member = new MemberLine();
+            member.lineNum = 0;
+            member.to = true;
+            memberLineDatas.add(member);
+            // SWO涓嶆槸鎵瑰噯鍚庣姸鎬佷笉鑳藉彂閫侀偖浠�
+            if ('Quotes'.equals(mail.RECORD_TYPE__c)) {
+                List<Quotes__c> quotesList = new List<Quotes__c>();
+                quotesList = [SELECT  Id, Name, BILLING_SCHEDULE__c, BILL_TO__c, SHIP_TO__c, BILL_TO_SELECT__c,SWOStatusMark__c  FROM Quotes__c WHERE Id = :typeid];
+                
+                if (quotesList.size() > 0 ) {
+                    if (quotesList[0].SWOStatusMark__c < 2) {
+                        isOnClick = true;
+                    }    
+                }
+            }
+        }else{
+            mail = [select id,send__c,MESSAGE__c,SUBJECT__c,TYPE__c,FROM__c,DATE__c,RECIPIENT__c,CC__c,BCC__c,RECORD__c,RECORD_TYPE__c,toName__c,ccName__c,bccName__c,ALL_MEMBER__c,ALL_MEMBER_NAME__c,ALL_MEMBER_TYPE__c,EMAIL_SENT__c,SWO__c,CaseF__c,Quotes__c from Mail_Merge__c where id =:id];
+            //mail.TYPE__c == 'reply' 閭欢涓哄洖澶嶉偖浠� 鎴栬�呮槸绯荤粺鑷姩鍙戦�佺殑閭欢
+            //EMAIL_SENT__c =='YES' 閭欢宸插彂閫�
+            if(mail.TYPE__c == 'reply' || mail.EMAIL_SENT__c =='YES'){
+                //isOnClick = true; 鍦ㄩ偖浠堕〉闈㈡墍鏈夌殑鎸夐挳閮戒笉鍙偣鍑�
+                isOnClick = true;
+            }
+            type = mail.RECORD_TYPE__c;
+            if(mail.RECORD_TYPE__c == 'SWO') typeid = mail.SWO__c;
+            if(mail.RECORD_TYPE__c == 'Case') typeid = mail.CaseF__c;
+            if(mail.RECORD_TYPE__c == 'Quotes') typeid = mail.Quotes__c;
+            mail.RECORD__c = typeid;
+            typeid = mail.RECORD__c;
+            List<String> allEmails = String.isNotBlank(mail.ALL_MEMBER__c)?mail.ALL_MEMBER__c.split(';'):new List<String>();
+            List<String> allName = String.isNotBlank(mail.ALL_MEMBER_NAME__c)?mail.ALL_MEMBER_NAME__c.split(';'):new List<String>();
+            List<String> allType = String.isNotBlank(mail.ALL_MEMBER_TYPE__c)?mail.ALL_MEMBER_TYPE__c.split(';'):new List<String>();
+            
+            if(String.isNotBlank(openType) && openType == 'Reply' && mail.EMAIL_SENT__c == 'YES'){
+                if(mail.EMAIL_SENT__c == 'YES' || mail.TYPE__c == 'reply'){
+                    mail.Id = null;
+                    mail.EMAIL_SENT__c = 'NO';
+                }
+                mail.TYPE__c = 'send';
+                isOnClick = false;
+                //mail.DATE__c = Datetime.now();
+                if(String.isNotBlank(UserInfo.getUserEmail()) && !UserInfo.getUserEmail().equals(mail.FROM__c)){
+                    MemberLine member_line = new MemberLine();
+                    member_line.emailAddress = mail.FROM__c;
+                    member_line.name = '';
+                    member_line.to = true;
+                    member_line.cc = false;
+                    member_line.bcc = false;
+                    member_line.lineNum = 0;
+                    memberLineDatas.add(member_line);
+                }
+                isOnClick = false;
+                String mailToAddressName = '';
+                String mailCcAdressName = '';
+                if(allEmails.size() != 0){
+                    for(Integer i = 0 ; i<allEmails.size() ; i++){
+                        if(allType[i] == 'to'){
+                            mailToAddressName += allEmails[i]+'锛�';
+                        }
+                        if(allType[i] == 'cc'){
+                            mailCcAdressName += allEmails[i]+'锛�';
+                        }
+                    }
+                }
+                String replyEmailHead = '';
+                replyEmailHead    = '\n\n\n\n';
+                replyEmailHead    += '-------------閭欢鍘熶欢--------------\n';
+                replyEmailHead    += '鍙戜欢浜猴細' + mail.FROM__c + ';\n';
+                replyEmailHead    += '鍙戜欢鏃堕棿锛�' + mail.DATE__c.addHours(8) + ';\n';
+                replyEmailHead    += '鏀朵欢浜猴細' + mailToAddressName + '\n';
+                replyEmailHead    += '鎶勯�侊細' + mailCcAdressName + '\n';
+                replyEmailHead    += '涓婚锛�' + mail.SUBJECT__c + ';\n\n';
+                mail.MESSAGE__c   = replyEmailHead+(String.isNotBlank(mail.MESSAGE__c)?mail.MESSAGE__c:'');
+                
+                if(String.isNotBlank(mail.SUBJECT__c) && !mail.SUBJECT__c.replaceAll(' ','').contains('鍥炲')){
+                    mail.SUBJECT__c = '鍥炲:'+mail.SUBJECT__c;
+                }
+            }
+
+            if(allEmails.size() != 0){
+                for(Integer i = 0 ; i<allEmails.size() ; i++){
+                    MemberLine member_line = new MemberLine();
+                    member_line.emailAddress = allEmails[i];
+                    if(String.isNotBlank(openType) && openType == 'Reply'){
+                        if(allEmails[i].equals(UserInfo.getUserEmail())){
+                            continue;
+                        }
+                    }
+                    //鎷嗗垎name鏃� 濡傛灉鏄媶鍒嗗嚭鈥�-鈥濓紝鍒檔ame涓虹┖
+                    member_line.name = allName[i]=='-'?'':allName[i];
+                    if(allType[i] == 'to'){
+                        member_line.to = true;
+                        member_line.cc = false;
+                        member_line.bcc = false;
+                    }
+                    if(allType[i] == 'cc'){
+                        member_line.to = false;
+                        member_line.cc = true;
+                        member_line.bcc = false;
+                    }
+                    if(allType[i] == 'bcc'){
+                        member_line.to = false;
+                        member_line.cc = false;
+                        member_line.bcc = true;
+                    }
+                    member_line.lineNum = i+memberLineDatas.size();
+                    memberLineDatas.add(member_line);
+                }
+            }else{
+                 /*MemberLine member_line = new MemberLine();
+                 member_line.lineNum = 0;
+                 member_line.to = true;
+                 memberLineDatas.add(member_line);*/
+                 addLine();
+            }
+            attachmentList = [select Id,Name,CreatedDate,BodyLength,Body from Attachment where ParentId=:id];
+            /*if(String.isNotBlank(openType) && openType == 'Reply'){
+                attachmentList.clear();
+            }*/
+        }
+        mail.DATE__c = Datetime.now();
+        mail.FROM__c = UserInfo.getUserEmail();
+    }
+
+    public PageReference SendEmail(){
+        save();
+        // System.debug('杩涘叆閭欢鍙戦��');
+        // List<String> toAddresses = new List<String>();
+        // List<String> ccAddresses = new List<String>();
+        // List<String> bccAddresses = new List<String>();
+        // mail.RECIPIENT__c = '';
+        // mail.toName__c = '';
+        // mail.CC__c = '';
+        // mail.ccName__c = '';
+        // mail.BCC__c = '';
+        // mail.bccName__c = '';
+        // mail.ALL_MEMBER__c = '';
+        // mail.ALL_MEMBER_NAME__c = '';
+        // mail.ALL_MEMBER_TYPE__c = '';
+        // if(memberLineDatas!=null && memberLineDatas.size()!=0){
+        //     System.debug('memberLineDatas--->'+memberLineDatas);
+        //     //鎷兼帴閭欢鏀朵欢淇℃伅
+        //     for(MemberLine line : memberLineDatas){
+        //         if(String.isNotBlank(line.emailAddress)){
+        //             mail.ALL_MEMBER__c = mail.ALL_MEMBER__c + line.emailAddress + ';';
+        //             //鎵嬪姩杈撳叆閭欢鍦板潃鏃� name浼氱┖ 鐢�-鍗犱綅淇濆瓨 鐢ㄤ簬鍒濆鍖栨椂鎷嗗垎
+        //             mail.ALL_MEMBER_NAME__c = mail.ALL_MEMBER_NAME__c + (String.isNotBlank(line.name) ? line.name : '-') + ';';
+        //             if(line.to){
+        //                 if(String.isNotBlank(line.emailAddress)){
+        //                     toAddresses.add(line.emailAddress);
+        //                     mail.RECIPIENT__c = mail.RECIPIENT__c + line.emailAddress + ';';
+        //                     mail.toName__c = mail.toName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
+        //                     mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'to;';
+        //                 }
+        //             }
+        //             if(line.cc){
+        //                 if(String.isNotBlank(line.emailAddress)){
+        //                     ccAddresses.add(line.emailAddress);
+        //                     mail.CC__c = mail.CC__c + line.emailAddress + ';';
+        //                     mail.ccName__c = mail.ccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
+        //                     mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'cc;';
+        //                 }
+        //             }
+        //             if(line.bcc){
+        //                 if(String.isNotBlank(line.emailAddress)){
+        //                     bccAddresses.add(line.emailAddress);
+        //                     mail.BCC__c = mail.BCC__c + line.emailAddress + ';';
+        //                     mail.bccName__c = mail.bccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
+        //                     mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'bcc;';
+        //                 }
+        //             }
+        //         }
+        //     }
+        // }
+        // if('SWO'.equals(mail.RECORD_TYPE__c)){
+        //     mail.SWO__c = mail.RECORD__c;
+        //     SWO__c swo = [select Id,Name from SWO__c where Id=:mail.RECORD__c];
+        //     name = 'SWO:'+swo.Name;
+        // }
+        // if('Case'.equals(mail.RECORD_TYPE__c)){
+        //     mail.CaseF__c = mail.RECORD__c;
+        //     User_FaultInfo__c caseInfo = [select Id,Name from User_FaultInfo__c where Id=:mail.RECORD__c];
+        //     name = 'Case:'+caseInfo.Name;
+        // }
+        // if('Quotes'.equals(mail.RECORD_TYPE__c)){
+        //     mail.Quotes__c = mail.RECORD__c;
+        //     Quotes__c quotes = [select Id,Name from Quotes__c where Id=:mail.RECORD__c];
+        //     name = 'Quotes:'+quotes.Name;
+        // }
+        // //鍒ゆ柇鏄惁鏃剁偣鍑诲彂閫佹寜閽紝杩涘叆鎻愪氦鏂规硶
+        // if(String.isNotBlank(handleType) && !'send'.equals(handleType)){
+        //     mail.EMAIL_SENT__c = 'NO';
+        //     upsert mail;
+        //     id = mail.Id;
+        // }
+        System.debug('閭欢鏍囬mail.subject'+mail.SUBJECT__c);
+        System.debug('閭欢Name'+mail.toName__c);
+        errorMessage = '';
+        System.debug('handleType:'+handleType);
+        //鐐瑰嚮鍙戦�佹寜閽紝骞朵笖閭欢鎺ユ敹鍦板潃涓嶄负绌� 鍙戦�侀偖浠�
+        if(String.isNotBlank(handleType) && 'send'.equals(handleType)){
+            if(toAddresses.size()!=0){
+                mail.DATE__c = Datetime.now();
+                if(String.isNotBlank(mail.SUBJECT__c) && String.isNotBlank(mail.MESSAGE__c)){
+                    //鍏宠仈淇℃伅鎷煎叆鍒版爣棰樹腑渚涳紝鍥炲閭欢鍏宠仈浣跨敤
+                    //mail.SUBJECT__c = mail.SUBJECT__c;
+                    mail.Name = mail.SUBJECT__c;
+                    mail.SUBJECTCOPY__c = mail.SUBJECT__c + '~' + (name!=null ? name : '');
+                    System.debug('鏍囬锛�'+mail.SUBJECTCOPY__c);
+                    Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
+                    sendMail.setToAddresses(toAddresses);
+                    sendMail.setBccAddresses(bccAddresses);
+                    //sendMail.setReplyTo('');
+                    sendMail.setSubject(mail.SUBJECTCOPY__c);
+                    sendMail.setPlainTextBody(mail.MESSAGE__c);
+                    sendMail.setBccSender(false);
+                    sendMail.setUseSignature(false);
+                    //濡傛灉缁欏鎴峰彂閫佹姤浠峰崟SWO闇�瑕佹姄鍙栧彂閫佹椂闂� 鏄惁鎶撳彇鏃堕棿鐨勬爣璁�
+                    Boolean isSaveTime = false;
+                    if(attachmentList!=null&&attachmentList.size()!=0){
+                        List<Messaging.EmailFileAttachment> sendMailFileList = new List<Messaging.EmailFileAttachment>();
+                        for(Attachment att : attachmentList){
+                            Messaging.EmailFileAttachment sendMailFile = new Messaging.EmailFileAttachment();
+                            sendMailFile.setBody(att.Body);
+                            sendMailFile.setFileName(att.Name);
+                            //鎶ヤ环椤甸潰鍙戦�侀偖浠讹紝濡傛灉鍖呭惈鈥滄姤浠峰崟鈥濆紑澶寸殑闄勪欢鍒橲WO闇�瑕佹姄鍙栧綋鍓嶆椂闂�
+                            if('Quotes'.equals(mail.RECORD_TYPE__c) && att.Name.startsWith('鎶ヤ环鍗�')){
+                                // isSaveTime = true;
+                                continue;
+                            }
+                            sendMailFileList.add(sendMailFile);
+                        }
+                        if (!isSaveTime && 'Quotes'.equals(mail.RECORD_TYPE__c)) {
+                            sendMailFileList.add(SendEmailaddPDF());
+                            isSaveTime = true;
+                        }
+                        sendMail.setFileAttachments(sendMailFileList);
+                    } else {
+                        List<Messaging.EmailFileAttachment> sendMailFileList = new List<Messaging.EmailFileAttachment>();
+                        if ('Quotes'.equals(mail.RECORD_TYPE__c)) {
+                            sendMailFileList.add(SendEmailaddPDF());
+                            isSaveTime = true;
+                        }
+                        sendMail.setFileAttachments(sendMailFileList);
+                        isSaveTime = true;
+                    }
+                    //涓夌閭欢瀹㈡埛鍥炲鏃讹紝鍥炲鍒颁笉鍚岀殑閭欢鏈嶅姟鐩戝惉涓��
+                    if('SWO'.equals(mail.RECORD_TYPE__c)){
+                        SWO__c swo = new SWO__c();
+                        swo.Id =  mail.RECORD__c;
+                        //鏍囪璺宠繃閭欢鍥炲鐩戝惉
+                        swo.notSaveEmail__c = true;
+                        update swo;
+                    }
+                    if('Case'.equals(mail.RECORD_TYPE__c)){
+                        User_FaultInfo__c caseInfo = new User_FaultInfo__c();
+                        caseInfo.Id = mail.RECORD__c;
+                        //鏍囪璺宠繃閭欢鍥炲鐩戝惉
+                        caseInfo.notSaveEmail__c = true;
+                        update caseInfo;
+                    }
+                    if('Quotes'.equals(mail.RECORD_TYPE__c)){
+                        Quotes__c quotes = [select Id,Name,notSaveEmail__c,SWO__c,SWO__r.Quotation_send__c from Quotes__c where Id=:mail.RECORD__c];
+                       /* Quotes__c quotes = new Quotes__c();
+                        quotes.Id = mail.RECORD__c;*/
+                        //鏍囪璺宠繃閭欢鍥炲鐩戝惉
+                        quotes.notSaveEmail__c = true;
+                        update quotes;
+                        if (isSaveTime && String.isNotBlank(quotes.SWO__c) && quotes.SWO__r.Quotation_send__c == null) {
+                            SWO__c swo = new SWO__c();
+                            swo.Id = quotes.SWO__c;
+                            swo.Quotation_send__c = Datetime.now();
+                            update swo;
+                        }    
+                    }
+
+                
+                    //ccAddresses.add('email@sqtxllncwbyghx9lphlh50gefur2jyyj95io4r968llbumzh7.0t-8aptuaq.cs112.apex.sandbox.salesforce.com');
+                    ccAddresses.add(System.label.EmailComeBackListen);
+                    ccAddresses.add('dai_Prectech@olympus.com.cn');
+                    ccAddresses.add('Xin_Prectech@olympus.com.cn');
+
+                    sendMail.setCcAddresses(ccAddresses);
+                    system.debug('=====sendMail---->'+sendMail);
+                    Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
+                    for (Integer i = 0; i < result_list.size(); i++) {
+                        if (result_list[i].success == true ) {
+                            system.debug('=====send mail success');
+                        } else {
+                            system.debug('=====send mail error:' + result_list[i].errors[0].message);
+                        }
+                    }
+                    mail.EMAIL_SENT__c = 'YES';
+                    upsert mail;
+                    // 杩斿洖鐐瑰嚮閭欢椤甸潰
+                    PageReference ref = new Pagereference('/'+mail.RECORD__c+'?type=mail');
+                    ref.setRedirect(true);
+                    return ref;
+                }else{
+                    errorMessage='閭欢鏍囬鍜屼俊鎭笉鍙负绌猴紒';
+                }
+            }else{
+                errorMessage='蹇呴』鑷冲皯鏈変竴涓敹浠朵汉锛�';
+            }
+        }
+        return null;
+    }
+
+    public void save() {
+        toAddresses = new List<String>();
+        ccAddresses = new List<String>();
+        bccAddresses = new List<String>();
+
+        // System.debug('杩涘叆閭欢鍙戦��');
+        // List<String> toAddresses = new List<String>();
+        // List<String> ccAddresses = new List<String>();
+        // List<String> bccAddresses = new List<String>();
+        mail.RECIPIENT__c = '';
+        mail.toName__c = '';
+        mail.CC__c = '';
+        mail.ccName__c = '';
+        mail.BCC__c = '';
+        mail.bccName__c = '';
+        mail.ALL_MEMBER__c = '';
+        mail.ALL_MEMBER_NAME__c = '';
+        mail.ALL_MEMBER_TYPE__c = '';
+        if(memberLineDatas!=null && memberLineDatas.size()!=0){
+            System.debug('memberLineDatas--->'+memberLineDatas);
+            //鎷兼帴閭欢鏀朵欢淇℃伅
+            for(MemberLine line : memberLineDatas){
+                if(String.isNotBlank(line.emailAddress)){
+                    mail.ALL_MEMBER__c = mail.ALL_MEMBER__c + line.emailAddress + ';';
+                    //鎵嬪姩杈撳叆閭欢鍦板潃鏃� name浼氱┖ 鐢�-鍗犱綅淇濆瓨 鐢ㄤ簬鍒濆鍖栨椂鎷嗗垎
+                    mail.ALL_MEMBER_NAME__c = mail.ALL_MEMBER_NAME__c + (String.isNotBlank(line.name) ? line.name : '-') + ';';
+                    if(line.to){
+                        if(String.isNotBlank(line.emailAddress)){
+                            toAddresses.add(line.emailAddress);
+                            mail.RECIPIENT__c = mail.RECIPIENT__c + line.emailAddress + ';';
+                            mail.toName__c = mail.toName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
+                            mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'to;';
+                        }
+                    }
+                    if(line.cc){
+                        if(String.isNotBlank(line.emailAddress)){
+                            ccAddresses.add(line.emailAddress);
+                            mail.CC__c = mail.CC__c + line.emailAddress + ';';
+                            mail.ccName__c = mail.ccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
+                            mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'cc;';
+                        }
+                    }
+                    if(line.bcc){
+                        if(String.isNotBlank(line.emailAddress)){
+                            bccAddresses.add(line.emailAddress);
+                            mail.BCC__c = mail.BCC__c + line.emailAddress + ';';
+                            mail.bccName__c = mail.bccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
+                            mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'bcc;';
+                        }
+                    }
+                }
+            }
+        }
+        if('SWO'.equals(mail.RECORD_TYPE__c)){
+            mail.SWO__c = mail.RECORD__c;
+            SWO__c swo = [select Id,Name from SWO__c where Id=:mail.RECORD__c];
+            name = 'SWO:'+swo.Name;
+        }
+        if('Case'.equals(mail.RECORD_TYPE__c)){
+            mail.CaseF__c = mail.RECORD__c;
+            User_FaultInfo__c caseInfo = [select Id,Name from User_FaultInfo__c where Id=:mail.RECORD__c];
+            name = 'Case:'+caseInfo.Name;
+        }
+        if('Quotes'.equals(mail.RECORD_TYPE__c)){
+            mail.Quotes__c = mail.RECORD__c;
+            Quotes__c quotes = [select Id,Name from Quotes__c where Id=:mail.RECORD__c];
+            name = 'Quotes:'+quotes.Name;
+        }
+        //鍒ゆ柇鏄惁鏃剁偣鍑诲彂閫佹寜閽紝杩涘叆鎻愪氦鏂规硶
+        if(String.isNotBlank(handleType) && !'send'.equals(handleType)){
+            mail.EMAIL_SENT__c = 'NO';
+            upsert mail;
+            id = mail.Id;
+        }
+
+        // return mail;
+    }
+
+    public void addLine(){
+        MemberLine member = new MemberLine();
+        member.lineNum = memberLineDatas.size();
+        member.memberId = '';
+        member.name = '';
+        member.emailAddress = '';
+        member.to = true;
+        member.cc = false;
+        member.bcc = false;
+        memberLineDatas.add(member);
+    }
+
+    public void deLine(){
+        //淇濊瘉椤甸潰涓婃渶灏戞湁涓�琛屼汉鍛樹俊鎭爮
+        if(memberLineDatas.size() == 1){
+            memberLineDatas[0].memberId = '';
+            memberLineDatas[0].emailAddress = '';
+            memberLineDatas[0].name = '';
+            memberLineDatas[0].to = true;
+            memberLineDatas[0].cc = false;
+            memberLineDatas[0].bcc = false;
+            return;
+        }
+        memberLineDatas.remove(lineNum);
+        //鍒犻櫎涓�琛屼汉鍛樹俊鎭紝閲嶆柊缁欒鏍囪祴鍊�
+        for(Integer i = 0 ; i<memberLineDatas.size() ; i++){
+            memberLineDatas[i].lineNum = i;
+        }
+    }
+    
+    public void kong(){
+        System.debug('绌烘彁浜�');
+    }
+
+    public PageReference uploadFile(){
+        handleType = 'uploadFile';
+        SendEmail();
+        PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + id + '&retURL=%2Fapex/SendEmail?id=' + id + '&type=' + type + '&typeid='+typeid);
+        ref.setRedirect(true);
+        return ref;
+    }
+
+    public void uploadFileS(){
+        handleType = 'uploadFile';
+        save();
+        
+    }
+
+    public PageReference RefreshPage(){
+        PageReference ref = new Pagereference('/apex/SendEmail?id=' + id + '&type=' + type + '&typeid='+typeid);
+        ref.setRedirect(true);
+        return ref;
+    }
+
+    public PageReference seeFile(){
+        if(String.isNotBlank(fileId)){
+            for(Integer i = 0; i< attachmentList.size();i++){
+                if(fileId.equals(attachmentList[i].Id)){
+                    PageReference acctPage = new ApexPages.StandardController(attachmentList[i]).view();
+                    acctPage.setRedirect(true);
+                    return acctPage;
+                }
+            }
+        }
+        return null;
+    }
+
+    public void deleteFile(){
+        System.debug('fileId'+fileId);
+        if(String.isNotBlank(fileId)){
+            for(Integer i = 0; i< attachmentList.size();i++){
+                if(fileId.equals(attachmentList[i].Id)){
+                    System.debug('id'+attachmentList[i].Id);
+                    System.debug('fileId'+fileId);
+                    delete attachmentList[i];
+                    attachmentList.remove(i);
+                    break;
+                }
+            }
+        }
+    }
+
+    public void addPDF(){
+        handleType = 'uploadFile';
+        SendEmail();
+        PageReference pdfPage ;
+        pdfPage = new PageReference('/apex/QuotesPDF?id='+typeid);
+        // pdfPage.getParameters().put('id',laId);
+        pdfPage.setRedirect(false);
+        Blob b = pdfPage.getContentAsPDF();
+        // attach the pdf to the Opportunity
+        Attachment attach = new Attachment();
+        attach.Body = b;
+        attach.Name = '鎶ヤ环鍗�.pdf';
+        System.debug('id--'+ id );
+        attach.ParentId = id;
+        insert attach;
+        attachmentList = [select Id,Name,CreatedDate,BodyLength,Body from Attachment where ParentId=:id];
+
+    }
+
+    public Messaging.EmailFileAttachment SendEmailaddPDF(){
+        handleType = 'uploadFile';
+        
+        if (String.isBlank(id)) {
+            SendEmail();   
+        }
+        
+        PageReference pdfPage ;
+        pdfPage = new PageReference('/apex/QuotesPDF?id='+typeid);
+        // pdfPage.getParameters().put('id',laId);
+        pdfPage.setRedirect(false);
+        Blob b = pdfPage.getContentAsPDF();
+        // attach the pdf to the Opportunity
+        Attachment attach = new Attachment();
+        attach.Body = b;
+        attach.Name = '鎶ヤ环鍗�.pdf';
+        System.debug('id--'+ id );
+        attach.ParentId = id;
+        insert attach;
+        Messaging.EmailFileAttachment sendMailFile = new Messaging.EmailFileAttachment();
+        sendMailFile.setBody(attach.Body);
+        sendMailFile.setFileName(attach.Name);
+        return sendMailFile;
+        // attachmentList = [select Id,Name,CreatedDate,BodyLength,Body from Attachment where ParentId=:id];
+
+    }
+
+    //涓婁紶闄勪欢
+    @RemoteAction
+    public static String AddAttachment(List<String> nameList, List<String> typeList, List<String> bodyList, String parentId) {
+        String operateResult;
+        if (nameList.size() > 0) {
+            List<Attachment> insertAttachmentList = new List<Attachment>();
+            for (Integer num = 0; num < nameList.size(); num ++ ) {
+                Attachment tmpAttachment = new Attachment();
+                tmpAttachment.Name = nameList[num];
+                tmpAttachment.Body = EncodingUtil.base64Decode(bodyList[num]);
+                tmpAttachment.ParentId = parentId;
+                tmpAttachment.ContentType = typeList[num];
+                insertAttachmentList.add(tmpAttachment);
+            }
+
+            try {
+                insert insertAttachmentList;
+                operateResult = '鏂囦欢涓婁紶鎴愬姛';
+            } catch (Exception e) {
+                operateResult = '鏂囦欢涓婁紶澶辫触';
+            }
+        }
+
+
+        return operateResult;
+    }
+    public void addMemberData(){
+        System.debug(memberName);
+        System.debug('memberEmail:'+memberEmail);
+        System.debug(memberId);
+        if(lineNum!=null){
+            if(String.isNotBlank(memberName)){
+                memberLineDatas[lineNum].name = memberName;
+            }
+            if(String.isNotBlank(memberEmail)){
+                memberLineDatas[lineNum].emailAddress = memberEmail;
+            }
+            if(String.isNotBlank(memberId)){
+                memberLineDatas[lineNum].memberId = memberId;
+            }
+        }
+    }
+
+    public class MemberLine{
+        public String memberId{get;set;}
+        public String emailAddress{get;set;}
+        public String name{get;set;}
+        public Boolean to{get;set;}
+        public Boolean cc{get;set;}
+        public Boolean bcc{get;set;}
+        public Integer lineNum{get;set;}
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SendEmailController.cls-meta.xml b/scr/classes/SendEmailController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SendEmailController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SendEmailControllerTest.cls b/scr/classes/SendEmailControllerTest.cls
new file mode 100644
index 0000000..524bc5d
--- /dev/null
+++ b/scr/classes/SendEmailControllerTest.cls
@@ -0,0 +1,166 @@
+@isTest
+private class SendEmailControllerTest {
+    static testMethod void Add() {
+
+        User_FaultInfo__c ca = new User_FaultInfo__c();
+        ca.ORIGIN__c = 'Web';
+        ca.SUBJECT__c = 'test';
+        ca.OFFICE_OWNER__c = 'Beijing';
+        ca.Product_Type__c = 'NDT';
+        ca.TYPE__c = 'Service';
+        ca.LOGISTICS_SHIPMENT_TYPE__c = 'Domestic';
+        ca.STATUS__c = 'Not Started';
+        ca.PRIORITY__c = 'High';
+        insert ca;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        swo.StatusMark__c = 2;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        insert quotes;
+
+        Mail_Merge__c  mailMerge = new Mail_Merge__c(); 
+        mailMerge.RECORD__c = swo.Id;
+        mailMerge.ALL_MEMBER__c = '1234Test@olympus.inv;1234Test1@olympus.inv;1234Test2@olympus.inv;';
+        mailMerge.ALL_MEMBER_NAME__c = 'Test01;Test02;Test03;';
+        mailMerge.ALL_MEMBER_TYPE__c = 'to;cc;bcc;';
+        mailMerge.RECORD_TYPE__c = 'SWO';
+        mailMerge.SWO__c = swo.Id;
+        mailMerge.CaseF__c = ca.Id;
+        mailMerge.Quotes__c = quotes.Id;
+        mailMerge.SUBJECT__c = 'TEST';
+        mailMerge.MESSAGE__c = 'TEST';
+        mailMerge.EMAIL_SENT__c = 'NO';
+        mailMerge.TYPE__c = 'reply';
+        mailMerge.DATE__c = Datetime.now();
+        insert mailMerge;
+
+        Attachment att = new Attachment(
+            Name = 'test.pdf',
+            parentId = mailMerge.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+        Attachment att1 = new Attachment(
+            Name = 'test1.pdf',
+            parentId = mailMerge.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att1;
+
+        PageReference page = new PageReference('/apex/SendEmail?type=SWO&typeid='+swo.Id);
+        System.Test.setCurrentPage(page);
+        SendEmailController controller = new SendEmailController(new ApexPages.StandardController(mailMerge));
+        controller.init();
+        controller.SendEmail();
+
+        page = new PageReference('/apex/SendEmail?id='+mailMerge.Id+'&type=SWO&typeid='+swo.Id+'&openType=Reply');
+        System.Test.setCurrentPage(page);
+        controller = new SendEmailController(new ApexPages.StandardController(mailMerge));
+        controller.init();
+        controller.SendEmail();
+
+        PageReference page1 = new PageReference('/apex/SendEmail?id='+mailMerge.Id+'&type=SWO&typeid='+swo.Id);
+        System.Test.setCurrentPage(page1);
+        SendEmailController controller1 = new SendEmailController(new ApexPages.StandardController(mailMerge));
+        controller1.init();
+        controller1.addLine();
+        controller1.lineNum = 0;
+        controller1.deLine();
+        controller1.deLine();
+        controller1.deLine();
+        controller1.deLine();
+        controller1.uploadFile();
+        controller1.fileId = att1.Id;
+        controller1.seeFile();
+        controller1.deleteFile();
+        controller1.handleType = 'send';
+        controller1.SendEmail();
+        controller1.lineNum = 0;
+        controller1.memberName = 'test';
+        controller1.memberEmail = '1234Test@olympus.inv';
+        controller1.memberId = 'test';
+        controller1.addMemberData();
+        mailMerge.SUBJECT__c = '';
+        update mailMerge;
+        controller1.SendEmail();
+        mailMerge.SUBJECT__c = 'Test';
+        update mailMerge;
+        controller1.SendEmail();
+
+        mailMerge.RECORD__c = ca.Id;
+        mailMerge.RECORD_TYPE__c = 'Case';
+        update mailMerge;
+        PageReference page2 = new PageReference('/apex/SendEmail?id='+mailMerge.Id+'&type=Case&typeid='+ca.Id);
+        System.Test.setCurrentPage(page2);
+        SendEmailController controller2 = new SendEmailController(new ApexPages.StandardController(mailMerge));
+        controller2.init();
+        controller2.handleType = 'send';
+        controller2.SendEmail();
+    }
+
+    static testMethod void quoteSendEmail() {
+        User_FaultInfo__c ca = new User_FaultInfo__c();
+        ca.ORIGIN__c = 'Web';
+        ca.SUBJECT__c = 'test';
+        ca.OFFICE_OWNER__c = 'Beijing';
+        ca.Product_Type__c = 'NDT';
+        ca.TYPE__c = 'Service';
+        ca.LOGISTICS_SHIPMENT_TYPE__c = 'Domestic';
+        ca.STATUS__c = 'Not Started';
+        ca.PRIORITY__c = 'High';
+        insert ca;
+
+        SWO__c swo = new SWO__c();
+        swo.Name = 'Test';
+        swo.QUANTITY__c = 22;
+        swo.ESTIMATED_LABOUR_HOURS__c = 22;
+        swo.LABOUR_RATE__c = 22;
+        swo.StatusMark__c = 2;
+        insert swo;
+
+        Quotes__c quotes = new Quotes__c();
+        quotes.SWO__c = swo.Id;
+        quotes.QuotesType__c = '闆朵欢鎶ヤ环鍗�';
+        insert quotes;
+
+        Mail_Merge__c  mailMerge = new Mail_Merge__c(); 
+        mailMerge.RECORD__c = quotes.Id;
+        mailMerge.ALL_MEMBER__c = '1234Test@olympus.inv;1234Test1@olympus.inv;1234Test2@olympus.inv;';
+        mailMerge.ALL_MEMBER_NAME__c = 'Test01;Test02;Test03;';
+        mailMerge.ALL_MEMBER_TYPE__c = 'to;cc;bcc;';
+        mailMerge.RECORD_TYPE__c = 'Quotes';
+        mailMerge.SWO__c = swo.Id;
+        mailMerge.CaseF__c = ca.Id;
+        mailMerge.Quotes__c = quotes.Id;
+        mailMerge.SUBJECT__c = 'TEST';
+        mailMerge.MESSAGE__c = 'TEST';
+        mailMerge.EMAIL_SENT__c = 'YES';
+        mailMerge.TYPE__c = 'reply';
+        mailMerge.DATE__c = Datetime.now();
+        insert mailMerge;
+
+        PageReference page = new PageReference('/apex/SendEmail?type=Quotes&typeid='+quotes.Id);
+        System.Test.setCurrentPage(page);
+        SendEmailController controller = new SendEmailController(new ApexPages.StandardController(mailMerge));
+        controller.init();
+        controller.uploadFileS();
+        controller.RefreshPage();
+        controller.SendEmail();
+        // controller.addPDF();
+        PageReference page2 = new PageReference('apex/SendEmail?id='+mailMerge.Id+'&type=Quotes&typeid='+quotes.Id+'&openType=Reply');
+        System.Test.setCurrentPage(page2);
+        SendEmailController controller2 = new SendEmailController();
+        controller2.init();
+        controller2.SendEmail();
+
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/SendEmailControllerTest.cls-meta.xml b/scr/classes/SendEmailControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SendEmailControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/ServiceSummaryHandler.cls b/scr/classes/ServiceSummaryHandler.cls
new file mode 100644
index 0000000..fdfd4ca
--- /dev/null
+++ b/scr/classes/ServiceSummaryHandler.cls
@@ -0,0 +1,44 @@
+public without sharing class ServiceSummaryHandler {
+    public static String recordtypeId = '';
+    public static void CreateCase(List<ServiceSummary__c> newList, Map<Id, ServiceSummary__c> newMap, List<ServiceSummary__c> oldList, Map<Id, ServiceSummary__c> oldMap) {
+        recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Case' and DeveloperName = 'Draft'].id;
+        List<Case> upsertCaseList = new List<Case>();
+        for (ServiceSummary__c newServiceSummary : newList) {
+            ServiceSummary__c oldServiceSummary = oldMap == null ? null : oldMap.get(newServiceSummary.Id);
+            if (oldServiceSummary != null) {
+                if (newServiceSummary.IndividualCase__c != oldServiceSummary.IndividualCase__c && newServiceSummary.IndividualCase__c) {
+                    upsertCaseList.add(CaseDate(newServiceSummary));
+                }
+            } else  if (newServiceSummary.IndividualCase__c) {
+                upsertCaseList.add(CaseDate(newServiceSummary));
+            }
+            
+        }
+
+        if (upsertCaseList.size() > 0 ) {
+            upsert upsertCaseList;
+        }
+
+    }
+
+
+    public static Case CaseDate(ServiceSummary__c serviceSummary) {
+
+        Case newCase = new Case();
+        newCase.Subject = serviceSummary.ServiceSubject__c; //涓婚 
+        newCase.Description = serviceSummary.ServiceDescription__c; //鎻忚堪
+        newCase.AccountId = serviceSummary.ServiceAccount__c; //鏈嶅姟瀹㈡埛
+        newCase.Reason = serviceSummary.ServiceReason__c; //涓鍘熷洜
+        newCase.Origin = serviceSummary.ServiceOrigin__c; //涓鏉ユ簮
+        newCase.Priority = serviceSummary.ServicePriority__c; //浼樺厛绾�
+        newCase.CreatedDate = Datetime.now(); //寮�濮嬫棩鏈�/鏃堕棿
+        newCase.CaseServiceSummary__c = serviceSummary.Id;
+        newCase.Status = 'New';
+        newCase.ApprovalStatus__c = '鑽夋涓�';
+        newCase.recordtypeId = recordtypeId;
+
+        return newCase;
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/ServiceSummaryHandler.cls-meta.xml b/scr/classes/ServiceSummaryHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/ServiceSummaryHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SiteLoginController.cls b/scr/classes/SiteLoginController.cls
new file mode 100644
index 0000000..fb2f4c7
--- /dev/null
+++ b/scr/classes/SiteLoginController.cls
@@ -0,0 +1,14 @@
+/**
+ * An apex page controller that exposes the site login functionality
+ */
+global with sharing class SiteLoginController {
+    global String username {get; set;}
+    global String password {get; set;}
+
+    global PageReference login() {
+        String startUrl = System.currentPageReference().getParameters().get('startURL');
+        return Site.login(username, password, startUrl);
+    }
+    
+   	global SiteLoginController () {}
+}
\ No newline at end of file
diff --git a/scr/classes/SiteLoginController.cls-meta.xml b/scr/classes/SiteLoginController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SiteLoginController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SiteLoginControllerTest.cls b/scr/classes/SiteLoginControllerTest.cls
new file mode 100644
index 0000000..88ec4a9
--- /dev/null
+++ b/scr/classes/SiteLoginControllerTest.cls
@@ -0,0 +1,13 @@
+/**
+ * An apex page controller that exposes the site login functionality
+ */
+@IsTest global with sharing class SiteLoginControllerTest {
+    @IsTest(SeeAllData=true) global static void testSiteLoginController () {
+        // Instantiate a new controller with all parameters in the page
+        SiteLoginController controller = new SiteLoginController ();
+        controller.username = 'test@salesforce.com';
+        controller.password = '123456'; 
+                
+        System.assertEquals(controller.login(),null);                           
+    }    
+}
\ No newline at end of file
diff --git a/scr/classes/SiteLoginControllerTest.cls-meta.xml b/scr/classes/SiteLoginControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SiteLoginControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SiteRegisterController.cls b/scr/classes/SiteRegisterController.cls
new file mode 100644
index 0000000..9332bc4
--- /dev/null
+++ b/scr/classes/SiteRegisterController.cls
@@ -0,0 +1,50 @@
+/**
+ * An apex class that creates a portal user
+ */
+public with sharing class SiteRegisterController {
+    // PORTAL_ACCOUNT_ID is the account on which the contact will be created on and then enabled as a portal user.
+    // you need to add the account owner into the role hierarchy before this will work - please see Customer Portal Setup help for more information.       
+    private static Id PORTAL_ACCOUNT_ID = '001x000xxx35tPN';
+    
+    public SiteRegisterController () {
+    }
+
+    public String username {get; set;}
+    public String email {get; set;}
+    public String password {get; set {password = value == null ? value : value.trim(); } }
+    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
+    public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
+      
+    private boolean isValidPassword() {
+        return password == confirmPassword;
+    }
+    
+    public PageReference registerUser() {
+        // it's okay if password is null - we'll send the user a random password in that case
+        if (!isValidPassword()) {
+        	ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
+        	ApexPages.addMessage(msg);
+            return null;
+        }    
+        User u = new User();
+        u.Username = username;
+        u.Email = email;
+        u.CommunityNickname = communityNickname;
+        
+        String accountId = PORTAL_ACCOUNT_ID;
+
+        // lastName is a required field on user, but if it isn't specified, we'll default it to the username
+        String userId = Site.createPortalUser(u, accountId, password);
+        if (userId != null) { 
+            if (password != null && password.length() > 1) {
+                return Site.login(username, password, null);
+            }
+            else {
+                PageReference page = System.Page.SiteRegisterConfirm;
+                page.setRedirect(true);
+                return page;
+            }
+        }
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SiteRegisterController.cls-meta.xml b/scr/classes/SiteRegisterController.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SiteRegisterController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SiteRegisterControllerTest.cls b/scr/classes/SiteRegisterControllerTest.cls
new file mode 100644
index 0000000..79f27fa
--- /dev/null
+++ b/scr/classes/SiteRegisterControllerTest.cls
@@ -0,0 +1,17 @@
+/**
+ * Class containing tests for SiteRegisterController
+ */
+@IsTest public with sharing class SiteRegisterControllerTest {
+    @IsTest(SeeAllData=true) static void testRegistration() {
+        SiteRegisterController controller = new SiteRegisterController();
+        controller.username = 'test@force.com';
+        controller.email = 'test@force.com';
+        controller.communityNickname = 'test';
+        // registerUser will always return null when the page isn't accessed as a guest user
+        System.assert(controller.registerUser() == null);    
+        
+        controller.password = 'abcd1234';
+        controller.confirmPassword = 'abcd123';
+        System.assert(controller.registerUser() == null);  
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SiteRegisterControllerTest.cls-meta.xml b/scr/classes/SiteRegisterControllerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/SiteRegisterControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SoapApi.cls b/scr/classes/SoapApi.cls
new file mode 100644
index 0000000..1846deb
--- /dev/null
+++ b/scr/classes/SoapApi.cls
@@ -0,0 +1,104 @@
+// UnitTest銈傝�冩叜銇椼仸PartnerSoapSforceCom.cls 銈抴rapper銇欍倠
+public with sharing class SoapApi {
+    private static final PartnerSoapSforceCom.Soap soap;
+
+    // https://developer.salesforce.com/forums/ForumsMain?id=906F000000092a6IAA
+    private static Map<String, String> domainInstanceMap { get; private set; }
+    static {
+        domainInstanceMap = new Map<String, String>();
+        domainInstanceMap.put('1', 'ap0');
+        domainInstanceMap.put('2', 'ap2');
+        domainInstanceMap.put('9', 'ap1');
+        domainInstanceMap.put('O', 'cs5');
+        domainInstanceMap.put('N', 'cs6');
+        domainInstanceMap.put('0', 'cs112');
+        soap = new PartnerSoapSforceCom.Soap();
+        soap.SessionHeader = new PartnerSoapSforceCom.SessionHeader_element();
+        // This is important, give session id, to let the call work.
+        soap.SessionHeader.sessionId = UserInfo.getSessionId();
+        //system.debug('=========='+soap.SessionHeader.sessionId.subString(3, 4)); 
+        soap.endpoint_x = 'https://' + domainInstanceMap.get(soap.SessionHeader.sessionId.subString(3, 4)) + '-api.salesforce.com/services/Soap/u/33.0';
+    }
+    /*
+    PartnerSoapSforceCom.DescribeLayoutResult dlr = SoapApi.describeLayout('Repair__c', null, new String[]{'01210000000QmS9'});
+    System.debug('layoutId=' + dlr.layouts[0].id);
+    System.debug('recordTypeId=' + dlr.recordTypeMappings[0].recordTypeId);
+    */
+    public static PartnerSoapSforceCom.DescribeLayoutResult describeLayout(String sObjectType, String layoutName, String[] recordTypeIds) {
+        if (System.Test.isRunningTest()) {
+            // UnitTest 鐢�
+            PartnerSoapSforceCom.DescribeLayoutResult dlr = new PartnerSoapSforceCom.DescribeLayoutResult();
+            PartnerSoapSforceCom.RecordTypeMapping rtMap = new PartnerSoapSforceCom.RecordTypeMapping();
+            PartnerSoapSforceCom.DescribeLayout editLayout = new PartnerSoapSforceCom.DescribeLayout();
+            PartnerSoapSforceCom.DescribeLayoutSection editLayoutSection = new PartnerSoapSforceCom.DescribeLayoutSection();
+            PartnerSoapSforceCom.DescribeLayoutRow layoutRow = new PartnerSoapSforceCom.DescribeLayoutRow();
+            PartnerSoapSforceCom.DescribeLayoutItem layoutItem = new PartnerSoapSforceCom.DescribeLayoutItem();
+            PartnerSoapSforceCom.DescribeLayoutComponent layoutComponent = new PartnerSoapSforceCom.DescribeLayoutComponent();
+            dlr.recordTypeMappings = new List<PartnerSoapSforceCom.RecordTypeMapping>();
+            dlr.recordTypeMappings.add(rtMap);
+            rtMap.recordTypeId = 'recordTypeId';
+            dlr.layouts = new List<PartnerSoapSforceCom.DescribeLayout>();
+            dlr.layouts.add(editLayout);
+            editLayout.editLayoutSections = new List<PartnerSoapSforceCom.DescribeLayoutSection>();
+            editLayout.editLayoutSections.add(editLayoutSection);
+            editLayoutSection.layoutRows = new List<PartnerSoapSforceCom.DescribeLayoutRow>();
+            editLayoutSection.layoutRows.add(layoutRow);
+            layoutRow.layoutItems = new List<PartnerSoapSforceCom.DescribeLayoutItem>();
+            layoutRow.layoutItems.add(layoutItem);
+            layoutItem.layoutComponents = new List<PartnerSoapSforceCom.DescribeLayoutComponent>();
+            layoutItem.layoutComponents.add(layoutComponent);
+            return dlr;
+        } else {
+            return soap.describeLayout(sObjectType, layoutName, recordTypeIds);
+        }
+    }
+
+    // 绶ㄩ泦鐢ㄣ儸銈ゃ偤銇ㄣ伄闋呯洰銇� r,w,wm 銇儏鍫便倰 杩斻仚
+    // Map銇伅銆丷ecordTypeId(18妗�) => {api鍚� => r,w,wm}
+    public static Map<String, Map<String, String>> getEditLayoutItemRW(String sObjectType, String[] recordTypeIds) {
+        PartnerSoapSforceCom.DescribeLayoutResult dlr = describeLayout(sObjectType, null, recordTypeIds);
+        Map<String, Map<String, String>> rtn = new Map<String, Map<String, String>>();
+        for (Integer lidx = 0; lidx < dlr.layouts.size(); lidx++) {
+            String recordTypeId = dlr.recordTypeMappings[lidx].recordTypeId;
+            Map<String, String> rtnInner = new Map<String, String>();
+            rtn.put(recordTypeId, rtnInner);
+            System.debug('recordTypeId=' + recordTypeId);
+            for (PartnerSoapSforceCom.DescribeLayoutSection section : dlr.layouts[lidx].editLayoutSections) {
+                for (PartnerSoapSforceCom.DescribeLayoutRow row : section.layoutRows) {
+                    for (PartnerSoapSforceCom.DescribeLayoutItem item : row.layoutItems) {
+                        if (item.layoutComponents != null && item.layoutComponents.size() > 0 && String.isBlank(item.layoutComponents[0].value) == false) {
+                            rtnInner.put(item.layoutComponents[0].value, 'r');
+                            if (item.editableForUpdate) {
+                                rtnInner.put(item.layoutComponents[0].value, 'w');
+                            }
+                            if (item.required) {
+                                rtnInner.put(item.layoutComponents[0].value, 'wm');
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        return rtn;
+    }
+    
+    // SObject銇甊ecordType銇繙銇樸仸銆丳icklist銇甐alue銈掓娊鍑�
+    public static List<String> getPicklistValueByRecordType(String sObjectType, String[] recordTypeIds, String picklistApi) {
+        PartnerSoapSforceCom.DescribeLayoutResult dlr = describeLayout(sObjectType, null, recordTypeIds);
+        List<String> rtn = new List<String>();
+        for (Integer i = 0; i < dlr.layouts.size(); i++) {
+            String recordTypeId = dlr.recordTypeMappings[i].recordTypeId;
+            PartnerSoapSforceCom.PicklistForRecordType[] ptrList =  dlr.recordTypeMappings[i].picklistsForRecordType;
+            for (Integer j = 0; j < ptrList.size(); j++) {
+                if (ptrList[j].picklistName == picklistApi) {
+                    PartnerSoapSforceCom.PicklistEntry[] pe = ptrList[j].picklistValues;
+                    for (Integer k = 0; k < pe.size(); k++) {
+                        rtn.add(pe[k].label);
+                    }
+                    break;
+                }
+            }
+        }
+        return rtn;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SoapApi.cls-meta.xml b/scr/classes/SoapApi.cls-meta.xml
new file mode 100644
index 0000000..53eefa5
--- /dev/null
+++ b/scr/classes/SoapApi.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SoapApiTest.cls b/scr/classes/SoapApiTest.cls
new file mode 100644
index 0000000..b5a286b
--- /dev/null
+++ b/scr/classes/SoapApiTest.cls
@@ -0,0 +1,43 @@
+@isTest
+private class SoapApiTest {
+    @isTest
+    static void partnerSoapSforceComTest() {
+        // PartnerSoapSforceCom 鏈綋
+        new PartnerSoapSforceCom();
+        new PartnerSoapSforceCom.Soap();
+        new PartnerSoapSforceCom.SessionHeader_element();
+        new PartnerSoapSforceCom.describeLayout_element();
+        new PartnerSoapSforceCom.describeLayoutResponse_element();
+        new PartnerSoapSforceCom.DescribeLayoutResult();
+        new PartnerSoapSforceCom.DescribeLayout();
+        new PartnerSoapSforceCom.DescribeLayoutButtonSection();
+        new PartnerSoapSforceCom.DescribeLayoutButton();
+        new PartnerSoapSforceCom.DescribeColor();
+        new PartnerSoapSforceCom.DescribeIcon();
+        new PartnerSoapSforceCom.DescribeLayoutSection();
+        new PartnerSoapSforceCom.DescribeLayoutRow();
+        new PartnerSoapSforceCom.DescribeLayoutItem();
+        new PartnerSoapSforceCom.DescribeLayoutComponent();
+        new PartnerSoapSforceCom.DescribeQuickActionListResult();
+        new PartnerSoapSforceCom.DescribeQuickActionListItemResult();
+        new PartnerSoapSforceCom.RelatedContent();
+        new PartnerSoapSforceCom.DescribeRelatedContentItem();
+        new PartnerSoapSforceCom.RelatedList();
+        new PartnerSoapSforceCom.RelatedListSort();
+        new PartnerSoapSforceCom.RelatedListColumn();
+        new PartnerSoapSforceCom.RecordTypeMapping();
+        new PartnerSoapSforceCom.PicklistForRecordType();
+        new PartnerSoapSforceCom.PicklistEntry();
+    }
+/* 20151018 xud comment out
+    @isTest
+    static void partnerSoapSforceComMethodTest() {
+        PartnerSoapSforceCom.Soap soap = new PartnerSoapSforceCom.Soap();
+        soap.describeLayout('SObject', null, new String[]{'RecordTypeId'});
+    }
+*/
+    @isTest
+    static void getEditLayoutItemRWTest() {
+        SoapApi.getEditLayoutItemRW('SObject', new String[]{'RecordTypeId'});
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SoapApiTest.cls-meta.xml b/scr/classes/SoapApiTest.cls-meta.xml
new file mode 100644
index 0000000..d219ea1
--- /dev/null
+++ b/scr/classes/SoapApiTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>35.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/SoftphoneConsoleController.cls b/scr/classes/SoftphoneConsoleController.cls
new file mode 100644
index 0000000..a9162e7
--- /dev/null
+++ b/scr/classes/SoftphoneConsoleController.cls
@@ -0,0 +1,13 @@
+public without sharing class SoftphoneConsoleController {
+    public String baseUrl {get; set;}
+    public Boolean LoginFlag {get; set;}
+    public SoftphoneConsoleController() {
+        
+    }
+
+    public void init() {
+        LoginFlag = true;
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/SoftphoneConsoleController.cls-meta.xml b/scr/classes/SoftphoneConsoleController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/SoftphoneConsoleController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/StageProgressBarExtension.cls b/scr/classes/StageProgressBarExtension.cls
new file mode 100644
index 0000000..9b55428
--- /dev/null
+++ b/scr/classes/StageProgressBarExtension.cls
@@ -0,0 +1,39 @@
+public with sharing class StageProgressBarExtension {
+    public String targetId { get; set; }
+    public String targetStageName { get; set; }
+    public String recordTypeName { get; private set; }
+    public List<String> stages { get; set; }
+    
+    public StageProgressBarExtension(ApexPages.StandardController controller) {
+        Opportunity opp = [select RecordTypeId, RecordType.DeveloperName from Opportunity where Id = :controller.getRecord().Id];
+        recordTypeName = opp.RecordType.DeveloperName;
+        
+        stages = SoapApi.getPicklistValueByRecordType('Opportunity', new String[]{opp.RecordTypeId}, 'StageName');
+        /*
+        stages = new List<String>();
+        PartnerSoapSforceCom.DescribeLayoutResult dlr = SoapApi.describeLayout('Opportunity', null, new String[]{opp.RecordTypeId});
+        for (Integer i = 0; i < dlr.layouts.size(); i++) {
+            String recordTypeId = dlr.recordTypeMappings[i].recordTypeId;
+            PartnerSoapSforceCom.PicklistForRecordType[] ptrList =  dlr.recordTypeMappings[i].picklistsForRecordType;
+            for (Integer j = 0; j < ptrList.size(); j++) {
+                if (ptrList[j].picklistName == 'StageName') {
+                    PartnerSoapSforceCom.PicklistEntry[] pe = ptrList[j].picklistValues;
+                    for (Integer k = 0; k < pe.size(); k++) {
+                        stages.add(pe[k].label);
+                    }
+                    break;
+                }
+            }
+        }
+        */
+    }
+    
+    public void updateOpp() {
+        Opportunity opp = new Opportunity(
+            Id = targetId,
+            StageName = targetStageName
+        );
+        StaticParameter.StageProgressBarUpdate = True;
+        update opp;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/StageProgressBarExtension.cls-meta.xml b/scr/classes/StageProgressBarExtension.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/StageProgressBarExtension.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/StaticParameter.cls b/scr/classes/StaticParameter.cls
new file mode 100644
index 0000000..48e0495
--- /dev/null
+++ b/scr/classes/StaticParameter.cls
@@ -0,0 +1,284 @@
+public without sharing class StaticParameter {
+    // 鏄惁浠� StageProgressBarExtension 鏇存柊 Stage鐨�
+    public static Boolean StageProgressBarUpdate = false;
+    // 浜屾杩涘叆 OpportunityTriggerHandler 鐨� setReceiver鏂规硶璺宠繃鍒濆鍖�
+    public static Boolean OpportunityTriggerHandler_setReceiver = false;
+    // 鐜嬮箯浼� OrderTriggerHandler 鏇存柊 Opportunity 鏃惰烦杩� OpportunityTrigger涓兘鍚堝悓鐨勬洿鏂�
+    public static Boolean OpportunityTriggerIsUpdate = false;
+    // 鐜嬮箯浼� OpportunityTrigger 鏇存柊 Order 鏃惰烦杩� OrderTriggerHandler涓璇环鐨勬洿鏂�
+    public static Boolean OrderTriggerIsUpdate = false;
+    //鑳藉惁淇敼鍏宠仈璇环
+    public static Boolean OppCanChangeOpp = false;
+    //鐢ㄤ簬璺宠繃鍏宠仈璇环鏉ュ洖璧嬪�笺��
+    public static Boolean OppChangeopp = false;
+    //璺宠繃楠岃瘉銆�
+    public static Boolean temp = false;
+    // 浠g悊鍟咺D瀵瑰簲鐢ㄦ埛灏忕粍ID
+    public static Map<String, String> dealerGroupMap = new Map<String, String>{
+        '0012800000VhMq0' => '00G28000000eowR', //闀挎矙甯備紬鏋椾华鍣ㄨ澶囨湁闄愬叕鍙窧S
+        '0012800000DkOzP' => '00G28000000eowR', //
+        '0012800000DUL4Q' => '00G28000000eowR', //
+        '0012800000VhNG9' => '00G28000000eoxP', //涓婃捣澶╂斁瀹為獙浠櫒鏈夐檺鍏徃BS
+        '0012800000DkOzR' => '00G28000000eoxP', //
+        '0012800000DUL4U' => '00G28000000eoxP', //
+        '0012800000VhNPG' => '00G28000000eoy8', //涓婃捣姹熸枃鍥介檯璐告槗鏈夐檺鍏徃BS
+        '0012800000DkOzW' => '00G28000000eoy8', //
+        '0012800000DUL4Y' => '00G28000000eoy8', //
+        '0012800000VhNkn' => '00G28000000ep1b', //鏉窞鏌忓ゥ璋风鎶�鏈夐檺鍏徃BS
+        '0012800000VhNez' => '00G28000000ep1b', //
+        '0012800000VgrED' => '00G28000000ep1b', //
+        '0012800000VhO4T' => '00G28000000ep2e', //鍗椾含濂ュ姏绉戝浠櫒鏈夐檺鍏徃BS
+        '0012800000DUL4K' => '00G28000000ep2e', //
+        '0012800000DkOzQ' => '00G28000000ep2e', //
+        '0012800000VhOAl' => '00G28000000ep2t', //姝︽眽鎭掑槈淇婄鎶�鏈夐檺鍏徃BS
+        '0012800000DkOzM' => '00G28000000ep2t', //
+        '0012800000DUL4S' => '00G28000000ep2t', //
+        '0012800000VhOKW' => '00G28000000ep3S', //涓婃捣澶栨捣鐢熺墿绉戞妧鏈夐檺鍏徃BS
+        '0012800000DUL4R' => '00G28000000ep3S', //
+        '0012800000DkOzN' => '00G28000000ep3S', //
+        '0012800000VhOOn' => '00G28000000ep3w', //闀挎槬婧愬悎鍖荤枟璁惧鏈夐檺鍏徃BS
+        '0012800000DkOzH' => '00G28000000ep3w', //
+        '0012800000ElV7B' => '00G28000000ep3w', //
+        '0012800000VhORX' => '00G28000000ep4L', //鐢樿們鍢夌憺璐告槗鏈夐檺璐d换鍏徃BS
+        '0012800000DkOzF' => '00G28000000ep4L', //
+        '0012800000DUL4H' => '00G28000000ep4L', //
+        '0012800000VhOVU' => '00G28000000ep5d', //闄曡タ鍗庡ぇ鐢熺墿浠櫒鏈夐檺鍏徃BS
+        '0012800000DkOz8' => '00G28000000ep5d', //
+        '0012800000DUL4G' => '00G28000000ep5d', //
+        '0012800000VhP0E' => '00G28000000ep6P', //灞变笢鐖卞崥绉戞妧璐告槗鏈夐檺鍏徃BS
+        '0012800000DkOzL' => '00G28000000ep6P', //
+        '0012800000DUL4P' => '00G28000000ep6P', //
+        '0012800000VhP8g' => '00G28000000ep6o', //鍐呰挋鍙よ揪闊崇鎶�鏈夐檺鍏徃BS
+        '0012800000VhP7n' => '00G28000000ep6o', //
+        '0012800000VgrZy' => '00G28000000ep6o', //
+        '0012800000VhPEo' => '00G28000000ep7m', //鍐呰挋鍙よ揪闊崇鎶�鏈夐檺鍏徃BS
+        '0012800000DkOzO' => '00G28000000ep7m', //
+        '0012800000DUL4T' => '00G28000000ep7m', //
+        '0012800000VhPJP' => '00G28000000ep8k', //閮戝窞杩滀腑绉戞妧鏈夐檺鍏徃BS
+        '0012800000DkOzI' => '00G28000000ep8k', //
+        '0012800000DUL4D' => '00G28000000ep8k', //
+        '0012800000VhPOK' => '00G28000000ep9d', //娌堥槼绂惧厜绉戞妧鏈夐檺鍏徃BS
+        '0012800000DkOzJ' => '00G28000000ep9d', //
+        '0012800000DUL4E' => '00G28000000ep9d', //
+        '0012800000VhNEc' => '00G28000000eoxt', //鍖椾含鍐锋硥绉戞妧鏈夐檺鍏徃BS
+        '0012800000DkOzU' => '00G28000000eoxt', //
+        '0012800000DUL4A' => '00G28000000eoxt', //
+        '0012800000VhNjp' => '00G28000000ep0O', //鍖椾含淇″崕搴峰▉绉戞妧鏈夐檺鍏徃BS
+        '0012800000VgrTT' => '00G28000000ep0O', //
+        '0012800000VhNk9' => '00G28000000ep0O', //
+        '0012800000VhNta' => '00G28000000ep25', //鍖椾含淇″崕搴峰▉绉戞妧鏈夐檺鍏徃BS
+        '0012800000VgrR6' => '00G28000000ep25', //
+        '0012800000VhNsm' => '00G28000000ep25', //
+        '0012800000VhO8L' => '00G28000000ep2Z', //鍖椾含涓滄柟濂ヨ垷绉戞妧鍙戝睍鏈夐檺鍏徃BS
+        '0012800000VgrY2' => '00G28000000ep2Z', //
+        '0012800000VhO7D' => '00G28000000ep2Z', //
+        '0012800000VhOCc' => '00G28000000ep2y', //娴峰崡闅借獕绉戞妧鏈夐檺鍏徃BS
+        '0012800000DUL4M' => '00G28000000ep2y', //
+        '0012800000DkOzE' => '00G28000000ep2y', //
+        '0012800000VhOMw' => '00G28000000ep3c', //鍗楀畞缇庝附鐢熺墿绉戞妧鏈夐檺鍏徃BS
+        '0012800000Vgr6q' => '00G28000000ep3c', //
+        '0012800000VhOMN' => '00G28000000ep3c', //
+        '0012800000VhP9j' => '00G28000000ep73', //鍥涘窛鎭掓槗绉戞妧鏈夐檺鍏徃BS
+        '0012800000DkOzG' => '00G28000000ep73', //
+        '0012800000DUL4O' => '00G28000000ep73', //
+        '0012800000VhPKr' => '00G28000000ep94', //浜戝崡绁哄厜绉戞妧鏈夐檺鍏徃BS
+        '0012800000DkOzX' => '00G28000000ep94', //
+        '0012800000DUL4Z' => '00G28000000ep94', //
+        '0012800000VhPRE' => '00G28000000ep9s', //鍖椾含椤鸿兘鐢靛瓙浠櫒鏈夐檺鍏徃BS
+        '0012800000DUL4B' => '00G28000000ep9s', //00GO0000002HLzx
+        '0012800000DkOz7' => '00G28000000ep9s', //00GO0000002HLzx
+        '0012800000VhPa6' => '00G28000000epDO', //鍝堝皵婊ㄨ嫳鏉扮鎶�鍙戝睍鏈夐檺鍏徃BS
+        '0012800000DkOzK' => '00G28000000epDO', //
+        '0012800000DUL4F' => '00G28000000epDO', //
+        '0012800000VhPnl' => '00G28000000epFt', //骞垮窞甯備紬鍒涚敓鐗╃鎶�鏈夐檺鍏徃BS
+        '0012800000DUL49' => '00G28000000epFt', //
+        '0012800000DkOzV' => '00G28000000epFt', //
+        '0012800000VhPvp' => '00G28000000epIY', //鍚堣偉杩滄槑绉戞妧鏈夐檺鍏徃BS
+        '0012800000DUL4J' => '00G28000000epIY', //
+        '0012800000DkOzA' => '00G28000000epIY', //
+        '0012800000VhQLh' => '00G28000000epKP', //绂忓缓杩滄槑鐢熺墿绉戞妧鏈夐檺鍏徃BS
+        '0012800000VgrL5' => '00G28000000epKP', //
+        '0012800000VhRoB' => '00G28000000epKP', //
+        '0012800000VhQO7' => '00G28000000epKZ', //骞垮窞瀹夌鍖荤枟鍣ㄦ鏈夐檺鍏徃BS
+        '0012800000DUL4V' => '00G28000000epKZ', //
+        '0012800000DkOzS' => '00G28000000epKZ', //
+        '0012800000VhQOW' => '00G28000000epKj', //鍩瑰痉鍥介檯鏈夐檺鍏徃BS
+        '0012800000DUL4X' => '00G28000000epKj', //
+        '0012800000VhQLm' => '00G28000000epKj', //
+        '0012800000VhQcJ' => '00G28000000epP6', //涓婃捣鎸浠櫒鏈夐檺鍏徃BS
+        '0012800000DkOz9' => '00G28000000epP6', //
+        '0012800000DUL4I' => '00G28000000epP6', //
+        '0012800000DUL3z' => '00G28000000eowg', //鍖椾含楣扮憺杈剧鎶�鍙戝睍鏈夐檺璐d换鍏徃RVI
+        '0012800000DUL40' => '00G28000000eox0', //涓婃捣鍦堝僵璐告槗鏈夐檺鍏徃RVI
+        '0012800000DUL42' => '00G28000000eoxK', //涓婃捣鑵捐鏈虹數璁惧鏈夐檺鍏徃RVI
+        '0012800000DUL45' => '00G28000000eoxo', //娣卞湷甯傛鏌忔満鐢佃澶囨湁闄愬叕鍙窻VI
+        '0012800000DUL46' => '00G28000000eoyI', //骞垮窞杈炬硦鎭╄锤鏄撴湁闄愬叕鍙窻VI
+        '0012800000DUL48' => '00G28000000eoyc', //涓婃捣瑗垮姫鍏夊绉戞妧鏈夐檺鍏徃RVI
+        '0012800000DUL47' => '00G28000000eozf', //涓婃捣鏂岀憺妫�娴嬫妧鏈湇鍔℃湁闄愬叕鍙窻VI
+        '0012800000DUL3l' => '00G28000000ep0E', //鍖椾含鍏冧腑閿愮闆嗘垚妫�娴嬫妧鏈湁闄愬叕鍙窱E
+        '0012800000DUL3m' => '00G28000000ep0Y', //闄曡タ鑸俊绉戝伐璐告湁闄愬叕鍙窱E
+        '0012800000DUL3n' => '00G28000000ep1g', //澶╂触甯傛亽娉拌揪鍥介檯璐告槗鏈夐檺鍏徃IE
+        '0012800000DUL43' => '00G28000000epI9', //澶╂触甯傛亽娉拌揪鍥介檯璐告槗鏈夐檺鍏徃RVI
+        '0012800000DUL3o' => '00G28000000epIi', //娌堥槼鍏冩澃鍏夊鎶�鏈湁闄愬叕鍙窱E
+        '0012800000DUL3y' => '00G28000000epJ7', //娌堥槼鍏冩澃鍏夊鎶�鏈湁闄愬叕鍙窻VI
+        '0012800000DUL3p' => '00G28000000ep2U', //涓婃捣鍔涢槼瀹炰笟鏈夐檺鍏徃IE
+        '0012800000DUL3r' => '00G28000000ep38', //骞垮窞鍏冨崌绉戞妧鏈夐檺鍏徃IE
+        '0012800000DUL3s' => '00G28000000ep3N', //涓婃捣瑗垮姫鍏夊绉戞妧鏈夐檺鍏徃IE
+        '001N000001BHVhZ' => '00G28000000ep3N',
+        '001N000001BHVkg' => '00G28000000ep3N',
+        '0012800001HoNjr' => '00G28000000ep3N',
+        '0012800001HoO3Y' => '00G28000000ep3N',
+        '0012800000DUL3t' => '00G28000000epJM', //鏃犻敗鑱斿彂鏄撳垱绉戞妧鏈夐檺鍏徃IE
+        '0012800000DUL3u' => '00G28000000ep41', //鏃犻敗涓栬繄绉戞妧鏈夐檺鍏徃IE
+        '0012800000DUL3v' => '00G28000000ep4G', //鏉窞鍏ㄨ氨瀹為獙瀹よ澶囨湁闄愬叕鍙窱E
+        '0012800000DUL3w' => '00G28000000ep4V', //鑻忓窞绉戝啝鐢靛瓙绉戞妧鏈夐檺鍏徃IE
+        '0012800000DUL3Z' => '00G28000000ep6j', //鍖椾含寰峰畤娉涚編娴嬭瘯鎶�鏈湁闄愬叕鍙窷DT
+        '0012800000DUL3a' => '00G28000000ep78', //涓婃捣鍏嬫礇鍔涙棤鎹熸娴嬭澶囨湁闄愬叕鍙窷DT
+        '0012800000DUL44' => '00G28000000ep7h', //鍖椾含鏂板叴鏃ョゥ绉戞妧鍙戝睍鏈夐檺鍏徃RVI
+        '0012800000DUL3b' => '00G28000000ep8p', //鍖椾含鏂板叴鏃ョゥ绉戞妧鍙戝睍鏈夐檺鍏徃NDT
+        '0012800000DUL3c' => '00G28000000ep9O', //涓婃捣鏂岀憺妫�娴嬫妧鏈湇鍔℃湁闄愬叕鍙窷DT
+        '0012800000DUL3d' => '00G28000000epA2', //涓婃捣鑹惧洜钂傚厠瀹炰笟鏈夐檺鍏徃NDT
+        '0012800000DUL3e' => '00G28000000epBF', //闄曡タ鎭╁焹濮嗘娴嬫妧鏈湁闄愬叕鍙窷DT
+        '0012800000DUL3q' => '00G28000000epCk', //閲嶅簡姘搁暱绉戞妧鏈夐檺鍏徃IE
+        '0012800000DUL3f' => '00G28000000epDJ', //閲嶅簡姘搁暱绉戞妧鏈夐檺鍏徃NDT
+        '0012800000DUL41' => '00G28000000epEb', //閲嶅簡姘搁暱绉戞妧鏈夐檺鍏徃RVI
+        '0012800000DUL3g' => '00G28000000epFj', //寤婂潑甯傛柊鎬濈淮绉戞妧鏈夐檺鍏徃NDT
+        '0012800000DUL3j' => '00G28000000epGD', //鍖椾含甯傚箍涓氬崕涓板晢璐告湁闄愯矗浠诲叕鍙窤NI
+        '0012800000DUL3k' => '00G28000000epHL', //涓婃捣娉芥潈浠櫒璁惧鏈夐檺鍏徃ANI
+        '0012800000DkOz2' => '00G28000000epJb', //娣卞湷甯傝幈闆风鎶�鏈夐檺鍏徃ANI
+        '0012800000DkOz3' => '00G28000000epJv', //涓櫤鍗庢亽锛堝寳浜級绉戞妧鏈夐檺鍏徃RVI
+        '0012800000DUL3i' => '00G28000000epKF', //鍖椾含娆у畞鑸畤妫�娴嬫妧鏈湁闄愬叕鍙窷DT
+        '0012800000Vk2p2' => '00G28000000erQv', //宸存柉寰蜂华鍣紙鑻忓窞锛夋湁闄愬叕鍙窤NI
+        '001N000001BSTRn' => '00GN0000001y6Tg', //BS铏氭嫙浠g悊鍟�
+        '001N000001BSTXv' => '00GN0000001y6Tg',
+        '001N000001BSTaf' => '00GN0000001y6Tg',
+        '0012800001HoORb' => '00G28000003GUrf', //BS铏氭嫙浠g悊鍟�(鐢熶骇鏈�)
+        '0012800001HoPY4' => '00G28000003GUrf',
+        '0012800001HoPaz' => '00G28000003GUrf',
+        '0012800001HrYfb' => '00G28000003GXLg', //涓変赴鏅哄悎锛堝寳浜級绉戞妧鏈夐檺鍏徃RVI
+        '00128000010VBAC' => '00G28000003GXLW', //瀹濇�匡紙澶╂触锛夌鎶�鏈夐檺鍏徃IE
+        '0012800001YrM3K' => '00G28000003PVrh',  //鍖椾含涓诲鏃朵唬绉戞妧鏈夐檺鍏徃RVI
+        '0012800001YvAK9' => '00G28000003Pa4f',  //鍝堝皵婊ㄨ嫳妗�鎭掑姳绉戞妧鏈夐檺鍏徃BS
+        '0012800001YvAN9' => '00G28000003Pa4f',
+        '0012800001YvAQh' => '00G28000003Pa4f', 
+        '0012800000k77B5' => '00G0K000002e0U0',  //鍖椾含鏂版簮蹇楀嫟绉戞妧寮�鍙戞湁闄愯矗浠诲叕鍙窤NI
+        '0010K00001oSRPl' => '00G0K000002e1Rh',  //婀栧崡鑹炬.濞佸皵鐢熺墿绉戞妧鏈夐檺鍏徃BS
+        '0010K00001oSRRh' => '00G0K000002e1Rh',
+        '0010K00001oSRSp' => '00G0K000002e1Rh',
+        '0010K00001rX52j' => '00G0K000002e5EV',  //棣欐腐鍜岃皭绉戞妧BS
+        '0010K00001rX5Ao' => '00G0K000002e5EV',
+        '0010K00001rX57a' => '00G0K000002e5EV', 
+        '0010K00001vWYg7' => '00G0K000002eEHc',  //鎴愰兘鐭ュ绉戞妧鏈夐檺鍏徃BS
+        '0010K00001vWYkO' => '00G0K000002eEHc',
+        '0010K00001vWYoJ' => '00G0K000002eEHc',
+        '0010K00001yH6FB' => '00G0K000002eJEU',  //璧㈡床绉戞妧锛堜笂娴凤級鏈夐檺鍏徃(ANI)
+        '0010K00001yeroC' => '00G0K000002eJjr',   //闄曡タ鎭╁焹濮嗘娴嬫妧鏈湁闄愬叕鍙�(ANI)  
+        '00128000010VBJR' => '00G0K000002eTHp',  //瑗垮畨鍔╁崥鍟嗚锤鏈夐檺鍏徃(IE)  
+        '0010K000021ywpM' => '00G0K000002eYhe',  //瀹濇�匡紙澶╂触锛夌鎶�鏈夐檺鍏徃 (RVI) 
+        //'0010K000027TYtf' => '00G0K0000048ZDM',   //鎴愰兘閾佸畨绉戞妧鏈夐檺璐d换鍏徃(NDT) 
+        '0012800000etOTu' => '00G0K000003bFDx',   //鍖椾含姘哥洓閫氱鎶�鍙戝睍鏈夐檺鍏徃(ANI)
+        '0012800000DUL3j' => '00G0K000003bFE2',   //鍖椾含姘哥洓閫氱鎶�鍙戝睍鏈夐檺鍏徃(ANI)
+        '0010K00002B0rbU' => '00G0K000003bH3e',   //鍖椾含鏂板叴鏃ョゥ绉戞妧鍙戝睍鏈夐檺鍏徃鍖椾含鍒嗗叕鍙�(RVI)
+        '0010K000029aPEt' => '00G0K000003bHP7',   //澶╂触瀹忓熀浼熶笟绉戞妧鍙戝睍鏈夐檺鍏徃(NDT) 
+        '0010l000014DCVy' => '00G0l000002YURd',   //NDT鐩撮攢(NDT) 
+        '0010l000014F1xH' => '00G0l000002ZCV0',    //cxck鏋滄灉(P)娴嬭瘯(BS) 
+        '0010l000014F1xI' => '00G0l000002ZCV0',   //cxck鏋滄灉(P)娴嬭瘯(BS) 
+        '0010l000014F1xJ' => '00G0l000002ZCV0',    //cxck鏋滄灉(P)娴嬭瘯(BS) 
+        '0010l000014F9EA' => '00G0l000002ZCkU',   //閰嶇疆SFDC娴嬭瘯浠g悊鍟嗘垚閮界煡闀淟S1112-1(璇剧◣)(BS)
+        '0010l000014F9EB' => '00G0l000002ZCkU',   //閰嶇疆SFDC娴嬭瘯浠g悊鍟嗘垚閮界煡闀淟S1112-1(鍏嶇◣)(BS)
+        '0010l000014F9E9' => '00G0l000002ZCkU',    //閰嶇疆SFDC娴嬭瘯浠g悊鍟嗘垚閮界煡闀淟S1112-1(P)(BS)
+        '0010l000014F8kl' => '00G0l000002ZCkj',     //璐甸槼闆嗗洟(IE)
+        '0010l000014Eq8a' => '00G0l000002ZH60',    //ANI杈愬皠瀹℃壒浜轰笉涓�鑷�(ANI)
+        '0010l000014ERfV' => '00G0l000002ZH6P',    //ANI纾婃床鍑ょ绉戞妧鏈夐檺鍏徃(ANI)
+        '0010K00002FmNJV' => '00G0K000004gZJJ', //鍖椾含椤鸿兘姹囨嵎绉戞妧鏈夐檺鍏徃BS
+        '0010K00002FmNa2' => '00G0K000004gZJJ', //
+        '0010K00002FmNn6' => '00G0K000004gZJJ',
+        '0010K00002JFf2x' => '00G0K000004ILpG', //鍜岃皭绉戞妧棣欐腐鏈夐檺鍏徃LS
+        '0010K00002JFf2y' => '00G0K000004ILpG', //
+        '0010K00002JFf2z' => '00G0K000004ILpG',
+        '0010l000016tsGb' => '00G0l000002jOvM', //骞垮窞甯備腑瑾変华鍣ㄦ湁闄愬叕鍙窵S(娴嬭瘯鐜-鏆傛椂淇濈暀)
+        '0010l000016tsGc' => '00G0l000002jOvM', //
+        '0010l000016tsGd' => '00G0l000002jOvM',
+        '0010K00002K9uVi' => '00G0K000003f6dm',//骞垮窞甯備腑瑾変华鍣ㄦ湁闄愬叕鍙窵S(鍏堜笂绾夸簡,鍚庤竟闇�瑕佷慨鏀�)
+        '0010K00002K9uVj' => '00G0K000003f6dm',
+        '0010K00002K9uVh' => '00G0K000003f6dm',
+        '0010l000017FdAO' => '00G0l000002jdTh',//浣拌鍏ㄦ櫙鐢熺墿鎶�鏈紙鍖椾含锛夋湁闄愬叕鍙�(娴嬭瘯鐜)
+        '0010l000017FdAP' => '00G0l000002jdTh',
+        '0010l000017FdAQ' => '00G0l000002jdTh',
+        '0010K00002Krwa3' => '00G0K000003f6wd',//浣拌鍏ㄦ櫙鐢熺墿鎶�鏈紙鍖椾含锛夋湁闄愬叕鍙�
+        '0010K00002Krwa4' => '00G0K000003f6wd',
+        '0010K00002Krwa5' => '00G0K000003f6wd',
+        '0010K00002OzDAj' => '00G0K0000032GIu',   //鍥涘窛涓槉娴风撼绉戞妧鏈夐檺鍏徃(ANI)
+        '0010K00002QPKzg' => '00G0K0000032NuG', //鍖椾含搴风憺鐗圭璐告湁闄愯矗浠诲叕鍙窵S
+        '0010K00002QPKzh' => '00G0K0000032NuG',
+        '0010K00002QPKzi' => '00G0K0000032NuG',
+        '0010K00002QPL0F' => '00G0K0000032NuL', //鍖椾含涓�氭亽淇′俊鎭妧鏈湁闄愬叕鍙窵S
+        '0010K00002QPL0G' => '00G0K0000032NuL',
+        '0010K00002QPL0H' => '00G0K0000032NuL',
+        '0010K00002QPKzv' => '00G0K0000032NuQ', //澶╂触涓滃崡浠瘹绉戞妧鏈夐檺鍏徃LS
+        '0010K00002QPKzw' => '00G0K0000032NuQ',
+        '0010K00002QPKzx' => '00G0K0000032NuQ',
+        '0010K00002QQClI' => '00G0K0000032OcK', //鏉窞瑁曢泤鐢熺墿绉戞妧鏈夐檺鍏徃LS
+        '0010K00002QQClJ' => '00G0K0000032OcK',
+        '0010K00002QQClK' => '00G0K0000032OcK',
+        '0010K00002QQClm' => '00G0K0000032OcP', //鏉窞鐩婅埅璐告槗鏈夐檺鍏徃LS
+        '0010K00002QQCln' => '00G0K0000032OcP',
+        '0010K00002QQClo' => '00G0K0000032OcP',
+        '0010K00002QQClw' => '00G0K0000032PJN', //鐧鹃潏鐢熺墿绉戞妧婢抽杸鏈夐檺鍏徃LS
+        '0010K00002QQClx' => '00G0K0000032PJN',
+        '0010K00002QQCly' => '00G0K0000032PJN',
+        '0010K00002Rq7fV' => '00G0K0000032UPU',  //姹熻嫃杩笟妫�娴嬬鎶�鏈夐檺鍏徃NDT
+        '0010K00002UvCpN' => '00G0K000004AUM3', //鍥借嵂鍣ㄦ娌冲崡鐢熷懡绉戝鏈夐檺鍏徃
+        '0010K00002UvCpO' => '00G0K000004AUM3',
+        '0010K00002UvCpP' => '00G0K000004AUM3',
+        '0010K00002UvCpX' => '00G0K000004AUMX', //瀹夊窘鍢夊皻鐢熺墿绉戞妧鏈夐檺鍏徃
+        '0010K00002UvCpY' => '00G0K000004AUMX',
+        '0010K00002UvCpZ' => '00G0K000004AUMX',
+        '0010K00002UxwVw' => '00G0K000004AVL6', //骞垮窞甯備腑瑾変华鍣ㄧ鎶�鏈夐檺鍏徃(BS)
+        '0010K00002UxxSP' => '00G0K000004AVL6',
+        '0010K00002UxxSO' => '00G0K000004AVL6',
+        '0010K00002VHSaB' => '00G0K000004AW2o',
+        '0010K00002UxxT1' => '00G0K000004AW38',
+        '0010K00002W6zlh' => '00G0K000004AYjU',//鎴愰兘鐩涢敶绉戞妧鏈夐檺鍏徃(NDT)
+        '0010K00002ZVOwt' => '00G0K000004c0oG'//澶╂触瀹忓熀浼熶笟绉戞妧鍙戝睍鏈夐檺鍏徃(NDT)
+
+    };
+
+    public static List<String> specialDealerList = new List<String>{
+        '0010K000027TYtf'
+    };
+
+    public static Map<String, String> specialDealerMap = new Map<String, String>{
+        //'0010K000027TYtf'
+        '0010l000016tsGb' => '0010l000016tsGb', //骞垮窞甯備腑瑾変华鍣ㄦ湁闄愬叕鍙窵S(娴嬭瘯鐜-鏆傛椂淇濈暀)
+        '0010l000016tsGc' => '0010l000016tsGc', //
+        '0010l000016tsGd' => '0010l000016tsGd',
+        '0010K00002K9uVi' => '0010K00002K9uVi',//骞垮窞甯備腑瑾変华鍣ㄦ湁闄愬叕鍙窵S
+        '0010K00002K9uVj' => '0010K00002K9uVj',
+        '0010K00002K9uVh' => '0010K00002K9uVh',
+        '0010l000017FdAO' => '0010l000017FdAO',//浣拌鍏ㄦ櫙鐢熺墿鎶�鏈紙鍖椾含锛夋湁闄愬叕鍙�(娴嬭瘯鐜)
+        '0010l000017FdAP' => '0010l000017FdAP',
+        '0010l000017FdAQ' => '0010l000017FdAQ',
+        '0010K00002Krwa3' => '0010K00002Krwa3',//浣拌鍏ㄦ櫙鐢熺墿鎶�鏈紙鍖椾含锛夋湁闄愬叕鍙�(娴嬭瘯鐜)
+        '0010K00002Krwa4' => '0010K00002Krwa4',
+        '0010K00002Krwa5' => '0010K00002Krwa5',
+        '0010K00002UxwVw' => '0010K00002UxwVw', //骞垮窞甯備腑瑾変华鍣ㄧ鎶�鏈夐檺鍏徃(BS)
+        '0010K00002UxxSP' => '0010K00002UxxSP',
+        '0010K00002UxxSO' => '0010K00002UxxSO'
+
+    };
+
+     public static Map<String, String> specialDealerMap1 = new Map<String, String>{
+
+        '0010l000016tsGb' => '0010l000016tsGb', //骞垮窞甯備腑瑾変华鍣ㄦ湁闄愬叕鍙窵S(娴嬭瘯鐜-鏆傛椂淇濈暀)
+        '0010l000016tsGc' => '0010l000016tsGc', //
+        '0010l000016tsGd' => '0010l000016tsGd',
+        '0010K00002K9uVi' => '0010K00002K9uVi',//骞垮窞甯備腑瑾変华鍣ㄦ湁闄愬叕鍙窵S
+        '0010K00002K9uVj' => '0010K00002K9uVj',
+        '0010K00002K9uVh' => '0010K00002K9uVh',
+        '0010K00002UxwVw' => '0010K00002UxwVw', //骞垮窞甯備腑瑾変华鍣ㄧ鎶�鏈夐檺鍏徃(BS)
+        '0010K00002UxxSP' => '0010K00002UxxSP',
+        '0010K00002UxxSO' => '0010K00002UxxSO'
+     };
+
+}
\ No newline at end of file
diff --git a/scr/classes/StaticParameter.cls-meta.xml b/scr/classes/StaticParameter.cls-meta.xml
new file mode 100644
index 0000000..d219ea1
--- /dev/null
+++ b/scr/classes/StaticParameter.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>35.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/StaticParameterTest.cls b/scr/classes/StaticParameterTest.cls
new file mode 100644
index 0000000..0abd5b3
--- /dev/null
+++ b/scr/classes/StaticParameterTest.cls
@@ -0,0 +1,10 @@
+@isTest
+private class StaticParameterTest {
+	@isTest 
+	static void test_init() {
+		StaticParameter.StageProgressBarUpdate = true;
+		StaticParameter.OpportunityTriggerIsUpdate = false;
+		String id = StaticParameter.dealerGroupMap.get('0012800000VhMq0');
+
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/StaticParameterTest.cls-meta.xml b/scr/classes/StaticParameterTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/StaticParameterTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TOTPPlugin.cls b/scr/classes/TOTPPlugin.cls
new file mode 100644
index 0000000..4a0395e
--- /dev/null
+++ b/scr/classes/TOTPPlugin.cls
@@ -0,0 +1,96 @@
+global class TOTPPlugin implements Process.Plugin
+{    
+    global Process.PluginDescribeResult describe()
+    {
+        Process.PluginDescribeResult result = new Process.PluginDescribeResult();
+        result.description='This plug-in handles salesforce standard two factor authentication methods.';
+        result.tag='Identity';
+        
+        result.inputParameters = new List<Process.PluginDescribeResult.InputParameter> {
+                new Process.PluginDescribeResult.InputParameter('OTP_INPUT', Process.PluginDescribeResult.ParameterType.STRING, true),
+                new Process.PluginDescribeResult.InputParameter('OTP_REGISTRATION_INPUT', Process.PluginDescribeResult.ParameterType.STRING, true),
+                new Process.PluginDescribeResult.InputParameter('SECRET_INPUT', Process.PluginDescribeResult.ParameterType.STRING, true)      
+            };
+        
+        result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter> {
+            new Process.PluginDescribeResult.OutputParameter('QR_URL_OUTPUT',
+                Process.PluginDescribeResult.ParameterType.STRING),
+            new Process.PluginDescribeResult.OutputParameter('SECRET_OUTPUT',
+                Process.PluginDescribeResult.ParameterType.STRING),
+            new Process.PluginDescribeResult.OutputParameter('IsValid_OUTPUT',
+                Process.PluginDescribeResult.ParameterType.Boolean)
+        };
+        
+        return result;
+    }
+    
+    global Process.PluginResult invoke(Process.PluginRequest request)
+    {   
+        Map<String,String> QR;
+        String URL; 
+        String otp;
+        String secret;
+        Boolean status = false;
+        
+        String userid   = UserInfo.getUserId();  
+        
+        Map<String, Object> result = new Map<String, Object>();
+        
+        List<TwoFactorInfo> twoFactors = [SELECT UserId, Type FROM TwoFactorInfo where userID = :userid];
+        
+        secret = (String)request.inputParameters.get('SECRET_INPUT');
+        
+        if(twoFactors.isEmpty() && secret == null)
+        {
+            QR = Auth.SessionManagement.getQrCode();      
+            URL = QR.get('qrCodeUrl');
+            Secret = QR.get('secret');
+            
+            result.put('QR_URL_OUTPUT', URL);
+            result.put('SECRET_OUTPUT', Secret);
+            
+            return new Process.PluginResult(result);
+        }
+         
+        
+        otp = (String)request.inputParameters.get('OTP_REGISTRATION_INPUT');
+        
+        if(otp == null)
+            otp = (String)request.inputParameters.get('OTP_INPUT');
+        
+        result.put('IsValid_OUTPUT', validate(otp, secret));
+           
+        return new Process.PluginResult(result);
+    }
+      
+    
+    private Boolean validate(String otp, String secret)
+    {
+        String userid   = UserInfo.getUserId();   
+        Boolean status = false;
+        
+         
+        if(secret == null)
+        {
+            try {
+                status = Auth.SessionManagement.validateTotpTokenForUser(otp);
+            } 
+            catch(Exception e)
+            {
+                system.debug('The key is invalid or the current user has attempted too many validations');
+            } 
+            
+            return status;
+        }
+        
+        status = Auth.SessionManagement.validateTotpTokenForKey(secret, otp);
+        if(status == true)
+        {
+           TwoFactorInfo TwoFactor = new TwoFactorInfo(UserId=userid, Type='TOTP', SharedKey=secret);
+
+           insert(TwoFactor);
+        }
+       
+        return status;
+    }    
+}
\ No newline at end of file
diff --git a/scr/classes/TOTPPlugin.cls-meta.xml b/scr/classes/TOTPPlugin.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/TOTPPlugin.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TOTPPluginTest.cls b/scr/classes/TOTPPluginTest.cls
new file mode 100644
index 0000000..e52ccca
--- /dev/null
+++ b/scr/classes/TOTPPluginTest.cls
@@ -0,0 +1,47 @@
+@isTest
+private class TOTPPluginTest
+{
+    static testMethod void getQRCode() {
+     
+        TOTPPlugin totp = new TOTPPlugin();
+        Map<String,Object> inputParams = new Map<String,Object>();
+        Map<String,Object> outputParams = new Map<String,Object>();
+         
+        Map<String,String> QR = Auth.SessionManagement.getQrCode(); 
+         
+        inputParams.put('OTP_INPUT', null);
+         
+        Process.PluginRequest request = new Process.PluginRequest(inputParams);
+        Process.PluginResult result;
+        result = totp.invoke(request);
+        
+        System.AssertEquals(1,1);
+    }
+    
+    static testMethod void validateToken() {
+     
+        TOTPPlugin totp = new TOTPPlugin();
+        Map<String,Object> inputParams = new Map<String,Object>();
+        Map<String,Object> outputParams = new Map<String,Object>();
+         
+        Map<String,String> QR = Auth.SessionManagement.getQrCode(); 
+         
+        inputParams.put('OTP_INPUT', '1234');
+        inputParams.put('SECRET_INPUT', QR.get('secret'));
+         
+        Process.PluginRequest request = new Process.PluginRequest(inputParams);
+        Process.PluginResult result;
+        result = totp.invoke(request);
+        
+        System.AssertEquals(1,1);
+    }
+
+    static testMethod void describeTest() {
+
+        TOTPPlugin totp = new TOTPPlugin();
+        Process.PluginDescribeResult result = totp.describe();
+        
+        System.AssertEquals(result.inputParameters.size(), 3);
+        System.AssertEquals(result.OutputParameters.size(), 3);
+     }
+}
\ No newline at end of file
diff --git a/scr/classes/TOTPPluginTest.cls-meta.xml b/scr/classes/TOTPPluginTest.cls-meta.xml
new file mode 100644
index 0000000..08d159f
--- /dev/null
+++ b/scr/classes/TOTPPluginTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>32.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TSRepairController.cls b/scr/classes/TSRepairController.cls
new file mode 100644
index 0000000..89300ae
--- /dev/null
+++ b/scr/classes/TSRepairController.cls
@@ -0,0 +1,1882 @@
+public without sharing class TSRepairController {
+
+    // 鍩虹Url
+    public String baseUrl { get; private set; }
+    // 鏃ユ姤ID
+    public String repairId {get; set;}
+    public TS_Repair__c tsr {get; set;}
+
+    public String datestr;
+
+    public Integer num {get; set{ num = value;}} //娣诲姞浜у搧鏃朵娇鐢�
+    public String baIds {get; set{ baIds = value;}} //娣诲姞闄勪欢鏃朵娇鐢�
+
+    public Integer BusinessActivitySize {get; set;}
+
+    public String serviceCategoryJSON {get; set;}
+
+
+    public Date OriginalDate { get; set; }//淇敼鏃ユ湡鏌ユ壘鏃ユ姤鏃讹紝閿欒杩樺師
+
+    public List<Attachment> attachments { get; set; }  //闄勪欢
+
+    //椤甸潰鏄剧ず鍐呭
+    public List<RepairInfo> RepairInfoList {get; set;}
+
+    public String temp {get; set;}
+    // Label
+    public Integer initFailureAssetListSize;    //TS鏃ユ姤椤甸潰鏁呴殰鏈哄櫒鍒濆鍖栨暟閲�
+    public Integer maxFailureAssetListSize;     //TS鏃ユ姤椤甸潰鏁呴殰鏈哄櫒灞曠ず鏈�澶ф暟閲�
+    public Integer initBusinessActivityListSize;//TS鏃ユ姤椤甸潰鏁呬笟鍔℃椿鍔ㄥ垵濮嬪寲鏁伴噺
+
+    public User use {get; set;}//鐢ㄦ埛
+    //public List<BusinessActivity__c> activityInItList;
+    public Map<String, String> activityInItMap;
+    //public Map<String, String> activityInItMap1;
+
+    public String fromUserFaultInfoId {get; set;}
+    public String lineno {get; set;}
+
+    public String saveSign;
+
+    public Boolean errorFlag { get; set; }
+    public Map<String, List<String>> errorMessageMap;
+
+    public Map<String, List<BusinessActivity__c>> businessActivityListToMap;
+
+    //  鐜嬮箯浼熷畾涔夊彉閲忓紑濮�
+    // 鍓嶅彴鐐瑰嚮鎸夐挳淇敼鐘舵��
+    public String status {get; set;}
+    // 鍓嶅彴鏄惁鍙互鐐瑰嚮鎸夐挳
+    //onclickType=0鏃跺彧鑳界偣鍑昏崏妗堬紝鐢宠锛沷nclickType=1鏃跺彧鑳界偣鍑婚┏鍥烇紝鎵瑰噯
+    public String onclickType {get; set;} //onclickType=0鏃�
+    //  鐜嬮箯浼熷畾涔夊彉閲忕粨鏉�
+
+    public TSRepairController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+        errorFlag = false;
+        repairId = System.currentPageReference().getParameters().get('id');
+        datestr =  System.currentPageReference().getParameters().get('date');
+    }
+
+    public TSRepairController(ApexPages.StandardController stdController) {
+
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0, path.indexOf('/apex'));
+        }
+        errorFlag = false;
+        repairId = ApexPages.currentPage().getParameters().get('Id');
+        datestr =  System.currentPageReference().getParameters().get('date');
+
+    }
+
+    public PageReference init() {
+        errorMessageMap  = new Map<String, List<String>>();
+        businessActivityListToMap = new Map<String, List<BusinessActivity__c>>();
+        initFailureAssetListSize = Integer.valueOf(System.label.TSRepairPageInitFailureAssetListSize);
+        maxFailureAssetListSize = Integer.valueOf(System.label.TSRepairPageMaxFailureAssetListSize);
+        initBusinessActivityListSize = Integer.valueOf(System.label.TSRepairPageInitBusinessActivityListSize);
+        serviceCategoryJSON = JSON.serialize(TSRepairUtil.GetserviceCategoryMap());
+        activityInItMap = new Map<String, String>();
+
+        temp = '0';
+        BusinessActivitySize = 0;
+        RepairInfoList = new List<RepairInfo>();
+        // 鐜嬮箯浼� 鎺у埗鍓嶅彴鏃ユ姤鐘舵�佹寜閽�
+        onclickType = '0';
+        List<String> selectUserIdList = new List<String>();
+        String userId = UserInfo.getUserId();
+        selectUserIdList.add(userId);
+        use = TSRepairUtil.GetUserList(selectUserIdList)[0];
+        String saveflg = ApexPages.currentPage().getParameters().get('save');
+        if (String.isNotBlank(saveflg)) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, initPagePrompt(saveflg)));
+        }
+        if (repairId != null && repairId != '') {
+
+            GetInfoData(repairId, null);
+            // TS鏃ユ姤鍒涘缓浜� 涓� 褰撳墠鐢ㄦ埛鐨勫姣�
+            if (tsr.CreatedById != UserInfo.getUserId()) {
+                temp = '1';
+
+                onclickType = '-1';
+                // TS鏃ユ姤鐨勪笂绾� 涓� 褰撳墠鐢ㄦ埛鐨勫姣�
+                if (tsr.TSRepairSuperior__c == UserInfo.getUserId()) {
+                    onclickType = '1';
+                }
+            }
+            if (tsr.CreatedDate != Date.today() && tsr.TSReportStatus__c != '鑽夋涓�' && tsr.TSReportStatus__c != '椹冲洖') {
+                temp = '1';
+            }
+            if (tsr.TSReportStatus__c == '纭') {
+                onclickType = '-1';
+            }
+        } else {
+
+            if (String.isBlank(datestr)) {
+                FindTSRepair();
+                if (String.isBlank(repairId)) {
+                    GetInfoData('', null);
+                } else {
+                    return UnabletoEdit('2');
+                }
+
+            } else {
+                String dateTransform = datestr.split(' ')[0].replaceall('-', '');
+                Date updateDate = NFMUtil.parseStr2Date(dateTransform, false);//2020-09-26 00:00:00
+                GetInfoData('', updateDate);
+            }
+
+        }
+
+        return null;
+    }
+
+    public String initPagePrompt(String saveflg) {
+        String result = '';
+        if (saveflg == '1') {
+            result = '鏈嶅姟鏃ユ姤淇濆瓨鎴愬姛';
+        } else if (saveflg == 'Submit') {
+            result = '鏈嶅姟鏃ユ姤鎻愪氦鎴愬姛';
+        } else if (saveflg == 'Draft') {
+            result = '鏈嶅姟鏃ユ姤璋冨洖鎴愬姛';
+        } else if (saveflg == 'Approval') {
+            result = '鏈嶅姟鏃ユ姤纭鎴愬姛';
+        } else if (saveflg == 'Rejected') {
+            result = '鏈嶅姟鏃ユ姤椹冲洖鎴愬姛';
+        } else if (saveflg == '2') {
+            result = '鏈嶅姟鏃ユ姤鍒锋柊鎴愬姛';
+        }
+
+        return result;
+    }
+
+    public PageReference save() {
+
+        errorMessageMap = new Map<String, List<String>>();
+        List<BusinessActivity__c> businessActivityList = new List<BusinessActivity__c>();
+        Map<Integer, User_FaultInfo__c> userFaultInfoMap = new Map<Integer, User_FaultInfo__c>();
+        Map<Integer, List<FailureAsset__c>> failureAssetMap = new Map<Integer, List<FailureAsset__c>>();
+        List<String> deleteBusinessActivityIdList = new List<String>();//鍒犻櫎涓氬姟娲诲姩
+        // 涓氬姟娲诲姩淇℃伅鏄惁姝g‘
+        if (!AuthenticationInformationSave(RepairInfoList)) {
+            return null;
+        }
+
+        Savepoint sp = Database.setSavepoint();
+        try {
+            Boolean tSReportStatusIsApplyFor = false;
+            if (String.isBlank(repairId)) {
+                repairId = TSRepairAssembled(tsr);//TS鏃ユ姤淇濆瓨
+                if (String.isBlank(repairId)) {
+                    return null;
+                }
+            } else {
+                //鏌ユ壘TS鏃ユ姤鐨勭姸鎬�
+                List<TS_Repair__c> tSRepairList = TSRepairUtil.GetTsRepairList(repairId, '', null , null, null, '');
+                if (tSRepairList.size() > 0 ) {
+                    tSReportStatusIsApplyFor = tSRepairList[0].TSReportStatus__c == '鐢宠涓�' ? true : false;
+                }
+                upsert tsr;
+                repairId = tsr.Id;
+            }
+
+            if ( tSReportStatusIsApplyFor && (tsr.TSReportStatus__c == '椹冲洖' ||
+                                              tsr.TSReportStatus__c == '鑽夋涓�') ) {
+                TSRepairStatus();
+                return null;
+
+            }
+
+
+            // 涓氬姟娲诲姩 瑙i櫎涓� 妗堜欢鐨勫叧绯�
+            RepairInfoList = BusinessActivityAndUser_FaultInfoDissociated(RepairInfoList);
+
+            List<String> selectBAIdList = new List<String>();
+            for (RepairInfo info : RepairInfoList) {
+
+                if (String.isNotBlank(info.ba.serviceType__c)) {
+                    info.ba.BusinessATS__c = repairId;
+                    info.ba.BusinessASegment__c = use.TSUserSegment__c;
+                    if (String.isBlank(info.ba.Id) &&
+                            String.isBlank(info.ba.User_FaultInfo__c) &&
+                            info.ba.firstInput__c == '鏄�') {
+                        info.ba.AgreeReportDate__c = tsr.TSReportDate__c;
+                    }
+                    if ('鐢宠涓�'.equals(tsr.TSReportStatus__c)) {
+                        info.ba.BusinessAFirstSubmission__c = Datetime.now();
+                    }
+
+                    if (String.isNotBlank(info.ba.Id)) {
+                        if (info.ba.BaFromUserFaultInfo__c) {
+                            selectBAIdList.add(info.ba.Id);
+                        }
+                    }
+                    info.ba.BaFromUserFaultInfo__c = false;
+                    businessActivityList.add(info.ba);
+
+
+                    info.uf.UFLineNumber__c = info.lineNumber;
+                    info.ba.BusinessALineNumber__c = info.lineNumber;
+                    failureAssetMap.put(info.lineNumber, info.failureAssetList);
+                } else {
+                    if (String.isNotBlank(info.ba.Id)) {
+                        deleteBusinessActivityIdList.add(info.ba.Id);
+                    }
+                }
+            }
+            if (businessActivityList.size() > 0) {
+
+
+                upsert businessActivityList;
+            }
+            // 鍒犻櫎涓氬姟娲诲姩銆佺敤鎴锋晠闅滀俊鎭�
+            if (deleteBusinessActivityIdList != null && deleteBusinessActivityIdList.size() > 0) {
+                TSRepairUtil.deleteBusinessActivityInformation(deleteBusinessActivityIdList);
+
+            }
+            // 閫氳繃 鎼滅储鎸夐挳 鏌ユ壘 鐢ㄦ埛/鏁呴殰淇℃伅锛屽垹闄や笟鍔℃椿鍔ㄤ笅鐨� 鏁呴殰浜у搧淇℃伅 鍜� 闄勪欢 Start
+            if (selectBAIdList.size() > 0) {
+                // 鏌ユ壘 涓氬姟娲诲姩涓嬬殑 鏁呴殰浜у搧淇℃伅 骞跺垹闄�
+                List<FailureAsset__c> deleteFailureAssetList = TSRepairUtil.GetFailureAssetList(null, null, selectBAIdList, null, null);
+                if (deleteFailureAssetList.size() > 0) {
+                    delete deleteFailureAssetList;
+                }
+                // 鏌ユ壘 涓氬姟娲诲姩涓嬬殑 闄勪欢 骞跺垹闄�
+                List<String> parentIdList = new List<String>();
+                List<Attachment> deleteAttachmentList = TSRepairUtil.GetAttachmentList(selectBAIdList);
+                if (deleteAttachmentList.size() > 0) {
+                    delete deleteAttachmentList;
+                }
+            }
+            // 閫氳繃 鎼滅储鎸夐挳 鏌ユ壘 鐢ㄦ埛/鏁呴殰淇℃伅锛屽垹闄や笟鍔℃椿鍔ㄤ笅鐨� 鏁呴殰浜у搧淇℃伅 鍜� 闄勪欢 End
+            if (businessActivityList.size() > 0) {
+
+                Map<String, BusinessActivity__c> updateUserFaultInfoMap = new Map<String, BusinessActivity__c>();
+                List<BusinessActivity__c> updateBusinessActivityList = new List<BusinessActivity__c>();
+
+                // upsert businessActivityList;
+
+                //鏃ユ姤鐘舵�� 纭鐘舵�� 鏌ユ壘鐢ㄦ埛/鏁呴殰淇℃伅鐨� 鏈嶅姟鍐呭(姹囨��)鐨勫��
+                List<String> selectUfIdListPass = new List<String>();
+
+                for ( BusinessActivity__c  ba : businessActivityList) {
+                    updateUserFaultInfoMap.put(ba.Id, ba);
+
+                    if (ba.BusinessAHaveAttachment__c) {
+                        // 鐢ㄦ埛/鏁呴殰淇℃伅涓嬬殑闄勪欢鍏嬮殕涓�浠借嚦涓氬姟娲诲姩
+                        List<String> selectUfIdList = new List<String>();
+                        selectUfIdList.add(ba.User_FaultInfo__c);
+                        TSRepairUtil.insertattachmentCloneList(selectUfIdList, ba.Id);
+
+                        ba.BusinessAHaveAttachment__c = false;
+                        updateBusinessActivityList.add(ba);
+                    }
+
+                    if ('纭'.equals(tsr.TSReportStatus__c)) {
+                        selectUfIdListPass.add(ba.User_FaultInfo__c);
+
+                    }
+                }
+
+                // 鏇存柊 涓氬姟娲诲姩
+                if (updateBusinessActivityList != null && updateBusinessActivityList.size() > 0) {
+                    upsert updateBusinessActivityList;
+                }
+
+                if ('鐢宠涓�'.equals(tsr.TSReportStatus__c) || '纭'.equals(tsr.TSReportStatus__c)) {
+                    if (updateUserFaultInfoMap != null && updateUserFaultInfoMap.size() > 0) {
+                        // 鐢ㄦ埛鏁呴殰淇℃伅璧嬪��
+                        userFaultInfoMap.putAll(UserFaultInfoAssembled(updateUserFaultInfoMap, selectUfIdListPass));
+                    }
+                    if ('鐢宠涓�'.equals(tsr.TSReportStatus__c)) {
+                        upsertFailureAssetStatus(failureAssetMap, businessActivityList);
+                        if ( userFaultInfoMap != null && userFaultInfoMap.size() > 0) {
+                            // 鐢ㄦ埛鏁呴殰鏍锋満璧嬪��
+                            upsertFailureAsset(failureAssetMap, userFaultInfoMap);
+                        }
+                    }
+
+                } else {
+                    // 鏇存柊鏁呴殰浜у搧淇℃伅鐨勪笟鍔℃椿鍔↖D锛屾洿鏂颁笟鍔℃椿鍔ㄧ殑鍚堣鍙版暟
+                    upsertFailureAssetStatus(failureAssetMap, businessActivityList);
+                }
+            }
+        } catch (Exception e) {
+            ApexPages.addMessages(e);
+            errorFlag = true;
+            List<String> errorMessageList = new List<String>();
+            errorMessageList.add(e.getMessage());
+            errorMessageMap.put('TS鏃ユ姤寮傚父', errorMessageList);
+            pagemessages(errorMessageMap);
+            Database.rollback(sp);
+            return  null;
+        }
+        saveSign = '1';
+
+        return UnabletoEdit('1');
+    }
+    // 涓氬姟娲诲姩瑙i櫎涓庢浠剁殑鍏崇郴
+    public List<RepairInfo> BusinessActivityAndUser_FaultInfoDissociated(List<RepairInfo> RepairInfoList) {
+        List<String> deleteBaIdList = new List<String>();
+        List<RepairInfo> RepairInfoListSave = new List<RepairInfo>();
+        for (RepairInfo info : RepairInfoList) {
+
+            if (info.ba.firstInput__c == '鏄�') {
+                String baId = info.ba.Id;
+                // BaFromUserFaultInfo__c涓篢rue锛屼负 閫夋嫨宸叉湁妗堜欢锛屽張閲嶆柊閫夋嫨浜� 棣栨鐧婚檰妗堜欢 涓� [鏄痌锛屼笉鏇存柊 涓氬姟娲诲姩
+                if (info.ba.BaFromUserFaultInfo__c == true) {
+
+                } else {
+                    // BaFromUserFaultInfo__c涓篺alse锛屾湁 Id锛屾鏌� 鍘熸潵鐨勪笟鍔℃椿鍔� 鐨勯娆$櫥闄嗘浠� 鐨� 鍊�
+                    if (String.isNotBlank(baId) && activityInItMap != null && activityInItMap.containsKey(baId)) {
+                        String firstInputOriginalValue = activityInItMap.get(baId);
+                        if (firstInputOriginalValue != info.ba.firstInput__c) {
+                            // 涓嶇浉绛� 鍒犻櫎涓氬姟娲诲姩
+                            deleteBaIdList.add(baId);
+                        } else {
+                            // 涓嶅仛鐗规畩澶勭悊
+                            RepairInfoListSave.add(info);
+                        }
+                    } else {
+                        RepairInfoListSave.add(info);
+                    }
+                }
+            } else {
+                RepairInfoListSave.add(info);
+            }
+        }
+        // 鍒犻櫎涓氬姟娲诲姩
+        if (deleteBaIdList.size() > 0) {
+            TSRepairUtil.deleteBusinessActivityInformation(deleteBaIdList);
+        }
+
+        return RepairInfoListSave;
+    }
+
+    // TS鏃ユ姤琚┏鍥炴垨鐘舵�佺敱鐢宠涓彉鎴愯崏妗堜腑锛屼笌TS鏃ユ姤涓嬩笟鍔℃椿鍔ㄥ叧鑱旂殑 鐢ㄦ埛/鏁呴殰淇℃伅 杩涜杩樺師鎴栧垹闄�
+    public Void TSRepairStatus() {
+        //鑾峰彇涓氬姟娲诲姩鍏宠仈鐨勭敤鎴锋晠闅滀俊鎭疘d,鍙栧嚭鐩稿叧鑱旂殑涓氬姟娲诲姩
+        List<String> ufIdList = new List<String>();
+        List<String> deleteUfIdList =  new List<String>();
+        for (RepairInfo info : RepairInfoList) {
+            String ufId = info.ba.User_FaultInfo__c;
+            if (String.isNotBlank(ufId) && info.ba.firstInput__c == '鍚�') {
+                ufIdList.add(ufId);
+            } else if (String.isNotBlank(ufId) && info.ba.firstInput__c == '鏄�') {
+                deleteUfIdList.add(ufId);
+            }
+        }
+        if (deleteUfIdList.size() > 0) {
+            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(null, deleteUfIdList , null, null, null, '');
+            Map<String, List<BusinessActivity__c>> businessActivityListMap = new Map<String, List<BusinessActivity__c>>();
+            if (activityList.size() > 0) {
+                // 缁熻鐢ㄦ埛/鏁呴殰淇℃伅 涓� 鍏宠仈鐨勪笟鍔℃椿鍔ㄧ殑鏁伴噺 Start
+                for (BusinessActivity__c ba : activityList) {
+                    List<BusinessActivity__c> baList = new List<BusinessActivity__c>();
+                    if (businessActivityListMap.containsKey(ba.User_FaultInfo__c)) {
+                        baList = businessActivityListMap.get(ba.User_FaultInfo__c);
+                    }
+                    baList.add(ba);
+                    businessActivityListMap.put(ba.User_FaultInfo__c, baList);
+
+                }
+                // 缁熻鐢ㄦ埛/鏁呴殰淇℃伅 涓� 鍏宠仈鐨勪笟鍔℃椿鍔ㄧ殑鏁伴噺 End
+                if (businessActivityListMap != null && businessActivityListMap.size() > 0) {
+                    List<String> deleteUfIdList01 = new List<String>();
+                    List<BusinessActivity__c> updateBAlist = new List<BusinessActivity__c>();
+                    for ( String ufId : businessActivityListMap.keySet()) {
+                        // 鐢ㄦ埛鏁呴殰淇℃伅涓嬪彧鏈変竴涓� 涓氬姟娲诲姩
+                        if (businessActivityListMap.get(ufId).size() == 1) {
+                            // 灏嗕笟鍔℃椿鍔� 涓� 鐢ㄦ埛/鏁呴殰淇℃伅 鐩稿叧瀛楁鐨勫�� 娓呯┖ Start
+                            BusinessActivity__c updateBA  = businessActivityListMap.get(ufId)[0];
+                            updateBA.FindManagementCode__c = null;
+                            updateBA.ManagementCode__c = null;
+                            updateBA.User_FaultInfo__c = null;
+                            updateBAlist.add(updateBA);
+                            // 灏嗕笟鍔℃椿鍔� 涓� 鐢ㄦ埛/鏁呴殰淇℃伅 鐩稿叧瀛楁鐨勫�� 娓呯┖ End
+                            deleteUfIdList01.add(ufId);
+                        } else if (businessActivityListMap.get(ufId).size() > 1 ) {
+                            ufIdList.add(ufId);
+                        }
+                    }
+
+                    if (deleteUfIdList01.size() > 0) {
+                        // 鏌ユ壘鐢ㄦ埛/鏁呴殰淇℃伅涓嬬殑 鏁呴殰浜у搧淇℃伅 骞跺垹闄�
+                        List<FailureAsset__c> deleteUFfailureAssetList = TSRepairUtil.GetFailureAssetList(null, deleteUfIdList01, null, null, null);
+
+                        if (deleteUFfailureAssetList.size() > 0) {
+                            delete deleteUFfailureAssetList;
+                        }
+                        // 鏌ユ壘鐢ㄦ埛/鏁呴殰淇℃伅 骞跺垹闄�
+                        List<User_FaultInfo__c> delletefaultInfoList = TSRepairUtil.GetfaultInfoList(deleteUfIdList01, null, null, '');
+                        if (delletefaultInfoList.size() > 0) {
+                            delete delletefaultInfoList;
+                        }
+                        // 鍙樻洿 涓氬姟娲诲姩
+                        if (updateBAlist.size() > 0) {
+                            update updateBAlist;
+                        }
+                    }
+                }
+            }
+        }
+        Map<String, BusinessActivity__c> maxSubmissionMap = new Map<String, BusinessActivity__c>();
+        // 涓� 鐢ㄦ埛/鏁呴殰淇℃伅鐨� 鏈嶅姟鍐呭(姹囨��) 瀛楁 璧嬪��
+        businessActivityListToMap = new Map<String, List<BusinessActivity__c>>();
+        if (ufIdList.size() > 0) {
+            // 鏌ユ壘涓庣敤鎴�/鏁呴殰淇℃伅鍏宠仈鐨勪笟鍔℃椿鍔�
+            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(null, ufIdList , null, null, null, '');
+            if (activityList.size() > 0) {
+
+                for (BusinessActivity__c ba : activityList) {
+
+                    if (ba.BusinessATSReportStatus__c == '鐢宠涓�' ||
+                            ba.BusinessATSReportStatus__c == '纭') {
+                        // 鍙� 鐘舵�佹槸 '鐢宠涓�'/ '纭' 骞朵笖鎻愪氦鏃堕棿鏈�澶у�肩殑涓氬姟娲诲姩 鐢ㄤ簬 鐢ㄦ埛/鏁呴殰淇℃伅鐨勬暟鎹� 杩樺師 Start
+                        String ufId = ba.User_FaultInfo__c;
+                        if (maxSubmissionMap.containsKey(ufId)) {
+                            if (ba.BusinessAFirstSubmission__c  > maxSubmissionMap.get(ufId).BusinessAFirstSubmission__c) {
+                                maxSubmissionMap.put(ufId, ba);
+                            }
+                        } else {
+                            maxSubmissionMap.put(ufId, ba);
+                        }
+                        // 鍙� 鐘舵�佹槸 '鐢宠涓�'/ '纭' 骞朵笖鎻愪氦鏃堕棿鏈�澶у�肩殑涓氬姟娲诲姩 鐢ㄤ簬 鐢ㄦ埛/鏁呴殰淇℃伅鐨勬暟鎹� 杩樺師 End
+                        if (ba.BusinessATSReportStatus__c == '纭') {
+                            List<BusinessActivity__c> baList = new List<BusinessActivity__c>();
+                            if (businessActivityListToMap.containsKey(ba.User_FaultInfo__c)) {
+                                baList = businessActivityListToMap.get(ba.User_FaultInfo__c);
+                            }
+                            baList.add(ba);
+                            businessActivityListToMap.put(ba.User_FaultInfo__c, baList);
+                        }
+
+
+                    }
+
+                }
+            }
+        }
+
+        if (maxSubmissionMap != null && maxSubmissionMap.size() > 0) {
+            Map<String, BusinessActivity__c> baMap = new Map<String, BusinessActivity__c>();
+            List<String> ufIdList01 = new List<String>();
+            List<String> baIdListGetFailureAsset = new List<String>();
+            Map<String, String> BaUfIdMap = new Map<String, String>();
+            for (String ufId : maxSubmissionMap.keySet()) {
+                BusinessActivity__c ba = maxSubmissionMap.get(ufId);
+                ufIdList01.add(ufId);
+                baMap.put(ba.Id, ba);
+                baIdListGetFailureAsset.add(ba.Id);
+                BaUfIdMap.put(ba.Id, ufId);
+            }
+
+            //鍒犻櫎 鐢ㄦ埛/鏁呴殰淇℃伅涓嬬殑 鏁呴殰浜у搧淇℃伅 Start
+            Map<String, List<FailureAsset__c>> selectUFfailureAssetMap = new Map<String, List<FailureAsset__c>>();
+            selectUFfailureAssetMap = TSRepairUtil.GetUserFaultInfMap(ufIdList01, null);
+            List<FailureAsset__c> deleteFailureAssetList = new List<FailureAsset__c>();
+            if (selectUFfailureAssetMap != null && selectUFfailureAssetMap.size() > 0 ) {
+
+                for (String ufId : selectUFfailureAssetMap.keySet()) {
+
+                    for (FailureAsset__c fa : selectUFfailureAssetMap.get(ufId)) {
+                        deleteFailureAssetList.add(fa);
+                    }
+                }
+
+                if (deleteFailureAssetList.size() > 0) {
+                    delete deleteFailureAssetList;
+                }
+            }
+            // 鍒犻櫎 鐢ㄦ埛/鏁呴殰淇℃伅涓嬬殑 鏁呴殰浜у搧淇℃伅 End
+
+            //鐢ㄦ埛/鏁呴殰淇℃伅 鏁版嵁杩樺師 Start
+            List<String> selectUfIdListPass = new List<String>();
+            UserFaultInfoAssembled(baMap, selectUfIdListPass);
+            //鐢ㄦ埛/鏁呴殰淇℃伅 鏁版嵁杩樺師 End
+
+            Map<String, List<FailureAsset__c>> selectBAfailureAssetMap = new Map<String, List<FailureAsset__c>>();
+            if (BaUfIdMap != null && BaUfIdMap.size() > 0 ) {
+                selectBAfailureAssetMap = TSRepairUtil.GetUserFaultInfMap(null, baIdListGetFailureAsset);
+                if ( selectBAfailureAssetMap != null && selectBAfailureAssetMap.size() > 0) {
+                    List<FailureAsset__c> baFailureAssetList = new List<FailureAsset__c>();
+                    List<User_FaultInfo__c> updateUFlist = new List<User_FaultInfo__c>();
+                    for (String baId : selectBAfailureAssetMap.keySet()) {
+                        for (FailureAsset__c fa : selectBAfailureAssetMap.get(baId)) {
+
+                            // 灏� 涓氬姟娲诲姩涓嬬殑 鏁呴殰浜у搧淇℃伅 鍏嬮殕涓�浠� 鑷� 鐢ㄦ埛/鏁呴殰淇℃伅涓� Start
+                            FailureAsset__c cloneFa = fa.clone();
+                            cloneFa.FAActivity__c = null;
+                            cloneFa.Id = null;
+                            cloneFa.FAUserFaultInfo__c = BaUfIdMap.get(baId);
+                            baFailureAssetList.add(cloneFa);
+                            // 灏� 涓氬姟娲诲姩涓嬬殑 鏁呴殰浜у搧淇℃伅 鍏嬮殕涓�浠� 鑷� 鐢ㄦ埛/鏁呴殰淇℃伅涓� End
+                        }
+
+                        // 姹囨�� 鐢ㄦ埛/鏁呴殰淇℃伅 涓嬮潰鐨� 鏁呴殰浜у搧淇℃伅 涓� 鏈哄瀷/浜у搧绯诲垪/鏈鸿韩鍙�/淇濅慨鐘舵�� Start
+                        User_FaultInfo__c updateUserFaultInfo = new  User_FaultInfo__c();
+                        updateUserFaultInfo.Id = BaUfIdMap.get(baId);
+                        updateUserFaultInfo.UserFaultInfoCombinedAmount__c = selectBAfailureAssetMap.get(baId).size();//鍚堣鍙版暟
+                        updateUserFaultInfo = Summation(selectBAfailureAssetMap.get(baId), updateUserFaultInfo);
+                        updateUFlist.add(updateUserFaultInfo);
+
+                        // 姹囨�� 鐢ㄦ埛/鏁呴殰淇℃伅 涓嬮潰鐨� 鏁呴殰浜у搧淇℃伅 涓� 鏈哄瀷/浜у搧绯诲垪/鏈鸿韩鍙�/淇濅慨鐘舵�� End
+                    }
+
+                    if (baFailureAssetList.size() > 0) {
+                        insert baFailureAssetList;
+                    }
+
+                    if (updateUFlist.size() > 0) {
+                        update updateUFlist;
+                    }
+                }
+            }
+        }
+    }
+
+    // 鏂板 TS鏃ユ姤
+    public String TSRepairAssembled(TS_Repair__c tsr) {
+        String result = '';
+        if (tsr.TSReportDate__c == null) {
+            tsr.TSReportDate__c = Date.today();
+        }
+        tsr.TSReportPerson__c = UserInfo.getUserId();
+
+        tsr.TSRepairSuperior__c = use.TSUserSuperior__c ;
+        tsr.TSRepairClass__c = use.TSUserClass__c;
+        tsr.TSReportPerson__c = use.id;
+
+        if (tsr.TSReportStatus__c != '鐢宠涓�') {
+            tsr.TSReportStatus__c = '鑽夋涓�';
+        }
+        tsr.TSRepairDepartment__c = use.TSUserDepartment__c;
+        tsr.TSRepairSegment__c = use.TSUserSegment__c;
+
+        List<TS_Repair__c> tSRepairList = TSRepairUtil.GetTsRepairList('', tsr.TSReportPerson__c, tsr.TSReportDate__c , null, null, '');
+
+        if (tSRepairList != null && tSRepairList.size() > 0) {
+            List<String> errorMessageList = new List<String>();
+            String date01 = String.valueOf(tsr.TSReportDate__c);
+            errorMessageList.add(date01 + '鏃S鏃ユ姤宸插瓨鍦紝璇蜂笉瑕侀噸澶嶅垱寤�,宸插瓨鍦ㄧ殑TS鏃ユ姤鍚嶇О:' + tSRepairList[0].Name);
+            errorMessageMap.put('TS鏃ユ姤寮傚父', errorMessageList);
+            pagemessages(errorMessageMap);
+        } else {
+            upsert tsr;
+            result = tsr.Id;
+        }
+
+        return result;
+    }
+
+    // 鍒锋柊TS鏃ユ姤
+    public PageReference UnabletoEdit(String saveSign) {
+        String url = '/apex/TSRepair?Id=';
+        if (String.isNotBlank(repairId)) {
+            url +=  repairId;
+        }
+        if (String.isNotBlank(saveSign)) {
+            url += '&save=' + saveSign;
+        }
+
+        PageReference  ref = new Pagereference(url);
+        ref.setRedirect(true);
+        return ref;
+    }
+    //涓氬姟娲诲姩鐩稿叧瀛楁璧嬪��
+    public String ServiceContentNewAssembled(String serviceContentNew) {
+        String result = '';
+        if ( String.isNotBlank(serviceContentNew)) {
+            // 閫佷俊鑰�/TS鏃ユ姤鎶ュ憡浜�
+            String username = tsr.TSReportName__c;
+            // TS鏃ユ姤 鎶ュ憡鏃ユ湡
+            Date dt = tsr.TSReportDate__c;
+
+            // 鏈嶅姟鍐呭
+            result += '****** ' + username + ' ' + dt + ' ******\n';
+            result += serviceContentNew;
+        }
+
+        return result;
+
+    }
+    //涓氬姟娲诲姩鐩稿叧瀛楁璧嬪��
+    public String ServiceContentNewBa(BusinessActivity__c ba) {
+        String result = '';
+        // if ( String.isNotBlank(serviceContentNew)) {
+        // // 閫佷俊鑰�/TS鏃ユ姤鎶ュ憡浜�
+        String username = ba.BusinessATSReportReporter__c;
+        // // TS鏃ユ姤 鎶ュ憡鏃ユ湡
+        Date tSReportDate = ba.BusinessATSReportDay__c;
+
+        // 鏈嶅姟鍐呭
+        result += '****** ' + username + ' ' + tSReportDate + ' ******\n';
+        result += ba.BusinessAServiceContentNew__c;
+        // }
+
+        return result;
+
+    }
+    /**
+     * [UserFaultInfoAssembled 鐢ㄦ埛/鏁呴殰淇℃伅瀛楁璧嬪�糫
+     * @param  updateUserFaultInfoMap [涓氬姟娲诲姩鐨勫熀鏈俊鎭痌
+     * @return                        [description]
+     */
+    public Map<Integer, User_FaultInfo__c> UserFaultInfoAssembled(Map<String, BusinessActivity__c> updateUserFaultInfoMap, List<String> selectUfIdListPass) {
+        Map<Integer, User_FaultInfo__c> result = new Map<Integer, User_FaultInfo__c>();
+        List<User_FaultInfo__c> updateUserFaultInfoList = new List<User_FaultInfo__c>();
+        String UserFaultInfoId = '';
+        Map<String, List<Attachment>> insertAttachmentMap = new Map<String, List<Attachment>>();
+        Map<String, User_FaultInfo__c> findfaultInfoMap = new Map<String, User_FaultInfo__c>();
+        if (selectUfIdListPass != null && selectUfIdListPass.size() > 0) {
+            findfaultInfoMap = TSRepairUtil.GetfaultInfoMap(selectUfIdListPass);
+        }
+
+        for (String baId : updateUserFaultInfoMap.keySet()) {
+
+            BusinessActivity__c ba = updateUserFaultInfoMap.get(baId);
+            UserFaultInfoId =  ba.User_FaultInfo__c;
+            User_FaultInfo__c updateUserFaultInfo = new User_FaultInfo__c();
+            if (String.isBlank(UserFaultInfoId)) {
+                updateUserFaultInfo.UserFaultInfoUserArea__c = use.TSUserArea__c;
+                updateUserFaultInfo.UserFaultInfoSuperior__c = use.TSUserSuperior__c;
+                updateUserFaultInfo.UserFaultInfoDepartment__c = use.TSUserDepartment__c;
+                updateUserFaultInfo.UserFaultInfoEmployeeID__c = use.TSEmployeeID__c;
+                updateUserFaultInfo.UserFaultInfoReportPerson__c = use.Id;
+                updateUserFaultInfo.UserFaultInfoClass__c = use.TSUserClass__c;
+                updateUserFaultInfo.UserFaultInfoSegment__c = use.TSUserSegment__c;
+                updateUserFaultInfo.UserFaultInfoReportDate__c = tsr.TSReportDate__c;
+                // updateUserFaultInfo.RecordTypeId = '0120T0000000zFj';
+                updateUserFaultInfo.RecordTypeId = System.label.Case_RecordTypeTSTSReport;
+                
+            } else {
+                //灏嗕笟鍔℃椿鍔ㄤ笅鐨勯檮浠跺厠闅嗚嚦 鐢ㄦ埛/鏁呴殰淇℃伅
+                List<String> selectBAIdList = new List<String>();
+                selectBAIdList.add(baId);
+                TSRepairUtil.insertattachmentCloneList(selectBAIdList, UserFaultInfoId);
+            }
+            updateUserFaultInfo.Id = UserFaultInfoId;
+            updateUserFaultInfo.UserFaultInfoServiceType__c = ba.serviceType__c ;//鏈嶅姟绫诲瀷
+            updateUserFaultInfo.UFFaultContent__c = ba.BusinessAFaultContent__c ;//鏁呴殰鍐呭
+            updateUserFaultInfo.UFRepairDate__c = ba.BusinessARepairDate__c ;//鎶ヤ慨鏃ユ湡
+            updateUserFaultInfo.UFDetermineDate__c = ba.BusinessADetermineDate__c;//鍒ゆ柇鏃ユ湡
+            updateUserFaultInfo.UFDateRequest__c = ba.BusinessADateRequest__c ;//瑕佹眰鏈嶅姟鏃ユ湡
+            updateUserFaultInfo.UFMessageSource__c = ba.BusinessAMessageSource__c ;//淇℃伅鏉ユ簮
+            updateUserFaultInfo.UFNatureService__c = ba.BusinessANatureService__c ;//鏈嶅姟鎬ц川
+            updateUserFaultInfo.UFWithoutReason__c = ba.BusinessAWithoutReason__c ;//鏃犲伩鍘熷洜
+            updateUserFaultInfo.UFDateApproval__c = ba.BusinessADateApproval__c ;//鍚屾剰鎶ヤ环鏃ユ湡
+            updateUserFaultInfo.UserFaultInfoDateQuotation__c = ba.BusinessADateQuotation__c;//鎶ヤ环鏃ユ湡
+            if ('纭'.equals(tsr.TSReportStatus__c)) {//鏈嶅姟鍐呭(姹囨��)
+
+                String getserviceContent  = findfaultInfoMap.get(UserFaultInfoId).UserFaultInfoServiceContent__c;
+                String  serviceContent = ServiceContentNewAssembled(ba.BusinessAServiceContentNew__c);
+
+                if (String.isNotBlank(getserviceContent)) {
+                    updateUserFaultInfo.UserFaultInfoServiceContent__c = getserviceContent + '\n';
+                    updateUserFaultInfo.UserFaultInfoServiceContent__c += serviceContent;
+                } else {
+                    updateUserFaultInfo.UserFaultInfoServiceContent__c = serviceContent;
+                }
+            }
+
+            updateUserFaultInfo.UserFaultInfoServicePlace__c = ba.BusinessAServicePlace__c ;//鏈嶅姟鍦烘墍
+            updateUserFaultInfo.UserFaultInfoBusinessTrip__c = ba.BusinessABusinessTrip__c ;//鍑哄樊鍦�
+            updateUserFaultInfo.UserFaultInfoCompletionDate__c = ba.BusinessACompletionDate__c ;//妗堜欢瀹屾垚鏃�
+            updateUserFaultInfo.UserFaultInfoNextService__c = ba.BusinessANextService__c ;//涓嬫鏈嶅姟鏃堕棿
+            updateUserFaultInfo.UFAccount__c = ba.BusinessAAccount__c ;//瀹㈡埛鍗曚綅(鏌ユ壘)
+            updateUserFaultInfo.UserFaultInfoCustomerUnit__c = ba.BusinessACustomerUnit__c ;//瀹㈡埛鍗曚綅(鏂囨湰)
+            updateUserFaultInfo.UFContact__c = ba.BusinessAContact__c ;//鑱旂郴浜�
+            updateUserFaultInfo.UFPhone__c = ba.BusinessAPhone_F__c ;//鑱旂郴鐢佃瘽
+
+            updateUserFaultInfo.UserFaultInfoServiceCategory__c = ba.BusinessAServiceCategory__c ;//鏈嶅姟鑼冪暣
+            updateUserFaultInfo.UFLineNumber__c = ba.BusinessALineNumber__c;
+            updateUserFaultInfo.UserFaultInfoServiceContractNo__c = ba.BusinessAServiceContractNo__c;//鏈嶅姟鍚堝悓鍙�
+            updateUserFaultInfo.UserFaultInfoServiceResult__c = ba.BusinessAServiceResult__c;//鏈嶅姟缁撴灉
+            List<String> selectUserFaultInfoIdList = new List<String>();
+            selectUserFaultInfoIdList.add(UserFaultInfoId);
+
+            updateUserFaultInfoList.add(updateUserFaultInfo);
+
+            // 鍒犻櫎 鐢ㄦ埛/鏁呴殰淇℃伅涓嬬殑闄勪欢
+            List<Attachment> delectUFAttachmentList = TSRepairUtil.GetAttachmentList(selectUserFaultInfoIdList);
+            if (delectUFAttachmentList != null && delectUFAttachmentList.size() > 0) {
+                delete delectUFAttachmentList;
+            }
+
+
+        }
+
+
+        if (updateUserFaultInfoList.size() > 0 ) {
+            upsert updateUserFaultInfoList;
+            List<String> ufIdList = new List<String>();
+
+            for (User_FaultInfo__c uf : updateUserFaultInfoList) {
+                ufIdList.add(uf.Id);
+            }
+            // 鏌ユ壘 鐢ㄦ埛鏁呴殰淇℃伅 骞跺皢Name璧嬪�肩粰涓氬姟娲诲姩鐩稿叧鐨勫��
+            List<User_FaultInfo__c> faultInfoList = TSRepairUtil.GetfaultInfoList(ufIdList, null, null, '');
+            List<BusinessActivity__c> updateBusinessActivityList = new List<BusinessActivity__c>();
+            Map<String, BusinessActivity__c> updateBusinessActivityMap = new Map<String, BusinessActivity__c>();
+
+            for (String baId : updateUserFaultInfoMap.keySet()) {
+                BusinessActivity__c ba = updateUserFaultInfoMap.get(baId);
+                for (User_FaultInfo__c uf : faultInfoList) {
+                    // if (String.isBlank(ba.FindManagementCode__c)) {
+                    if (ba.User_FaultInfo__c == uf.Id || ba.BusinessALineNumber__c == uf.UFLineNumber__c) {
+                        ba.ManagementCode__c = uf.Name;
+                        ba.FindManagementCode__c = uf.Name;
+                        ba.User_FaultInfo__c = uf.Id;
+                        updateBusinessActivityList.add(ba);
+                        //灏嗕笟鍔℃椿鍔ㄤ笅鐨勯檮浠跺厠闅嗚嚦 鐢ㄦ埛/鏁呴殰淇℃伅
+                        List<String> selectBAIdList = new List<String>();
+                        selectBAIdList.add(baId);
+                        TSRepairUtil.insertattachmentCloneList(selectBAIdList, uf.Id);
+                    }
+                    // }
+                    result.put(Integer.valueOf(uf.UFLineNumber__c), uf);
+                }
+            }
+
+            if (updateBusinessActivityList.size() > 0) {
+                update updateBusinessActivityList;
+            }
+
+        }
+
+        return result;
+    }
+
+    //鏃ユ姤鐘舵�佹槸鑽夋涓垨椹冲洖鐘舵�� 鏁呴殰浜у搧璧嬪��
+    //鏇存柊鏁呴殰浜у搧淇℃伅鐨勪笟鍔℃椿鍔↖D锛屾洿鏂颁笟鍔℃椿鍔ㄧ殑鍚堣鍙版暟
+    public void upsertFailureAssetStatus(Map<Integer, List<FailureAsset__c>> failureAssetMap, List<BusinessActivity__c> businessActivityList) {
+        List<FailureAsset__c> upsertFailureAssetList = new List<FailureAsset__c>();
+        Map<String, List<FailureAsset__c>> combinedAmountMap = new Map<String, List<FailureAsset__c>>();
+        for (BusinessActivity__c ba : businessActivityList) {
+
+            Integer  lineNumber = Integer.valueOf(ba.BusinessALineNumber__c);
+            List<FailureAsset__c>  combinedAmountList = new List<FailureAsset__c>();
+            if ( failureAssetMap != null && failureAssetMap.size() > 0) {
+                for (FailureAsset__c  fa : failureAssetMap.get(lineNumber)) {
+                    if (String.isNotBlank(fa.model__c)) {
+
+                        if (String.isBlank(fa.Id)) {
+                            fa.FAActivity__c = ba.Id;
+                        }
+                        upsertFailureAssetList.add(fa);
+                        combinedAmountList.add(fa);
+                    }
+
+                }
+            }
+
+            combinedAmountMap.put(ba.Id, combinedAmountList);
+        }
+
+        if (upsertFailureAssetList.size() > 0 ) {
+            upsert upsertFailureAssetList;
+        }
+
+        if (combinedAmountMap != null && combinedAmountMap.size() > 0) {
+            List<BusinessActivity__c> updateCombinedAmount = new List<BusinessActivity__c>();
+            for (String baId : combinedAmountMap.keySet()) {
+                BusinessActivity__c updateBa = new BusinessActivity__c();
+                updateBa.Id = baId;
+                updateBa.BusinessACombinedAmount__c = combinedAmountMap.get(baId).size();
+                updateCombinedAmount.add(updateBa);
+            }
+
+            update updateCombinedAmount;
+        }
+    }
+
+    //淇濆瓨鐢ㄦ埛/鏁呴殰鏍锋満
+    public void upsertFailureAsset(Map<Integer, List<FailureAsset__c>> failureAssetMap, Map<Integer, User_FaultInfo__c> userFaultInfoMap) {
+
+        List<FailureAsset__c> upsertFailureAssetList = new List<FailureAsset__c>();
+        List<FailureAsset__c> deleteFailureAssetList = new List<FailureAsset__c>();
+        Map<String, User_FaultInfo__c> updateUserFaultInfoMap = new Map<String, User_FaultInfo__c>();
+        List<String> selectUfIdList = new List<String>();
+
+        Map<String, List<FailureAsset__c>> combinedAmountMap = new Map<String, List<FailureAsset__c>>();
+        for (Integer lineNumber : failureAssetMap.keySet()) {
+
+            User_FaultInfo__c updateUserFaultInfoOriginal = userFaultInfoMap.get(lineNumber);
+            User_FaultInfo__c updateUserFaultInfo = new  User_FaultInfo__c();
+            updateUserFaultInfo.Id = updateUserFaultInfoOriginal.Id;
+            if (failureAssetMap.get(lineNumber).size() > 0) {
+                selectUfIdList.add(updateUserFaultInfo.Id);
+            }
+            List<FailureAsset__c>  combinedAmountList = new List<FailureAsset__c>();
+            String baId = '';
+
+            for (FailureAsset__c fa : failureAssetMap.get(lineNumber)) {
+                if (String.isNotBlank(fa.model__c)) {
+                    // 鑾峰彇涓氬姟娲诲姩ID
+                    baId = fa.FAActivity__c;
+                    // 鏁呴殰鏍锋満 Start
+                    fa.FAUserFaultInfo__c = updateUserFaultInfo.Id;
+                    fa.Id = null;
+                    fa.FAActivity__c = null;
+                    upsertFailureAssetList.add(fa);
+                    // 鏁呴殰鏍锋満 End
+                    combinedAmountList.add(fa);
+
+                } else {
+                    // 鐢ㄦ埛鏁呴殰鏍锋満鐨勬満鍨嬩负绌猴紝骞朵笖鏍锋満瀛樺湪Id锛岄偅涔堝垹闄よ繖涓牱鏈�
+                    if (String.isNotBlank(fa.Id)) {
+                        deleteFailureAssetList.add(fa);
+                    }
+                }
+            }
+
+            if (String.isNotBlank(baId)) {
+                combinedAmountMap.put(baId, combinedAmountList);
+            }
+            updateUserFaultInfo.UserFaultInfoCombinedAmount__c = combinedAmountList.size();
+            updateUserFaultInfo.UserFaultInfoApprovalDate__c = updateUserFaultInfoOriginal.UserFaultInfoApprovalDate__c;
+            updateUserFaultInfo = Summation(failureAssetMap.get(lineNumber), updateUserFaultInfo);
+            updateUserFaultInfoMap.put(updateUserFaultInfo.Id, updateUserFaultInfo);
+
+        }
+        if (selectUfIdList.size() > 0) {
+            List<FailureAsset__c> deleteUFfailureAssetList = TSRepairUtil.GetFailureAssetList(null, selectUfIdList, null, null, null);
+
+            if (deleteUFfailureAssetList.size() > 0) {
+                delete deleteUFfailureAssetList;
+            }
+        }
+
+        if (combinedAmountMap != null && combinedAmountMap.size() > 0) {
+            List<BusinessActivity__c> updateCombinedAmount = new List<BusinessActivity__c>();
+            for (String baId : combinedAmountMap.keySet()) {
+                BusinessActivity__c updateBa = new BusinessActivity__c();
+                updateBa.Id = baId;
+                updateBa.BusinessACombinedAmount__c = combinedAmountMap.get(baId).size();
+                updateCombinedAmount.add(updateBa);
+            }
+
+            update updateCombinedAmount;
+        }
+
+        // 鏇存柊/鏂板 鏁呴殰鏍锋満
+        if (upsertFailureAssetList.size() > 0) {
+            upsert upsertFailureAssetList;
+        }
+        // 鍒犻櫎 鏁呴殰鏍锋満
+        if (deleteFailureAssetList.size() > 0) {
+            delete deleteFailureAssetList;
+        }
+        // 鏇存柊 鐢ㄦ埛/鏁呴殰鏍锋満 鏈哄瀷/浜у搧绯诲垪/鏈鸿韩鍙�/淇濅慨鐘舵��
+        if (updateUserFaultInfoMap != null && updateUserFaultInfoMap.size() > 0) {
+            upsert updateUserFaultInfoMap.values();
+        }
+    }
+    /**
+     * [getValue description]鏁版嵁鎷兼帴
+     * @param  originalValue [鍘熷鍊糫
+     * @param  addValue      [鏂板鍊糫
+     * @return               [description]
+     */
+    public String getValue(String originalValue, String addValue) {
+        // originalValue 绌� addValue 涓嶇┖ 鏁版嵁鎷兼帴
+        // originalValue 绌� addValue 绌�
+        // originalValue 涓嶇┖ addValue 绌�
+        // originalValue 涓嶇┖ addValue 涓嶇┖ 鏁版嵁鎷兼帴
+        if (String.isBlank(originalValue) && String.isNotBlank(addValue)) {
+            originalValue = addValue;
+        } else if (String.isNotBlank(originalValue) && String.isNotBlank(addValue)) {
+            originalValue += ';' + addValue;
+        }
+
+        return originalValue;
+
+    }
+    // 鏈哄瀷/浜у搧绯诲垪/鏈鸿韩鍙�/淇濅慨鐘舵�� 姹囨��
+    public User_FaultInfo__c Summation(List<FailureAsset__c> failureAssetList, User_FaultInfo__c updateUserFaultInfo) {
+        String userFaultInfoModel = '';
+        String userFaultInfoProductSeries = '';
+        String userFaultInfoSerialNumber = '';
+        String userFaultInfoWarrantyStatus = '';
+
+        for (FailureAsset__c fa : failureAssetList) {
+            if (String.isNotBlank(fa.model__c)) {
+
+                // 鏈哄瀷/浜у搧绯诲垪/鏈鸿韩鍙�/淇濅慨鐘舵�� 姹囨�� Start
+                userFaultInfoModel = getValue(userFaultInfoModel, fa.model__c);
+                userFaultInfoProductSeries = getValue(userFaultInfoProductSeries, fa.FAProductSeries__c);
+                userFaultInfoSerialNumber = getValue(userFaultInfoSerialNumber, fa.SerialNumber__c);
+                userFaultInfoWarrantyStatus = getValue(userFaultInfoWarrantyStatus, fa.WarrantyStatus__c);
+                // 鏈哄瀷/浜у搧绯诲垪/鏈鸿韩鍙�/淇濅慨鐘舵�� 姹囨�� End
+            }
+
+            updateUserFaultInfo.UserFaultInfoModel__c = userFaultInfoModel;//鏈哄瀷
+            updateUserFaultInfo.UserFaultInfoProductSeries__c = userFaultInfoProductSeries;//浜у搧绯诲垪
+            updateUserFaultInfo.UserFaultInfoSerialNumber__c = userFaultInfoSerialNumber;//鏈鸿韩鍙�
+            updateUserFaultInfo.UserFaultInfoWarrantyStatus__c = userFaultInfoWarrantyStatus;//淇濅慨鐘舵��
+        }
+
+        return updateUserFaultInfo;
+    }
+
+    // 鍒濆鍖朤S鏃ユ姤
+    public void GetInfoData(String repairId, Date dd) {
+        activityInItMap = new Map<String, String>();
+        //activityInItMap1 = new Map<String, String>();
+
+        if (String.isNotBlank(repairId)) {
+
+            List<TS_Repair__c> TSRepairs = TSRepairUtil.GetTsRepairList(repairId, '', null, null, null, '');
+            tsr = TSRepairs[0];
+            List<String> selectRepairIdList = new List<String>();
+            selectRepairIdList.add(repairId);
+            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(selectRepairIdList, null, null, null, null, '');
+
+            // 鐢ㄦ埛鏁呴殰淇℃伅
+            Map<String, User_FaultInfo__c> user_FaultMap = new Map<String, User_FaultInfo__c>();
+            // 鐢ㄦ埛鏁呴殰鏍锋満
+            Map<String, List<FailureAsset__c>> failureAssetMap = new Map<String, List<FailureAsset__c>>();
+            // 鏌ユ壘涓氬姟娲诲姩涓嬬殑闄勪欢
+            Map<String, List<Attachment>> attachmentsMap = new Map<String, List<Attachment>>();
+
+            if (activityList.size() > 0) {
+                //activityInItList = activityList
+                List<String> selectUfIdList = new List<String>();
+                List<String> selectbaIdList = new List<String>();
+                for (BusinessActivity__c ba : activityList) {
+                    selectUfIdList.add(ba.User_FaultInfo__c);
+                    selectbaIdList.add(ba.Id);
+                    activityInItMap.put(ba.Id, ba.firstInput__c );
+                    //activityInItMap1.put(ba.Id,ba.firstInput__c);
+                }
+                //system.debug('activityInItMap--->'+activityInItMap);
+                user_FaultMap = TSRepairUtil.GetfaultInfoMap(selectUfIdList);
+                failureAssetMap = TSRepairUtil.GetUserFaultInfMap(null, selectbaIdList);
+                attachmentsMap =  TSRepairUtil.GetAttachmentMap(selectbaIdList);
+                DataAssembly(activityList, user_FaultMap, failureAssetMap, attachmentsMap);
+            } else {
+                additionBusinessActivity(0);
+            }
+        } else {
+            //鍒濆鍖� 鏃ユ姤
+            tsr = new TS_Repair__c();
+            if (dd != null) {
+                tsr.TSReportDate__c = dd;
+            } else {
+                tsr.TSReportDate__c = Date.today();
+            }
+            tsr.TSReportPerson__c = UserInfo.getUserId();
+
+            tsr.TSRepairSuperior__c = use.TSUserSuperior__c ;
+            tsr.TSRepairClass__c = use.TSUserClass__c;
+            tsr.TSReportPerson__c = use.id;
+            tsr.TSReportStatus__c = '鑽夋涓�';
+            tsr.TSRepairDepartment__c = use.TSUserDepartment__c;
+            tsr.TSRepairSegment__c = use.TSUserSegment__c;
+
+            List<BusinessActivity__c> activityList = new List<BusinessActivity__c>();
+            DataAssembly(activityList, null, null, null);
+        }
+
+    }
+    // 椤甸潰鏁版嵁缁勮
+    public void DataAssembly(List<BusinessActivity__c> activityList,
+                             Map<String, User_FaultInfo__c> user_FaultMap,
+                             Map<String, List<FailureAsset__c>> failureAssetMap,
+                             Map<String, List<Attachment>> attachmentsMap) {
+        RepairInfoList = new List<RepairInfo>();
+
+        User_FaultInfo__c uf = new User_FaultInfo__c();
+
+
+        for (BusinessActivity__c ba : activityList) {
+            // 椤甸潰鏄剧ず 鐢ㄦ埛/鏁呴殰淇℃伅
+            if (user_FaultMap != null && user_FaultMap.size() > 0) {
+                if (user_FaultMap.containsKey(ba.User_FaultInfo__c)) {
+                    uf = user_FaultMap.get(ba.User_FaultInfo__c);
+                }
+            }
+            // 椤甸潰鏄剧ず 鏁呴殰鏍锋満
+            List<FailureAsset__c> faList = new List<FailureAsset__c>();
+            if (failureAssetMap != null && failureAssetMap.size() > 0) {
+                if (failureAssetMap.containsKey(ba.Id)) {
+                    faList = failureAssetMap.get(ba.Id);
+                }
+                Integer size = faList.size();
+                if ( size < initFailureAssetListSize) {
+
+                    faList = getFailureAssetList(faList, size);
+                }
+            } else {
+                faList = getFailureAssetList(null, 0);
+            }
+            // 椤甸潰鏄剧ず 闄勪欢
+            List<Attachment> attachments = new List<Attachment>();
+            if (attachmentsMap.containsKey(ba.Id)) {
+                attachments = attachmentsMap.get(ba.Id);
+            }
+            RepairInfo re = new RepairInfo(tsr, ba, uf, faList, BusinessActivitySize, attachments);
+            RepairInfoList.add(re);
+            BusinessActivitySize++;
+        }
+
+        Integer index = activityList.size();
+        additionBusinessActivity(index);
+    }
+
+    //娣诲姞涓氬姟娲诲姩
+    public void addBusinessActivity () {
+        // 鐢ㄦ埛/鏁呴殰淇℃伅 鍒濆鍖栬祴鍊�
+        User_FaultInfo__c uf = new User_FaultInfo__c();
+        uf.UserFaultInfoUserArea__c = use.TSUserArea__c;
+        uf.UserFaultInfoSuperior__c = use.TSUserSuperior__c;
+        uf.UserFaultInfoDepartment__c = use.TSUserDepartment__c;
+        uf.UserFaultInfoEmployeeID__c = use.TSEmployeeID__c;
+        uf.UserFaultInfoReportPerson__c = use.Id;
+        uf.UserFaultInfoClass__c = use.TSUserClass__c;
+        uf.UserFaultInfoSegment__c = use.TSUserSegment__c;
+        uf.UserFaultInfoReportDate__c = Date.today();
+
+        List<String> selectUfIdList = new List<String>();
+        selectUfIdList.add(uf.Id);
+        List<User_FaultInfo__c> uflist = TSRepairUtil.GetfaultInfoList(selectUfIdList, null, null, '');
+        //鍒濆鍖栦笟鍔℃椿鍔�
+        BusinessActivity__c ba = new BusinessActivity__c();
+        ba.StartTimeHour__c = '0';
+        ba.StartTimeMinute__c = '00';
+        ba.EndTimeHour__c = '0';
+        ba.EndTimeMinute__c = '00';
+        ba.workingHours__c = 0.00;
+        ba.firstInput__c = '鏄�';
+        ba.BusinessAFirstSubmission__c = null;
+        List<FailureAsset__c> faList = getFailureAssetList(null, 0);
+        List<Attachment> attachments = new List<Attachment>();
+        RepairInfo re = new RepairInfo(tsr, ba, uf, faList, BusinessActivitySize, attachments);
+
+        BusinessActivitySize++;
+        RepairInfoList.add(re);
+
+    }
+    //娣诲姞浜у搧
+    public void addFailureAsset() {
+        for (RepairInfo ri : RepairInfoList) {
+            if (ri.lineNumber == num) {
+                if (ri.failureAssetList.size() < maxFailureAssetListSize) {
+                    FailureAsset__c fa = new FailureAsset__c();
+                    ri.failureAssetList.add(fa);
+                    if (ri.failureAssetList.size() == maxFailureAssetListSize) {
+                        ri.disabled = true;
+                    }
+                }
+            }
+        }
+    }
+    // 鏈嶅姟鑼冪暣 璧嬪��
+    public void updateServiceCategory() {
+
+        for (RepairInfo ri : RepairInfoList) {
+            if (ri.lineNumber == num) {
+                Map<String, String>  serviceCategoryMap = TSRepairUtil.GetserviceCategoryMap();
+                String serviceType = serviceCategoryMap.get(ri.ba.serviceType__c);
+                ri.ba.BusinessAServiceCategory__c = serviceType;
+
+            }
+        }
+    }
+    // TS鏃ユ姤椤甸潰鍒濆鍖� 鏄剧ず 涓氬姟娲诲姩 鏁伴噺
+    public void additionBusinessActivity(Integer index) {
+        for (Integer i = index ; i < initBusinessActivityListSize; i++) {
+            addBusinessActivity();
+        }
+    }
+    //  TS鏃ユ姤椤甸潰鍒濆鍖� 鏄剧ず 鏁呴殰鏍锋満 鏁伴噺
+    public List<FailureAsset__c> getFailureAssetList(List<FailureAsset__c> faList, Integer index) {
+        List<FailureAsset__c> result = new List<FailureAsset__c>();
+        if (faList != null && faList.size() > 0) {
+            result = faList;
+        }
+        for (Integer i = index ; i < initFailureAssetListSize; i++) {
+            FailureAsset__c fa = new FailureAsset__c();
+            result.add(fa);
+        }
+
+        return result;
+    }
+
+    //TS鏃ユ姤椤甸潰锛屼慨鏀规棩鏈熸煡鎵惧搴旀棩鏈熺殑TS鏃ユ姤
+    public PageReference checkReportDate() {
+        Date tsDate = tsr.TSReportDate__c;
+        if (tsDate == null) {
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '鎶ュ憡鏃ユ湡涓虹┖璇风‘璁�'));
+            tsr.TSReportDate__c  = OriginalDate;
+            return null;
+        }
+        String userId = UserInfo.getUserId();
+        List<TS_Repair__c> TSRepairs = TSRepairUtil.GetTsRepairList('', userId, tsDate, null, null, '');
+        if (TSRepairs != null && TSRepairs.size() > 0) {
+
+            repairId = TSRepairs[0].Id;
+            return UnabletoEdit('2');
+        } else {
+
+            return SkipNewTSRepairPage(tsDate);
+        }
+    }
+    // 璺宠浆鑷虫柊椤甸潰
+    public PageReference SkipNewTSRepairPage(Date newDate) {
+
+        PageReference   ref = new Pagereference('/apex/TSRepair?date=' + newDate);
+
+        ref.setRedirect(true);
+        return ref;
+    }
+
+    //璺宠浆鍒颁笂浼犻檮浠堕〉闈�
+    public PageReference uploadingAttachment() {
+        save();
+        if (errorMessageMap != null && errorMessageMap.size() > 0) {
+            return null;
+        }
+        String pid = getParentId();
+        if (String.isBlank(pid)) {
+            return null;
+        }
+        PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + pid + '&retURL=%2Fapex/TSRepair?id=' + repairId);
+        ref.setRedirect(true);
+        return ref;
+    }
+    // 鑾峰彇闄勪欢鐨勭埗Id
+    public String getParentId() {
+        String result = '';
+        if (String.isNotBlank(baIds.split('/')[0])) {
+            result = baIds.split('/')[0];
+        } else {
+            Integer lineNumber = Integer.ValueOf(baIds.split('/')[1]);
+            // 鏍规嵁TS鏃ユ姤鏌ユ壘涓氬姟娲诲姩
+            List<String> selectRepairIdList = new List<String>();
+            selectRepairIdList.add(repairId);
+            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(selectRepairIdList, null, null, null, null, '');
+            if (activityList.size() > 0) {
+                for (BusinessActivity__c ba : activityList) {
+                    if (ba.BusinessALineNumber__c == lineNumber) {
+                        result = ba.Id;
+                    }
+                }
+            }
+
+            if (String.isBlank(result)) {
+                List<String> errorMessageList = new List<String>();
+                errorMessageList.add('闄勪欢涓婁紶澶辫触锛屾湇鍔$被鍨嬩负绌猴紝璇风‘璁�');
+                errorMessageMap.put(baIds.split('/')[1], errorMessageList);
+                pagemessages(errorMessageMap);
+            }
+        }
+
+
+        return result;
+    }
+
+    // 鏌ユ壘褰撳ぉ鐨凾S鏃ユ姤
+    public void FindTSRepair() {
+        Date  tSReportDate = Date.today();
+        String ownId = UserInfo.getUserId();
+
+        List<TS_Repair__c>  tsRepairList = TSRepairUtil.GetTsRepairList('', ownId, tSReportDate, null, null, '');
+
+        if (tsRepairList.size() > 0) {
+            repairId = tsRepairList[0].Id;
+        }
+
+    }
+
+// 鐜嬮箯浼� 鍓嶅彴鐐瑰嚮鎸夐挳淇敼鐘舵��
+    public PageReference setStatus() {
+
+        if (status != null && status != '') {
+
+            if (approvalOfValidationPass(status, RepairInfoList)) {
+                tsr.TSReportStatus__c = status;
+                save();
+            }
+
+            if (errorMessageMap != null && errorMessageMap.size() > 0) {
+                if ('鐢宠涓�'.equals(status)) {
+                    status = '鑽夋涓�';
+                }
+                pagemessages(errorMessageMap);
+
+                return null;
+            }
+        }
+        String statusSign = '1';
+
+        if ('鐢宠涓�'.equals(status)) {
+            statusSign = 'Submit';
+        } else if ('鑽夋涓�'.equals(status)) {
+            statusSign = 'Draft';
+        } else if ('纭'.equals(status)) {
+            statusSign = 'Approval';
+        } else if ('椹冲洖'.equals(status)) {
+            statusSign = 'Rejected';
+        }
+        return UnabletoEdit(statusSign);
+    }
+    public Boolean approvalOfValidationPass(String status, List<RepairInfo> RepairInfoList) {
+        errorMessageMap  = new Map<String, List<String>>();
+        errorFlag = false;
+        List<String> errorMessageList = new List<String>();
+
+        List<TS_Repair__c> TSRepairs = TSRepairUtil.GetTsRepairList(repairId, '', null, null, null, '');
+
+
+        for (RepairInfo info : RepairInfoList) {
+
+            String code = info.ba.FindManagementCode__c;
+
+            if ('纭'.equals(status)) {
+
+                // 楠岃瘉鏄惁绗﹀悎鎵瑰噯瑙勫垯
+                Boolean haveRead = info.ba.BusinessAApprovalOpinion__c != '鍚屾剰';//瀹℃壒鎰忚 涓嶆槸 鍚屾剰
+
+                if (String.isNotBlank(info.ba.Id) && haveRead) {
+
+                    errorFlag = true;
+                    String errorMessage = '涓氬姟娲诲姩 绠$悊缂栫爜 [ ' + code + ' ] 瀹℃壒鎰忚涓嶆槸鍚屾剰涓嶈兘瀹℃壒' ;
+                    errorMessageList.add(errorMessage);
+                    continue;
+                }
+                // 鍒ゆ柇涓氬姟娲诲姩鐨� 妗堜欢瀹屾垚鏃� 鏉ヤ慨鏀� 鐢ㄦ埛鏁呴殰淇℃伅鐨� 鎵瑰噯鏃� BusinessACompletionDate__c
+                if (info.ba.BusinessACompletionDate__c != null ) {
+                    info.uf.UserFaultInfoApprovalDate__c = Date.today();
+                }
+                // 璁剧疆鏃ユ姤鎵瑰噯鏃�
+                tsr.TSApprovalDate__c = Date.today();
+
+            }  else if ('鐢宠涓�'.equals(status)) {
+
+            }
+        }
+
+        if ('纭'.equals(status)) {
+
+            //鍒ゆ柇TS鏃ユ姤鏈�鍚庝慨鏀规棩鏈熸槸鍚︿竴鑷�
+            if (tsr.LastModifiedDate != TSRepairs[0].LastModifiedDate) {
+                errorFlag = true;
+                String errorMessage = '鏃ユ姤宸茶鎻愪氦浜烘洿鏂帮紝璇峰埛鏂板悗鍐嶇‘璁�';
+                errorMessageList.add(errorMessage);
+
+            }
+
+        }  else if ('鐢宠涓�'.equals(status)) {
+
+            if (!AuthenticationInformation(RepairInfoList)) {
+                errorFlag = true;
+            }
+            if (tsr.TSRepairFirstSubmission__c == null) {
+                tsr.TSRepairFirstSubmission__c = Datetime.now();
+
+            }
+        }  else if ('椹冲洖'.equals(status)) {
+
+            //鍒ゆ柇TS鏃ユ姤鏈�鍚庝慨鏀规棩鏈熸槸鍚︿竴鑷�
+            if (tsr.LastModifiedDate != TSRepairs[0].LastModifiedDate) {
+                errorFlag = true;
+                String errorMessage = '鏃ユ姤宸茶鎻愪氦浜烘洿鏂帮紝璇峰埛鏂板悗鍐嶇‘璁や俊鎭�';
+                errorMessageList.add(errorMessage);
+
+            }
+
+            if (String.isBlank(tsr.TSRepairDismissReason__c)) {
+                errorFlag = true;
+                String errorMessage = '椹冲洖鐞嗙敱涓嶈兘涓虹┖锛岃纭';
+                errorMessageList.add(errorMessage);
+            }
+        }
+        if (errorMessageList.size() > 0) {
+            errorMessageMap.put('TS鏃ユ姤寮傚父', errorMessageList);
+        }
+
+        if (errorFlag && errorMessageMap != null && errorMessageMap.size() > 0) {
+            pagemessages(errorMessageMap);
+            return false;
+        }
+
+        return true;
+    }
+    // 鑾峰彇鏃堕棿鎴�
+    public Long GetTimestamp(String timenow, Integer hour, Integer minute, Date tsReportDate) {
+        Long result = null;
+
+        if (String.isNotBlank(timenow)) {
+            List<String> timeList = timenow.split('-');
+
+            Integer year = Integer.valueOf(timeList[0]);
+            Integer month = Integer.valueOf(timeList[1]);
+            Integer day = Integer.valueOf(timeList[2]);
+            Integer timehour = Integer.valueOf(timeList[3]);
+            Integer timeminute = Integer.valueOf(timeList[4]);
+            result =  Datetime.newInstanceGmt(year, month, day, timehour, timeminute, 0).getTime();
+        } else {
+            Integer year = tsReportDate.year();
+            Integer month = tsReportDate.month();
+            Integer day = tsReportDate.day();
+            result =  Datetime.newInstanceGmt(year, month, day, hour, minute, 0).getTime();
+        }
+        return result;
+    }
+
+    public void initBusinessActivity() {
+        if (String.isNotBlank(fromUserFaultInfoId)) {
+            List<String> ufIdList = new List<String>();
+            ufIdList.add(fromUserFaultInfoId);
+            List<User_FaultInfo__c> faultInfoList = TSRepairUtil.GetfaultInfoList(ufIdList, null, null, '');
+            BusinessActivity__c ba = TSRepairUtil.BusinessActivityAssembled(faultInfoList);
+            // 鏌ヨ闄勪欢
+            List<Attachment> attachmentList =  TSRepairUtil.GetAttachmentCloneList(ufIdList);
+            // 鏌ヨ 鐢ㄦ埛鏁呴殰鏍锋満
+            List<FailureAsset__c> failureAssetList = TSRepairUtil.GetFailureAssetList(null, ufIdList, null, null, null);
+            List<FailureAsset__c> baFailureAssetList = new List<FailureAsset__c>();
+            if (failureAssetList.size() > 0) {
+
+                for (FailureAsset__c fa : failureAssetList) {
+                    FailureAsset__c cloneFa = fa.clone();
+                    cloneFa.FAActivity__c = null;
+                    cloneFa.Id = null;
+                    cloneFa.FAUserFaultInfo__c = null;
+                    baFailureAssetList.add(cloneFa);
+                }
+            }
+
+            if (baFailureAssetList.size() < 3) {
+                baFailureAssetList = getFailureAssetList(baFailureAssetList, baFailureAssetList.size());
+            }
+            for (RepairInfo repairInfo : RepairInfoList) {
+                Integer linenoInteger = Integer.valueof(lineno);
+                if (repairInfo.lineNumber == linenoInteger) {
+                    String baId = null;
+                    if (String.isNotBlank(repairInfo.ba.Id)) {
+                        baId = repairInfo.ba.Id;
+                    }
+                    repairInfo.ba = ba;
+                    repairInfo.ba.Id = baId;
+                    repairInfo.attachmentLsit = attachmentList;
+                    repairInfo.failureAssetList = baFailureAssetList;
+                }
+            }
+        }
+    }
+    // 寮傚父淇℃伅鎻愮ず
+    public void pagemessages(Map<String, List<String>> errorMessageMap) {
+        for (String key : errorMessageMap.keySet()) {
+            String  title = '';
+            if ('TS鏃ユ姤寮傚父'.equals(key)) {
+                title = 'TS鏃ユ姤寮傚父淇℃伅濡備笅锛�';
+            } else {
+                title = '涓氬姟娲诲姩 [ ' + key + ' ] 寮傚父淇℃伅濡備笅锛�' ;
+            }
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, title));
+            for (String errorMessage : errorMessageMap.get(key)) {
+
+                String body = '涓氬姟娲诲姩 [ ' + key + ' ], ' + errorMessage + '';
+                if ('TS鏃ユ姤寮傚父'.equals(key)) {
+                    body = errorMessage;
+                }
+                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, body));
+            }
+        }
+    }
+
+    //姝e父淇濆瓨鏃� 楠岃瘉 瀛楁鏈夊�� 鏄惁婊¤冻鏉′欢
+    public Boolean AuthenticationInformationSave(List<RepairInfo>  RepairInfoList) {
+        errorFlag = false;
+        for (RepairInfo info : RepairInfoList) {
+
+            List<String> errorMessageList = new List<String>();
+            String key = PromptMessage(info.ba, info.lineNumber);
+            if (String.isNotBlank(info.ba.serviceType__c)) {
+
+                if (String.isBlank(key)) {
+                    continue;
+                }
+                // 妗堜欢瀹屾垚鏃�
+                if (info.ba.BusinessACompletionDate__c != null) {
+                    if (info.ba.BusinessACompletionDate__c != tsr.TSReportDate__c) {
+                        errorFlag = true;
+                        String errorMessage =  '妗堜欢瀹屾垚鏃ュ彧鑳芥槸鎶ュ憡鏃ユ湡锛岃纭\n';
+                        errorMessageList.add(errorMessage);
+                    }
+                }
+
+                if ('鍚�'.equals(info.ba.firstInput__c) && String.isBlank(info.ba.User_FaultInfo__c)) {
+                    errorFlag = true;
+                    String errorMessage =  '璇锋绱㈡湁鏁堢殑绠$悊缂栫爜\n';
+                    errorMessageList.add(errorMessage);
+                }
+
+                Boolean ServiceCategoryIsRepair = info.ba.BusinessAServiceCategory__c == 'Repair';
+                // 鏈嶅姟鑼冪暣 涓� Repair 蹇呭~楠岃瘉
+                if (ServiceCategoryIsRepair) {
+
+                    String accountId = info.ba.BusinessAAccount__c;
+
+                    if (String.isBlank(accountId)) {
+
+                        //1> 瀹㈡埛鍗曚綅 Id 涓虹┖ 鎶ラ敊
+                        errorFlag = true;
+                        String errorMessage = '瀹㈡埛鍗曚綅 鍚嶇О 涓虹┖,璇风‘璁n';
+                        errorMessageList.add(errorMessage);
+                    }
+                    // 4> 鏍规嵁鑱旂郴浜篒d 纭璇ヨ仈绯讳汉鏄惁鏄� 瀹㈡埛鍗曚綅涓嬬殑鑱旂郴浜�
+                    String contactId = info.ba.BusinessAContact__c;
+                    if (String.isNotBlank(contactId)) {
+                        List<Contact> contactList = TSRepairUtil.GetContactList(contactId, null, null, '');
+                        if (contactList.size() <= 0) {
+                            String errorMessage =  '鑱旂郴浜� 鏃犳晥 璇风‘璁n';
+                            errorFlag = true;
+                            errorMessageList.add(errorMessage);
+                        } else {
+                            // 鏌ユ壘鑱旂郴浜� 鑾峰彇 鑱旂郴浜虹殑瀹㈡埛 涓庡鎴峰崟浣嶈繘琛屾瘮瀵�
+                            String contactAccountId = contactList[0].AccountId__c;
+                            if (String.isNotBlank(accountId)) {
+                                accountId = accountId.substring(0, 15);
+                                String contactName = contactList[0].Name;
+                                if (!accountId.equals(contactAccountId)) {
+                                    String errorMessage = '鑱旂郴浜� [ ' + contactName + ' ] 涓嶆槸瀹㈡埛涓嬬殑鑱旂郴浜� 璇风‘璁n';
+                                    errorFlag = true;
+                                    errorMessageList.add(errorMessage);
+                                }
+                            } else {
+                                String errorMessage =  '瀹㈡埛鍗曚綅涓虹┖  鑱旂郴浜烘棤娉曢獙璇佹槸鍚︽湁鏁� 璇风‘璁n';
+                                errorFlag = true;
+                                errorMessageList.add(errorMessage);
+                            }
+
+
+                        }
+
+                    }
+
+                    // 鍒ゆ柇鏃ユ湡
+                    if (info.ba.BusinessADetermineDate__c != null &&  info.ba.BusinessARepairDate__c != null) {
+                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADetermineDate__c) {
+                            // 鎶ラ敊
+                            String errorMessage = '鍒ゆ柇鏃ユ湡灏忎簬鎶ヤ慨鏃ユ湡锛岃纭';
+                            errorMessageList.add(errorMessage);
+                        }
+                    }
+
+                    // 瑕佹眰鏈嶅姟鏃ユ湡
+                    if (info.ba.BusinessADateRequest__c != null && info.ba.BusinessARepairDate__c != null) {
+                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADateRequest__c) {
+                            // 鎶ラ敊
+                            String errorMessage = '瑕佹眰鏈嶅姟鏃ユ湡灏忎簬鎶ヤ慨鏃ユ湡锛岃纭';
+
+                            errorMessageList.add(errorMessage);
+                        }
+                    }
+
+                    if (info.ba.BusinessANatureService__c == '鏈夊伩') {
+
+                        if (info.ba.BusinessADateApproval__c > tsr.TSReportDate__c) {
+                            String errorMessage = '鍚屾剰鎶ヤ环鏃ユ湡 涓嶈兘澶т簬鎶ュ憡鏃ユ湡锛岃纭';
+                            errorMessageList.add(errorMessage);
+                        }
+
+                        if (info.ba.BusinessADateQuotation__c != null && info.ba.BusinessARepairDate__c != null) {
+
+                            if (info.ba.BusinessADateQuotation__c < info.ba.BusinessARepairDate__c) {
+                                String errorMessage = '鎶ヤ环鏃ユ湡 涓嶈兘鏃╀簬鎶ヤ慨鏃ユ湡锛岃纭';
+                                errorMessageList.add(errorMessage);
+                            }
+
+                        }
+                    }
+
+
+                }
+
+            } else {
+                //if (String.isNotBlank(info.ba.Id) && tsr.TSRepairFirstSubmission__c != null) {
+                //    String errorMessage = '宸茬敵璇疯繃鐨勪笟鍔℃椿鍔紝涓嶅彲鍒犻櫎';
+
+                //    errorMessageList.add(errorMessage);
+
+                //}
+            }
+
+            if ( errorMessageList.size() > 0) {
+                errorFlag = true;
+
+                errorMessageMap.put(key, errorMessageList);
+            }
+
+        }
+        if (errorFlag) {
+            pagemessages(errorMessageMap);
+            return false;
+        }
+        return true;
+    }
+
+    // TS鏃ユ姤鐢宠鏃堕獙璇佹椿鍔ㄤ俊鎭�
+    public Boolean AuthenticationInformation(List<RepairInfo>  RepairInfoList) {
+        errorFlag = false;
+        Integer serviceTypeQuantity = 0;
+        for (RepairInfo info : RepairInfoList) {
+
+            if (String.isNotBlank(info.ba.serviceType__c)) {
+                serviceTypeQuantity = 1;
+                String key = PromptMessage(info.ba, info.lineNumber);
+                List<String> errorMessageList = new List<String>();
+                if (String.isBlank(key)) {
+                    continue;
+                }
+                Boolean isNotZero = info.ba.BusinessACombinedAmount__c != null && info.ba.BusinessACombinedAmount__c != 0 ; //鍚堣鍙版暟 涓嶄负 0
+                String code = info.ba.FindManagementCode__c;
+                //鑻ョ敤鎴峰湪娣诲姞瀹岀敤鎴锋晠闅滄牱鏈� 鐩存帴鐐瑰嚮 鐢宠涓�
+                Boolean needVerification = false;
+                for (FailureAsset__c fa : info.failureAssetList) {
+                    //1>鑻� 鏁呴殰鏍锋満 鐨� 鏈哄瀷涓嶄负绌� 鎴戜滑灏辫楠岃瘉
+                    if (!needVerification) {
+                        if (String.isNotBlank(fa.model__c)) {
+                            needVerification = true;
+                        }
+                    }
+
+                }
+
+                if (String.isBlank(info.ba.BusinessAServiceCategory__c)) {
+                    String errorMessage = '鏈嶅姟鑼冪暣 涓嶈兘涓虹┖锛岃纭\n';
+                    errorMessageList.add(errorMessage);
+                }
+
+                if ('鍚�'.equals(info.ba.firstInput__c) && String.isBlank(info.ba.User_FaultInfo__c)) {
+                    errorFlag = true;
+                    String errorMessage =  '璇锋绱㈡湁鏁堢殑绠$悊缂栫爜\n';
+                    errorMessageList.add(errorMessage);
+                }
+                // 鑾峰彇褰撳墠鏃堕棿鐨勬椂闂存埑
+                String timenow = Datetime.now().format('yyyy-MM-dd-HH-mm-ss');
+                Long timestampNow = GetTimestamp(timenow, null, null, null);
+
+                if (info.ba.workingHours__c == null || info.ba.workingHours__c <= 0) {
+                    errorFlag = true;
+                    String errorMessage = '涓氬姟娲诲姩 宸ヤ綔鏃堕棿濉啓閿欒锛岃纭\n';
+                    errorMessageList.add(errorMessage);
+                } else {
+                    Integer baEndHour = Integer.valueOf(info.ba.EndTimeHour__c);
+                    Integer baEndMinute = Integer.valueOf(info.ba.EndTimeMinute__c);
+                    // 鑾峰彇鎶ュ憡鏃ユ湡
+                    Date reportDate = tsr.TSReportDate__c ;
+                    Long timestamp = GetTimestamp('', baEndHour, baEndMinute, reportDate);
+
+                    if (timestampNow < timestamp) {
+                        errorFlag = true;
+                        String errorMessage = '璇峰湪浠婂ぉ鏈�缁堜簨浠剁粨鏉熶箣鍚庡啀鎻愪氦鏃ユ姤';
+                        errorMessageList.add(errorMessage);
+                    }
+                }
+
+                // 妗堜欢瀹屾垚鏃�
+                if (info.ba.BusinessACompletionDate__c != null) {
+
+                    if (info.ba.BusinessACompletionDate__c != tsr.TSReportDate__c) {
+                        errorFlag = true;
+                        String errorMessage =  '妗堜欢瀹屾垚鏃ュ彧鑳芥槸鎶ュ憡鏃ユ湡锛岃纭\n';
+
+                        errorMessageList.add(errorMessage);
+                    }
+                }
+                if (info.ba.workingHours__c == null || info.ba.workingHours__c <= 0) {
+                    errorFlag = true;
+                    String errorMessage =  '宸ヤ綔鏃堕棿濉啓閿欒锛岃纭\n';
+                    errorMessageList.add(errorMessage);
+                }
+
+                if (String.isBlank(info.ba.firstInput__c)) {
+                    errorFlag = true;
+                    String errorMessage =  '棣栨鐧诲綍妗堜欢 涓虹┖锛岃纭\n';
+                    errorMessageList.add(errorMessage);
+                }
+
+                if (String.isBlank(info.ba.BusinessAServiceContentNew__c)) {
+                    errorFlag = true;
+                    String errorMessage =  '鏈嶅姟鍐呭 涓虹┖锛岃纭\n';
+                    errorMessageList.add(errorMessage);
+                }
+                Boolean ServiceCategoryIsRepair = info.ba.BusinessAServiceCategory__c == 'Repair';
+                Boolean ServiceCategoryIsSevice = info.ba.BusinessAServiceCategory__c == 'Sevice';
+                // 鏈嶅姟鑼冪暣 涓� Repair 蹇呭~楠岃瘉
+                if (ServiceCategoryIsRepair) {
+
+
+                    String accountId = info.ba.BusinessAAccount__c;
+                    if (String.isBlank(accountId)) {
+                        // 1> 瀹㈡埛鍗曚綅 鍚嶇О 涓虹┖ 鎶ラ敊 // 2> 瀹㈡埛鍗曚綅 Id 涓虹┖ 鎶ラ敊
+                        errorFlag = true;
+                        String errorMessage = '瀹㈡埛鍗曚綅 鍚嶇О 涓虹┖,璇风‘璁n';
+                        errorMessageList.add(errorMessage);
+                    }
+                    // 4> 鏍规嵁鑱旂郴浜篒d 纭璇ヨ仈绯讳汉鏄惁鏄� 瀹㈡埛鍗曚綅涓嬬殑鑱旂郴浜�
+                    String contactId = info.ba.BusinessAContact__c;
+                    if (String.isNotBlank(contactId)) {
+                        List<Contact> contactList = TSRepairUtil.GetContactList(contactId, null, null, '');
+                        if (contactList.size() <= 0) {
+                            String errorMessage =  '鑱旂郴浜� 鏃犳晥 璇风‘璁n';
+                            errorFlag = true;
+                            errorMessageList.add(errorMessage);
+                        } else {
+                            // 鏌ユ壘鑱旂郴浜� 鑾峰彇 鑱旂郴浜虹殑瀹㈡埛 涓庡鎴峰崟浣嶈繘琛屾瘮瀵�
+                            String contactAccountId = contactList[0].AccountId__c;
+                            if (String.isNotBlank(accountId)) {
+                                accountId = accountId.substring(0, 15);
+                                String contactName = contactList[0].Name;
+                                if (!accountId.equals(contactAccountId)) {
+                                    String errorMessage = '鑱旂郴浜� [ ' + contactName + ' ] 涓嶆槸瀹㈡埛涓嬬殑鑱旂郴浜� 璇风‘璁�';
+
+                                    errorFlag = true;
+                                    errorMessageList.add(errorMessage);
+                                }
+                            } else {
+                                String errorMessage =  '瀹㈡埛鍗曚綅涓虹┖  鑱旂郴浜烘棤娉曢獙璇佹槸鍚︽湁鏁� 璇风‘璁�';
+                                errorFlag = true;
+                                errorMessageList.add(errorMessage);
+                            }
+
+
+                        }
+
+                    } else {
+                        String errorMessage =  '鑱旂郴浜轰负绌� 璇风‘璁�';
+                        errorFlag = true;
+                        errorMessageList.add(errorMessage);
+                    }
+
+                    // 楠岃瘉鏁呴殰鏍锋満 蹇呭~瀛楁
+                    if (info.failureAssetList.size() > 0 ) {
+                        for (FailureAsset__c fa : info.failureAssetList) {
+                            // 鏈哄瀷
+                            if (String.isNotBlank(fa.model__c)) {
+                                // 浜у搧绯诲垪
+                                if (String.isBlank(fa.FAProductSeries__c)) {
+                                    errorFlag = true;
+                                    String errorMessage =  '鏈哄瀷 [ ' + fa.model__c + ' ] 浜у搧绯诲垪涓虹┖锛岃纭';
+                                    errorMessageList.add(errorMessage);
+                                }
+                                // 淇濅慨鐘舵��
+                                if (String.isBlank(fa.WarrantyStatus__c) ) {
+                                    errorFlag = true;
+                                    String errorMessage =  '鏈哄瀷 [ ' + fa.model__c + ' ] 淇濅慨鐘舵�佷负绌猴紝璇风‘璁�';
+                                    errorMessageList.add(errorMessage);
+                                }
+                            }
+                        }
+
+                    } else {
+                        // 閿欒鎻愰啋
+                        String errorMessage = '鏈~鍐欐晠闅滄満鍣紝璇风‘璁�';
+                        errorMessageList.add(errorMessage);
+                    }
+
+                    // 鏁呴殰鍐呭
+                    if ( String.isBlank(info.ba.BusinessAFaultContent__c)) {
+                        errorFlag = true;
+                        String errorMessage =  '鏁呴殰鍐呭涓虹┖ 璇风‘璁�';
+                        errorMessageList.add(errorMessage);
+                    }
+                    // 鎶ヤ慨鏃ユ湡
+                    if (info.ba.BusinessARepairDate__c == null) {
+                        // 鎶ラ敊
+                        String errorMessage = '鎶ヤ慨鏃ユ湡涓虹┖锛岃纭';
+                        errorMessageList.add(errorMessage);
+                    }
+                    // 鍒ゆ柇鏃ユ湡
+                    if (info.ba.BusinessADetermineDate__c == null) {
+                        // 鎶ラ敊
+                        String errorMessage = '鍒ゆ柇鏃ユ湡涓虹┖锛岃纭';
+                        errorMessageList.add(errorMessage);
+                    } else {
+                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADetermineDate__c) {
+                            // 鎶ラ敊
+                            String errorMessage = '鍒ゆ柇鏃ユ湡灏忎簬鎶ヤ慨鏃ユ湡锛岃纭';
+                            errorMessageList.add(errorMessage);
+                        }
+                    }
+                    // 瑕佹眰鏈嶅姟鏃ユ湡
+                    if (info.ba.BusinessADateRequest__c == null) {
+                        String errorMessage = '瑕佹眰鏈嶅姟鏃ユ湡涓虹┖锛岃纭';
+
+                        errorMessageList.add(errorMessage);
+                    } else {
+                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADateRequest__c) {
+                            // 鎶ラ敊
+                            String errorMessage = '瑕佹眰鏈嶅姟鏃ユ湡灏忎簬鎶ヤ慨鏃ユ湡锛岃纭';
+
+                            errorMessageList.add(errorMessage);
+                        }
+                    }
+                    // 淇℃伅鏉ユ簮
+                    if (String.isBlank(info.ba.BusinessAMessageSource__c)) {
+                        // 鎶ラ敊
+                        String errorMessage = '淇℃伅鏉ユ簮涓虹┖锛岃纭';
+
+                        errorMessageList.add(errorMessage);
+                    }
+                    // 鏈嶅姟鎬ц川
+                    if (String.isBlank(info.ba.BusinessANatureService__c)) {
+                        // 鎶ラ敊
+                        String errorMessage = '鏈嶅姟鎬ц川涓虹┖锛岃纭';
+
+                        errorMessageList.add(errorMessage);
+                    } else {
+                        // 鏃犲伩鍘熷洜
+                        if (info.ba.BusinessANatureService__c == '鏃犲伩' && String.isBlank(info.ba.BusinessAWithoutReason__c)) {
+                            // 鎶ラ敊
+                            String errorMessage = '鏃犲伩鍘熷洜涓虹┖锛岃纭';
+
+                            errorMessageList.add(errorMessage);
+
+                        } else if (info.ba.BusinessANatureService__c == '鏈夊伩' && info.ba.BusinessADateApproval__c == null && info.ba.BusinessACompletionDate__c != null) {// 鏈嶅姟鑼冪暣涓篟epair锛孾鏈嶅姟鎬ц川]="鏈夊伩"锛屾浠跺畬鎴愭棩涓嶄负绌虹殑鎯呭喌涓�
+                            // 鎶ラ敊
+                            String errorMessage = '鍚屾剰鎶ヤ环鏃ユ湡涓虹┖锛岃纭';
+
+                            errorMessageList.add(errorMessage);
+                        } else if (info.ba.BusinessANatureService__c == '鏈夊伩' ) {
+
+                            // 鍚屾剰鎶ヤ环鏃ユ湡
+                            if ( info.ba.BusinessADateApproval__c > tsr.TSReportDate__c) {
+                                String errorMessage = '鍚屾剰鎶ヤ环鏃ユ湡 涓嶈兘澶т簬鎶ュ憡鏃ユ湡锛岃纭';
+
+                                errorMessageList.add(errorMessage);
+                            }
+
+                            if (info.ba.BusinessADateQuotation__c == null ) {
+                                String errorMessage = '鎶ヤ环鏃ユ湡 涓嶈兘涓虹┖锛岃纭';
+
+                                errorMessageList.add(errorMessage);
+                            } else {
+                                // 鎶ヤ环鏃ユ湡
+                                if (info.ba.BusinessADateQuotation__c < info.ba.BusinessARepairDate__c) {
+                                    String errorMessage = '鎶ヤ环鏃ユ湡 涓嶈兘鏃╀簬鎶ヤ慨鏃ユ湡锛岃纭';
+
+                                    errorMessageList.add(errorMessage);
+                                }
+                            }
+                        }
+
+                    }
+                    // 鏈嶅姟鍦烘墍
+                    if (String.isBlank(info.ba.BusinessAServicePlace__c)) {
+                        errorFlag = true;
+                        String errorMessage =  '鏈嶅姟鍦烘墍 涓虹┖锛岃纭';
+                        errorMessageList.add(errorMessage);
+                    }
+                }
+                if (ServiceCategoryIsRepair || ServiceCategoryIsSevice) {
+                    Boolean  cmpletionDateIsNotNull = info.ba.BusinessACompletionDate__c != null;//妗堜欢瀹屾垚鏃�
+                    // 鏈嶅姟缁撴灉
+                    if (cmpletionDateIsNotNull && String.isBlank(info.ba.BusinessAServiceResult__c)) {
+                        errorFlag = true;
+                        String errorMessage =  '鏈嶅姟缁撴灉 涓虹┖锛岃纭';
+                        errorMessageList.add(errorMessage);
+                    }
+                }
+
+                if ( errorMessageList.size() > 0) {
+                    errorFlag = true;
+
+                    errorMessageMap.put(key, errorMessageList);
+                }
+            }
+
+        }
+
+
+        if (serviceTypeQuantity == 0) {
+            errorFlag = true;
+            String errorMessage =  '鎵�鏈変笟鍔℃椿鍔ㄧ殑鏈嶅姟绫诲瀷閮戒负绌猴紝鎻愪氦澶辫触锛岃纭';
+            List<String> errorMessageList = new List<String>();
+            errorMessageList.add(errorMessage);
+            errorMessageMap.put('TS鏃ユ姤寮傚父', errorMessageList);
+
+        }
+
+        if (errorFlag) {
+            pagemessages(errorMessageMap);
+            return false;
+        }
+        return true;
+    }
+
+    // 鎻愮ず淇℃伅鏍囪
+    public String PromptMessage(BusinessActivity__c ba, Integer lineNumber) {
+
+        String result = '';
+
+        // 涓氬姟娲诲姩绠$悊缂栫爜
+        String code = ba.FindManagementCode__c;
+        // 涓氬姟娲诲姩Id
+        String baId = ba.Id;
+
+        if (String.isNotBlank(baId)) {
+            if (String.isNotBlank(code)) {
+                result = code;
+            } else {
+                result = String.valueOf(lineNumber + 1) ;
+            }
+        } else {
+            result = String.valueOf(lineNumber + 1);
+        }
+
+        return result;
+    }
+
+    public class RepairInfo {
+
+        public BusinessActivity__c ba {get; set;} //涓氬姟娲诲姩
+        public User_FaultInfo__c uf {get; set;}  //鐢ㄦ埛鏁呴殰淇℃伅
+        public List<FailureAsset__c> failureAssetList {get; set;} //鏁呴殰鏍锋満
+        public List<Attachment> attachmentLsit {get; set;}//闄勪欢淇℃伅
+        public String baServiceType {get; set;} //鏈嶅姟绫诲瀷
+        public Integer lineNumber {get; set;}
+        public String BusinessActivityId {get; set;} //涓氬姟娲诲姩Id
+        public Boolean disabled {get; set;}//娣诲姞浜у搧 鎸夐挳 绂佺敤
+        public Boolean firstSubmission {get; private set;}
+        public Boolean approvalOpinionDisabled {get; set;} //瀹℃壒鎰忚/鎰忚 涓嶅彲淇敼
+        public String firstinputOriginalValue {get; set;} // 棣栨鐧婚檰妗堜欢
+        public RepairInfo (TS_Repair__c tsr, BusinessActivity__c ba_in , User_FaultInfo__c uf_in , List<FailureAsset__c> faList , Integer num_in, List<Attachment> attachments) {
+            ba = ba_in;
+            baServiceType = ba.serviceType__c;
+            firstinputOriginalValue = ba.firstInput__c;
+            BusinessActivityId = ba.Id;
+            uf = uf_in;
+            failureAssetList = faList;
+            attachmentLsit = attachments;
+            lineNumber = num_in;
+            firstSubmission = false;
+            String  firstSubmissionStr = String.valueOf(ba.BusinessAFirstSubmission__c);
+            if (String.isNotBlank(firstSubmissionStr)) {
+                firstSubmission = true;
+            }
+
+            Integer maxFailureAssetListSize = Integer.valueOf(System.label.TSRepairPageMaxFailureAssetListSize);
+            if (faList == null || faList.size() < maxFailureAssetListSize) {
+                disabled = false;
+            } else {
+                disabled = true;
+            }
+            //鐢ㄦ埛涓嶆槸TS鏃ユ姤鍒涘缓浜虹殑涓婄骇锛屽鎵规剰瑙併�佹剰瑙� 涓嶅彲淇敼
+            if (tsr.TSRepairSuperior__c != UserInfo.getUserId()) {
+                approvalOpinionDisabled = true;
+            }
+        }
+
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TSRepairController.cls-meta.xml b/scr/classes/TSRepairController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TSRepairController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TSRepairControllerTest.cls b/scr/classes/TSRepairControllerTest.cls
new file mode 100644
index 0000000..7e04dd5
--- /dev/null
+++ b/scr/classes/TSRepairControllerTest.cls
@@ -0,0 +1,326 @@
+@isTest
+private class TSRepairControllerTest {
+    public static TS_Repair__c tsr;
+    public static TS_Repair__c tsr2;
+    public static BusinessActivity__c ba1;
+    public static BusinessActivity__c ba2;
+    public static BusinessActivity__c ba3;
+
+    public static User_FaultInfo__c uf1;
+    public static User_FaultInfo__c uf2;
+    public static User_FaultInfo__c uf3;
+
+    public static FailureAsset__c fa1;
+    public static FailureAsset__c fa2;
+    public static FailureAsset__c fa3;
+
+    public static Contact contact;
+
+    public static Account acc1;
+    public static Account acc2;
+
+    static void basicData() {
+
+        tsr = new TS_Repair__c();
+        tsr.TSReportDate__c = Date.today();
+        insert tsr;    
+        tsr2 = new TS_Repair__c();
+        tsr2.TSReportDate__c = Date.today();
+        tsr2.TSReportStatus__c  = '鐢宠涓�';
+        insert tsr2;
+
+        uf1 = new User_FaultInfo__c();
+        insert uf1;
+        FailureAsset__c fa1 = new FailureAsset__c();
+        fa1.model__c = 'test1';
+        fa1.FAUserFaultInfo__c = uf1.Id;
+        insert fa1;
+        ba1 = new BusinessActivity__c();
+        ba1.BusinessATS__c = tsr.Id;
+        // ba1.BusinessARepairDate__c =  Date.today();
+        insert ba1;
+
+        uf2 = new User_FaultInfo__c();
+        insert uf2;
+        fa2 = new FailureAsset__c();
+        fa2.model__c = 'test2';
+        fa2.FAUserFaultInfo__c = uf2.Id;
+        insert fa2;
+        ba2 = new BusinessActivity__c();
+        ba2.BusinessATS__c = tsr2.Id;
+        ba2.User_FaultInfo__c = uf2.Id;
+        insert ba2;
+
+        User_FaultInfo__c uf3 = new User_FaultInfo__c();
+        insert uf3;
+        fa3 = new FailureAsset__c();
+        fa3.model__c = 'test3';
+        fa3.FAUserFaultInfo__c = uf3.Id;
+        insert fa3;
+        ba3 = new BusinessActivity__c();
+        ba3.BusinessATS__c = tsr2.Id;
+        ba3.User_FaultInfo__c = uf3.Id;
+        insert ba3;
+
+        Attachment att = new Attachment(
+            Name = 'ORDER-123456.pdf',
+            parentId = ba1.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+
+        Attachment att2 = new Attachment(
+            Name = 'not-ORDER-123456.pdf',
+            parentId = ba2.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+
+
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        acc1 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id, 
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Service IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Service IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        insert acc1;
+
+        acc2 = new Account(
+            name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Service IE2',
+            FacilityName__c = 'abc2',
+            DivisionName_D__c = 'Service IE2',
+            FacilityNameD__c = 'abc2',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456'
+        );
+        insert acc2;
+        List<Account> selectAccount = [ Select Id,Name from Account];
+        contact = new Contact();
+        contact = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=acc2.id);
+        insert contact;
+
+    }
+    // 淇濆瓨楠岃瘉
+    static testMethod void saveValidation() {
+        basicData();
+        ba1.serviceType__c = '纭欢淇悊';
+        ba1.BusinessAServiceCategory__c = 'Repair';
+        ba1.User_FaultInfo__c = uf1.Id;
+        ba1.BusinessADetermineDate__c = Date.today().addDays(-2);
+        ba1.BusinessARepairDate__c = Date.today().addDays(-1);
+        ba1.BusinessADateRequest__c = Date.today().addDays(-3);
+        ba1.BusinessANatureService__c = '鏈夊伩';
+        ba1.BusinessADateApproval__c = Date.today().addDays(1);
+        ba1.BusinessADateQuotation__c = Date.today().addDays(-2);
+        ba1.BusinessACompletionDate__c = Date.today().addDays(1);
+
+        ba2.serviceType__c = '纭欢淇悊';
+        ba2.BusinessAServiceCategory__c = 'Repair';
+        ba2.BusinessACustomerUnit__c = 'Test 01';
+        ba2.BusinessAAccount__c = acc1.Id;
+        ba2.BusinessAContact__c = contact.Id;
+        ba2.BusinessANatureService__c = '鏈夊伩';
+        ba2.BusinessADateApproval__c = null;
+        ba2.BusinessADateQuotation__c  = null;
+
+        ba3.serviceType__c = '纭欢淇悊';
+        ba3.BusinessAServiceCategory__c = 'Repair';
+        ba3.BusinessACustomerUnit__c = '';
+        // ba3.BusinessAAccount__c = acc1.Id;
+        ba3.BusinessAContact__c = contact.Id;
+        ba3.BusinessANatureService__c = '鏃犲伩';
+        ba3.BusinessAWithoutReason__c = '';
+        ba3.BusinessADateApproval__c = null;
+        ba3.BusinessADateQuotation__c  = null;
+
+        PageReference page = new PageReference('/apex/TSRepair?Id='+tsr.Id);
+        System.Test.setCurrentPage(page);
+        TSRepairController controller = new TSRepairController();
+        controller.init(); 
+        controller.RepairInfoList[0].ba = ba1;
+        controller.RepairInfoList[1].ba = ba2;
+        controller.RepairInfoList[2].ba = ba3;
+        controller.RepairInfoList[1].ba.BusinessAServiceContentNew__c = 'Test';
+        controller.RepairInfoList[1].failureAssetList[0].model__c = 'Test';
+        controller.RepairInfoList[1].failureAssetList[1].model__c = 'Test';
+        // controller.save();
+        controller.baIds = ba3.Id + '/0';
+        controller.FindTSRepair();
+        controller.checkReportDate();
+        controller.uploadingAttachment();
+         
+        controller.status  = '宸叉壒鍑�';
+        controller.setStatus();
+
+        controller.addFailureAsset();
+    }
+    // 鐢宠涓� 楠岃瘉
+    static testMethod void AuthenticationInformationValidation() {
+        basicData();
+        ba1.serviceType__c = '纭欢淇悊';
+        ba1.BusinessAServiceCategory__c = 'Repair';
+        ba1.User_FaultInfo__c = uf1.Id;
+        ba1.BusinessADetermineDate__c = Date.today().addDays(-2);
+        ba1.BusinessARepairDate__c = Date.today().addDays(-1);
+        ba1.BusinessADateRequest__c = Date.today().addDays(-3);
+        ba1.BusinessANatureService__c = '鏈夊伩';
+        ba1.BusinessADateApproval__c = Date.today().addDays(1);
+        ba1.BusinessADateQuotation__c = Date.today().addDays(-2);
+        ba1.BusinessACompletionDate__c = Date.today().addDays(1);
+
+        ba2.serviceType__c = '纭欢淇悊';
+        ba2.BusinessAServiceCategory__c = 'Repair';
+        ba2.BusinessACustomerUnit__c = 'Test 01';
+        ba2.BusinessAAccount__c = acc1.Id;
+        ba2.BusinessAContact__c = contact.Id;
+        ba2.workingHours__c = 11.5;
+        ba2.EndTimeHour__c = '20';
+        ba2.EndTimeMinute__c = '00';
+
+        ba3.serviceType__c = '纭欢淇悊';
+        ba3.BusinessAServiceCategory__c = 'Repair';
+        ba3.BusinessACustomerUnit__c = '';
+        ba3.BusinessAContact__c = contact.Id;
+
+        PageReference page = new PageReference('/apex/TSRepair?Id='+tsr.Id);
+        System.Test.setCurrentPage(page);
+        TSRepairController controller = new TSRepairController();
+        controller.init(); 
+        controller.RepairInfoList[0].ba = ba1;
+        controller.RepairInfoList[1].ba = ba2;
+        controller.RepairInfoList[1].ba = ba3;
+        controller.RepairInfoList[0].failureAssetList[0].model__c = 'Test';
+        controller.RepairInfoList[0].failureAssetList[1].model__c = 'Test';
+
+        controller.RepairInfoList[1].ba = ba2;
+        controller.save();         
+        controller.status  = '鐢宠涓�';
+        controller.setStatus();
+
+        controller.addFailureAsset();
+    }
+    // 鐢宠涓�
+    static testMethod void save() {
+        basicData();
+        tsr2.TSReportStatus__c  = '鐢宠涓�';
+        // update tsr2;
+        // 
+        System.Test.startTest();
+        BusinessActivity__c ba4 = new BusinessActivity__c();
+        ba4.serviceType__c = '纭欢淇悊';
+        ba4.BusinessAServiceCategory__c = 'Repair';
+        ba4.User_FaultInfo__c = uf1.Id;
+        ba4.BusinessADetermineDate__c = Date.today().addDays(-1);
+        ba4.BusinessARepairDate__c = Date.today().addDays(-1);
+        ba4.BusinessANatureService__c = '鏈夊伩';
+        ba4.BusinessACustomerUnit__c = 'abc2Service IE2';
+        ba4.BusinessAAccount__c = acc2.Id;
+        ba4.BusinessAContact__c = contact.Id;
+        ba4.BusinessAHaveAttachment__c = true;
+        ba4.firstInput__c = '鍚�';
+        ba4.workingHours__c = 10;
+        insert ba4;
+        BusinessActivity__c ba6 = new BusinessActivity__c();
+        ba6.serviceType__c = '纭欢淇悊';
+        ba6.BusinessAServiceCategory__c = 'Repair';
+        ba6.User_FaultInfo__c = uf1.Id;
+        ba6.BusinessADetermineDate__c = Date.today().addDays(-1);
+        ba6.BusinessARepairDate__c = Date.today().addDays(-1);
+        ba6.BusinessANatureService__c = '鏈夊伩';
+        ba6.BusinessACustomerUnit__c = 'abc2Service IE2';
+        ba6.BusinessAAccount__c = acc2.Id;
+        ba6.BusinessAContact__c = contact.Id;
+        ba6.BusinessAHaveAttachment__c = true;
+        ba6.firstInput__c = '鏄�';
+        ba6.workingHours__c = 10;
+        insert ba6;
+        PageReference page = new PageReference('/apex/TSRepair?Id='+tsr2.Id);
+        System.Test.setCurrentPage(page);
+        TSRepairController controller = new TSRepairController();
+        controller.init(); 
+        controller.status = '鐢宠涓�';
+        FailureAsset__c fa4 = new FailureAsset__c();
+        fa4.model__c = 'test3';
+        fa4.FAActivity__c = ba4.Id;
+        insert fa4;
+        controller.RepairInfoList[0].failureAssetList[0] = fa4;
+        controller.RepairInfoList[0].ba = ba4;
+        controller.save();
+        System.Test.StopTest();
+        controller.baIds = '/0';
+        controller.FindTSRepair();
+        controller.checkReportDate();
+        controller.uploadingAttachment();
+
+        controller.status  = '鑽夋涓�';
+        // controller.save();
+        controller.setStatus();
+    }
+    // 鑽夋涓� / 椹冲洖
+    static testMethod void save1() {
+        basicData();
+        tsr2.TSReportStatus__c  = '鐢宠涓�';
+
+        BusinessActivity__c ba4 = new BusinessActivity__c();
+        ba4.serviceType__c = '纭欢淇悊';
+        ba4.BusinessAServiceCategory__c = 'Repair';
+        ba4.User_FaultInfo__c = uf1.Id;
+        ba4.BusinessADetermineDate__c = Date.today().addDays(-1);
+        ba4.BusinessARepairDate__c = Date.today().addDays(-1);
+        ba4.BusinessANatureService__c = '鏈夊伩';
+        ba4.BusinessACustomerUnit__c = 'abc2Service IE2';
+        ba4.BusinessAAccount__c = acc2.Id;
+        ba4.BusinessAContact__c = contact.Id;
+        ba4.firstInput__c = '鍚�';
+        ba4.BusinessAHaveAttachment__c = true;
+        ba4.workingHours__c = 10;
+        TS_Repair__c tsr3 = new TS_Repair__c();
+        PageReference page = new PageReference('/apex/TSRepair?Id='+tsr2.Id);
+        System.Test.setCurrentPage(page);
+        TSRepairController controller = new TSRepairController();
+        controller.init(); 
+        controller.status = '鑽夋涓�';
+        controller.RepairInfoList[0].ba = ba4;
+        controller.lineno = '1';
+        controller.fromUserFaultInfoId = uf1.Id;
+        controller.initBusinessActivity();
+        controller.save();
+        controller.initPagePrompt('1');
+        controller.initPagePrompt('2');
+        controller.initPagePrompt('Submit');
+        controller.initPagePrompt('Draft');
+        controller.initPagePrompt('Approval');
+        controller.initPagePrompt('Rejected');
+        controller.ServiceContentNewAssembled('Test');
+        controller.TSRepairAssembled(tsr3);
+        page = new PageReference('/apex/TSRepair?Id='+tsr2.Id);
+        System.Test.setCurrentPage(page);
+        controller = new TSRepairController(new ApexPages.StandardController(tsr2));
+        controller.init();
+    }
+    // 鐢ㄦ埛鐐瑰嚮 鏂板缓TS鏃ユ姤鎸夐挳鍒涘缓TS鏃ユ姤
+    static testMethod void testMethod3() {
+        basicData();
+        PageReference page = new PageReference('/apex/TSRepair?Id=');
+        System.Test.setCurrentPage(page);
+        TSRepairController controller = new TSRepairController();
+        controller.init(); 
+        controller.FindTSRepair();
+        controller.checkReportDate();
+        controller.status  = '宸叉壒鍑�';
+        controller.setStatus();
+
+        controller.addFailureAsset();
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/TSRepairControllerTest.cls-meta.xml b/scr/classes/TSRepairControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TSRepairControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TSRepairUtil.cls b/scr/classes/TSRepairUtil.cls
new file mode 100644
index 0000000..5a61f2e
--- /dev/null
+++ b/scr/classes/TSRepairUtil.cls
@@ -0,0 +1,544 @@
+global class TSRepairUtil {
+    
+    // 鐢ㄦ埛鏁呴殰淇℃伅
+    public static Map<String, User_FaultInfo__c> GetfaultInfoMap(List<String> ufIdList) {
+
+        Map<String, User_FaultInfo__c> result = new Map<String, User_FaultInfo__c>();
+        List<User_FaultInfo__c> faultInfoList = GetfaultInfoList(ufIdList,null,null,'');
+        
+        if ( faultInfoList.size() > 0) {
+
+            for (User_FaultInfo__c uf : faultInfoList) {
+
+                result.put(uf.Id, uf);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 鑾峰彇鐢ㄦ埛/鏁呴殰淇℃伅
+     * @DateTime 2020-08-22
+     * @param    ufIdList     [鐢ㄦ埛/鏁呴殰淇℃伅 Id]
+     * @param    placeholder1 [棰勭暀浣嶇疆1]
+     * @param    placeholder2 [棰勭暀浣嶇疆2]
+     * @param    placeholder3 [棰勭暀浣嶇疆3]
+     * @return                [description]
+     */
+    public static List<User_FaultInfo__c> GetfaultInfoList(List<String> ufIdList,Set<String> placeholder1,List<String> placeholder2,String placeholder3){
+        List<User_FaultInfo__c> result = new List<User_FaultInfo__c>();
+        String sql = UserFaultInfoBaseSQL();
+        if (ufIdList != null && ufIdList.size() > 0) {
+            sql += ' AND Id In : ufIdList';
+        }
+        sql += ' order by Id';
+
+        result = Database.query(sql);
+
+        return result;
+    }
+    /**
+     * [UserFaultInfoBaseSQL 鐢ㄦ埛/鏁呴殰淇℃伅鐨勫熀鏈琒QL]
+     * @return [description]
+     */
+    public static String UserFaultInfoBaseSQL(){
+        String sql = '';
+            sql += 'SELECT Id,Name,UFAccount__c, UFContact__c, UFDateRequest__c, UFDetermineDate__c,UserFaultInfoReportDate__c,';
+            sql += 'UFFaultContent__c, UFManagementCode__c, UFMessageSource__c, UFNatureService__c,';
+            sql += 'UFPhone__c, UFRepairDate__c, UFWithoutReason__c,';
+            sql += 'UFLineNumber__c, UFTS__c, UserFaultInfoServiceResult__c,UFDateApproval__c,UserFaultInfoApprovalDate__c,UserFaultInfoModel__c,';
+            sql += 'UserFaultInfoServiceContent__c, UserFaultInfoCustomerUnit__c,';
+            sql += 'UserFaultInfoServicePlace__c, UserFaultInfoBusinessTrip__c,';
+            sql += 'UserFaultInfoCompletionDate__c, UserFaultInfoNextService__c,';
+            sql += 'UserFaultInfoServiceType__c, UserFaultInfoWorkingHours__c,';
+            sql += 'UserFaultInfoBeSelected__c,UserFaultInfoServiceCategory__c,UserFaultInfoServiceContractNo__c,UserFaultInfoCombinedAmount__c,UserFaultInfoDateQuotation__c ';
+            sql += ' FROM User_FaultInfo__c WHERE Id != null';
+        return sql;
+    }
+
+    // 鐢ㄦ埛鏁呴殰鏍锋満
+    public static Map<String, List<FailureAsset__c>> GetUserFaultInfMap(List<String> ufIdList,List<String> baIdList){
+
+        Map<String, List<FailureAsset__c>> result = new Map<String, List<FailureAsset__c>>();
+        List<FailureAsset__c> failureAssetList = new List<FailureAsset__c>();
+        if (ufIdList != null && ufIdList.size() > 0) {
+            failureAssetList = GetFailureAssetList(null,ufIdList,null,null,null);
+        }
+
+        if (baIdList != null && baIdList.size() > 0) {
+            failureAssetList = GetFailureAssetList(null,null,baIdList,null,null);
+        }
+        // List<FailureAsset__c> failureAssetList = GetFailureAssetList(null,ufIdList,null,null);
+            if ( failureAssetList.size() > 0) {
+                for (FailureAsset__c fa : failureAssetList) {
+                    if (ufIdList != null && ufIdList.size() > 0) {
+                        List<FailureAsset__c> faList = new List<FailureAsset__c>();
+                        if (result.containsKey(fa.FAUserFaultInfo__c)) {
+
+                            faList = result.get(fa.FAUserFaultInfo__c);
+                        }
+                        faList.add(fa);
+                        result.put(fa.FAUserFaultInfo__c, faList);
+                    }
+
+                    if (baIdList != null && baIdList.size() > 0) {
+                        List<FailureAsset__c> faList = new List<FailureAsset__c>();
+                        if (result.containsKey(fa.FAActivity__c)) {
+
+                            faList = result.get(fa.FAActivity__c);
+                        }
+                        faList.add(fa);
+                        result.put(fa.FAActivity__c, faList);
+                    }
+
+                }
+            }
+        return result;
+    }
+    /**
+     * 鑾峰彇鏁呴殰浜у搧淇℃伅
+     * @DateTime 2020-08-22
+     * @param    faIdList     [鏁呴殰鏈哄櫒 Id]
+     * @param    ufIdList     [鐢ㄦ埛/鏁呴殰淇℃伅 Id]
+     * @param    placeholder1 [棰勭暀浣嶇疆1]
+     * @param    placeholder2 [棰勭暀浣嶇疆2]
+     * @return                [description]
+     */
+    public static List<FailureAsset__c> GetFailureAssetList(List<String> faIdList,List<String> ufIdList,List<String> baIdList,Set<String> placeholder1, String placeholder2){
+
+        List<FailureAsset__c> result = new List<FailureAsset__c>();
+
+        String sql = '';
+        sql += 'SELECT Id, UFManagementCode__c, model__c, SerialNumber__c, WarrantyStatus__c,';
+        sql += 'FAActivity__c, FAUserFaultInfo__c,FAProductSeries__c ';
+        sql += ' FROM FailureAsset__c WHERE Id != null ';
+
+        if (faIdList != null && faIdList.size() > 0) {
+            sql += ' AND Id In : faIdList ';     
+        }
+        if (ufIdList != null && ufIdList.size() > 0) {
+            sql += ' AND FAUserFaultInfo__c In : ufIdList';
+        }
+
+        if (baIdList != null && baIdList.size() > 0) {
+            sql += ' AND FAActivity__c In : baIdList';
+        }
+        sql += ' Order by FAUserFaultInfo__c,Id';
+        result = Database.query(sql);
+
+        return result;
+
+    }
+
+    //鏌ユ壘"涓氬姟娲诲姩"涓嬫墍鏈夌殑闄勪欢
+    public static Map<String,List<Attachment>> GetAttachmentMap(List<String> baIdList) {
+        Map<String,List<Attachment>> result = new Map<String,List<Attachment>>();
+        List<Attachment>  all_BA_AttachmentList=  GetAttachmentList(baIdList);
+        if (all_BA_AttachmentList != null && all_BA_AttachmentList.size() > 0) {
+
+            for (Attachment att :all_BA_AttachmentList) {
+                List<Attachment> ba_AttachmentList = new List<Attachment>();
+                if (result.containsKey(att.ParentId)) {
+                    ba_AttachmentList = result.get(att.ParentId);
+                } 
+                ba_AttachmentList.add(att);
+                result.put(att.ParentId,ba_AttachmentList);
+            }
+        } 
+        return result;
+    }
+
+
+    /**鑾峰彇闄勪欢
+     * This is a cool function
+     * @param    parentIdList [description]
+     * @return                [description]
+     */
+    public static List<Attachment> GetAttachmentCloneList(List<String> parentIdList) {
+        List<Attachment> result = new List<Attachment>();
+        String sql = '';
+        sql += 'select Id, IsDeleted, ParentId, Name, IsPrivate, ContentType, BodyLength,';
+        sql += 'Body, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById,';
+        sql += 'SystemModstamp, Description  ';
+        sql += ' FROM Attachment where Id != null ';
+        if (parentIdList != null && parentIdList.size() >0 ) {
+            sql += ' AND ParentId In : parentIdList';
+        }
+
+        sql += ' order by Id';
+
+        result = Database.query(sql);
+
+        return result;
+    }
+    /**
+     * [GetdeleteAttachmentList 鏌ヨ闄勪欢]
+     * @param  parentIdList [description]
+     * @return              [description]
+     */
+    public static List<Attachment> GetAttachmentList(List<String> parentIdList) {
+        List<Attachment> result = new List<Attachment>();
+        String sql = '';
+        sql += 'select Id,Name,CreatedDate,OwnerId,ParentId  ';
+        sql += ' FROM Attachment where Id != null ';
+        if (parentIdList != null && parentIdList.size() >0 ) {
+            sql += ' AND ParentId In : parentIdList';
+        }
+
+        sql += ' order by Id';
+
+        result = Database.query(sql);
+
+        return result;
+    }
+
+    /**
+     * 鑾峰彇涓氬姟娲诲姩
+     * @Author   XHL
+     * @DateTime 2020-08-22
+     * @param    tsRepairIdList         [TS鏃ユ姤 ID]
+     * @param    userFaultInfoIdList    [鐢ㄦ埛/鏁呴殰淇℃伅 ID]
+     * @param    businessActivityIdList [涓氬姟娲诲姩 ID]
+     * @param    placeholder1           [棰勭暀浣嶇疆1]
+     * @param    placeholder2           [棰勭暀浣嶇疆2]Map.keyset()
+     * @param    placeholder3           [棰勭暀浣嶇疆3]
+     * @return                          [description]
+     */
+    public static List<BusinessActivity__c> GetBusinessActivityList(List<String> tsRepairIdList, 
+                                                    List<String> userFaultInfoIdList,
+                                                    List<String> businessActivityIdList,
+                                                    set<String> placeholder1,
+                                                    List<String> placeholder2,
+                                                    String placeholder3) {
+
+        List<BusinessActivity__c> result = new List<BusinessActivity__c>();
+        String sql = '';
+        sql += 'SELECT Id, Name, firstInput__c, serviceType__c, BusinessATS__c,BusinessAServicePlace__c,';
+        sql += 'BusinessABusinessTrip__c,BusinessACompletionDate__c,BusinessANextService__c,';
+        sql += 'BusinessAServiceContent__c,BusinessAOpinion__c,BusinessAApprovalOpinion__c,';
+        sql += 'ManagementCode__c,workingHoursFrom__c, workingHoursTo__c,workingHours__c,';
+        sql += 'BusinessALineNumber__c,StartTimeHour__c,StartTimeMinute__c,EndTimeHour__c,';
+        sql += 'EndTimeMinute__c,FindManagementCode__c,edit__c,BusinessAServiceContentNew__c,';
+        sql += 'BusinessAAccount__c,BusinessAContact__c,BusinessAFaultContent__c,BaFromUserFaultInfo__c,';
+        sql += 'BusinessARepairDate__c,BusinessADetermineDate__c,BusinessADateRequest__c,';
+        sql += 'BusinessAMessageSource__c,BusinessANatureService__c,BusinessAWithoutReason__c,';
+        sql += 'BusinessADateApproval__c,User_FaultInfo__c,BusinessAServiceResult__c,StartTime__c,';
+        sql += 'BusinessADispatchTime__c,BusinessAMaintainTime__c,BusinessACustomerUnit__c, ';
+        sql += 'BusinessADowntime__c,BusinessAServiceCategory__c,BusinessAPhone_F__c,EndTime__c, ';
+        sql += 'BusinessAHaveAttachment__c,BusinessAServiceContractNo__c,BusinessAAccount__r.Id,';
+        sql += 'BusinessAPhone__c,BusinessASegment__c,BusinessADateQuotation__c,AgreeReportDate__c,  ';
+        sql += 'BusinessATSReportStatus__c,BusinessACombinedAmount__c,BusinessAFirstSubmission__c, ';
+        sql += 'BusinessATSReportReporter__c,BusinessATSReportDay__c ';
+        sql += ' FROM BusinessActivity__c where Id != null ';
+
+        if (tsRepairIdList != null && tsRepairIdList.size() > 0) {
+            sql += ' AND BusinessATS__c In : tsRepairIdList';
+        }
+
+        if (userFaultInfoIdList != null && userFaultInfoIdList.size() > 0) {
+            sql += ' AND User_FaultInfo__c In : userFaultInfoIdList ';
+        }
+
+        if (businessActivityIdList != null && businessActivityIdList.size() > 0) {
+            sql += ' AND Id In : businessActivityIdList';
+
+        }
+
+        sql += ' order by EndTime__c,Id';
+
+        result = Database.query(sql);
+
+        return result;
+
+    }
+
+    // 鍒犻櫎涓氬姟娲诲姩銆佺敤鎴锋晠闅滀俊鎭�
+    public static void deleteBusinessActivityInformation(List<String> deleteBusinessActivityIdList){
+
+        //鏌ユ壘涓氬姟娲诲姩
+        List<BusinessActivity__c> deleteBusinessActivityList = GetBusinessActivityList(null,null,deleteBusinessActivityIdList,null,null,'');
+        List<User_FaultInfo__c> deleteUserFaultInfoList = new List<User_FaultInfo__c>();
+        //鏌ユ壘 涓氬姟娲诲姩涓� 鏁呴殰浜у搧淇℃伅
+        List<FailureAsset__c> deleteBAfailureAssetList = GetFailureAssetList(null,null,deleteBusinessActivityIdList,null,null);
+        List<String> userFaultInfoIdList = new List<String>();
+        System.debug('deleteBusinessActivityList--->'+deleteBusinessActivityList);
+
+        if (deleteBusinessActivityList.size() > 0) {
+
+            for (BusinessActivity__c businessActivity :deleteBusinessActivityList){
+                
+                // 鑾峰彇 涓氬姟娲诲姩 棣栨鐧婚檰妗堜欢鐨勫��
+                if ('鏄�'.equals(businessActivity.firstInput__c) ){
+                    // 鍒犻櫎涓氬姟娲诲姩銆佺敤鎴锋晠闅滀俊鎭�佺敤鎴锋晠闅滀俊鎭� 涓� 鏁呴殰浜у搧淇℃伅
+                    // 鍥� 鐩墠鍙湁鏈彁浜ょ殑涓氬姟娲诲姩鎵嶅彲鍒犻櫎锛屾湭鎻愪氦杩囩殑涓氬姟娲诲姩娌℃湁鍏宠仈鐨勭敤鎴锋晠闅滀俊鎭紝鍥犳娉ㄦ帀
+                    // 鑻ヤ互鍚庨渶瑕佸彲鏀惧紑 ---20200912
+                    // -----------------------------------------------------------
+                    //if (String.isNotBlank(businessActivity.User_FaultInfo__c)) {
+                    //    User_FaultInfo__c deleteUserFaultInfo = new User_FaultInfo__c();
+                    //    deleteUserFaultInfo.Id = businessActivity.User_FaultInfo__c;
+                    //    deleteUserFaultInfoList.add(deleteUserFaultInfo);
+                    //    userFaultInfoIdList.add(businessActivity.User_FaultInfo__c); 
+                    //}
+                    // -----------------------------------------------------------
+                                       
+                } else if ('鍚�'.equals(businessActivity.firstInput__c) ){
+                    // 浠呭垹闄や笟鍔℃椿鍔�
+                } 
+            } 
+
+            if (deleteUserFaultInfoList != null && deleteUserFaultInfoList.size() > 0 ) {
+                // 鏌ユ壘 鐢ㄦ埛鏁呴殰淇℃伅涓� 鏁呴殰浜у搧淇℃伅
+                List<FailureAsset__c> deleteUFfailureAssetList = GetFailureAssetList(null,userFaultInfoIdList,null,null,null);
+                // 鍒犻櫎 鐢ㄦ埛鏁呴殰淇℃伅涓� 鏁呴殰浜у搧淇℃伅
+                if (deleteUFfailureAssetList.size() > 0) {
+                    delete deleteUFfailureAssetList;
+                }
+                //鍒犻櫎 鐢ㄦ埛鏁呴殰淇℃伅
+                delete deleteUserFaultInfoList;
+            } 
+            //鍒犻櫎 涓氬姟娲诲姩涓� 鏁呴殰浜у搧淇℃伅
+            if (deleteBAfailureAssetList.size() > 0) {
+                delete deleteBAfailureAssetList;
+            }
+            //鍒犻櫎 涓氬姟娲诲姩
+            delete deleteBusinessActivityList;
+        }
+    }
+
+    /**
+     * 鑾峰彇TS鏃ユ姤
+     * @Author   XHL
+     * @DateTime 2020-08-22
+     * @param    repairId     [TS鏃ユ姤 Id]
+     * @param    userId       [鐢ㄦ埛 Id]
+     * @param    tsDate       [鎶ュ憡鏃ユ湡]
+     * @param    placeholder1 [棰勭暀浣嶇疆1]
+     * @param    placeholder2 [棰勭暀浣嶇疆2]
+     * @param    placeholder3 [棰勭暀浣嶇疆3]
+     * @return                [description]
+     */
+    public static List<TS_Repair__c> GetTsRepairList(String repairId,String userId,Date tsDate,
+                                        List<String> placeholder1, set<String> placeholder2, String placeholder3){
+        List<TS_Repair__c> result = new List<TS_Repair__c>();
+
+        String sql = '';
+        sql += 'SELECT Id, TSReportStatus__c,TSRepairClass__c,TSRepairSuperior__c,CreatedById,';
+        sql += 'TSApprovalDate__c, TSRepairEmployeeID__c,TSRepairDepartment__c,TSReportPerson__c ,';
+        sql += 'TSReportName__c,TSRepairSegment__c, TSReportDate__c,TSRepairDepartmenClass__c,'; 
+        sql += 'TSRepairUserArea__c,TSRepairDismissReason__c,LastModifiedDate,Name,CreatedDate, ';
+        sql += 'TSRepairFirstSubmission__c ' ;
+        sql += ' FROM TS_Repair__c  where Id != null ';
+
+        if (String.isNotBlank(repairId)) {
+            sql += ' AND Id = \''+ repairId + '\'';
+        }
+
+        if (String.isNotBlank(userId)) {
+            sql += ' AND TSReportPerson__c  = \''+userId+'\'';
+            sql += ' AND TSReportDate__c = ' + String.valueOf(tsDate);
+        }
+
+        result = Database.query(sql);
+
+        return result;
+    }
+
+    public static void insertattachmentCloneList(List<String> cloneFromIdList,String cloneToId){
+
+        List<Attachment> cloneFromAttachmentList = TSRepairUtil.GetAttachmentCloneList(cloneFromIdList);
+        List<Attachment> attachmentCloneList = new List<Attachment>();
+        List<Attachment> cloneToAttachmentList = new List<Attachment>();
+
+        if ( cloneFromAttachmentList.size() > 0) {
+            for (Attachment attachment :cloneFromAttachmentList) {
+                Attachment attachmentclone = new Attachment();
+                attachmentclone = attachment.clone();
+                attachmentclone.ParentId = cloneToId;
+                cloneToAttachmentList.add(attachmentclone);
+            }    
+        }
+        
+        if ( cloneToAttachmentList.size() > 0 ) {
+            insert cloneToAttachmentList;
+        }
+    }
+    /**
+     * [GetUserList 鏌ヨ褰撳墠鐢ㄦ埛淇℃伅]
+     * @param  userIdList [鐢ㄦ埛ID 闆嗗悎]
+     * @return            [description]
+     */
+    public static List<User> GetUserList(List<String> userIdList){
+        String sql = '';
+        System.debug('userIdList--->'+userIdList);
+        List<User> result  = new List<User>();
+        sql += 'Select Id,Name,TSUserArea__c,TSUserSuperior__c,TSUserDepartment__c,TSUserSegment__c,' ;
+        sql += 'TSEmployeeID__c,TSUserClass__c ';
+        sql += ' From User where Id In : userIdList' ;
+        System.debug('sql--->'+sql);
+        result = Database.query(sql);
+
+        return result;
+    }
+
+    public static BusinessActivity__c BusinessActivityAssembled(List<User_FaultInfo__c> faultInfoList){
+
+        BusinessActivity__c ba = new BusinessActivity__c();
+        User_FaultInfo__c updateUserFaultInfo = faultInfoList[0];
+        String fromUserFaultInfoId = updateUserFaultInfo.Id;
+        //ba.Id = baId;
+        ba.serviceType__c = updateUserFaultInfo.UserFaultInfoServiceType__c  ;//鏈嶅姟绫诲瀷
+        ba.BusinessAFaultContent__c = updateUserFaultInfo.UFFaultContent__c  ;//鏁呴殰鍐呭 
+        ba.BusinessARepairDate__c = updateUserFaultInfo.UFRepairDate__c  ;//淇濅慨鏃ユ湡
+        ba.BusinessADetermineDate__c = updateUserFaultInfo.UFDetermineDate__c  ;//鍒ゆ柇鏃ユ湡
+        ba.BusinessADateRequest__c = updateUserFaultInfo.UFDateRequest__c  ;//瑕佹眰鏈嶅姟鏃ユ湡
+        ba.BusinessAMessageSource__c = updateUserFaultInfo.UFMessageSource__c  ;//淇℃伅鏉ユ簮
+        ba.BusinessANatureService__c = updateUserFaultInfo.UFNatureService__c  ;//鏈嶅姟鎬ц川  
+        ba.BusinessAWithoutReason__c = updateUserFaultInfo.UFWithoutReason__c  ;//鏃犲伩鍘熷洜
+        ba.BusinessADateApproval__c = updateUserFaultInfo.UFDateApproval__c  ;//鍚屾剰鎶ヤ环鏃ユ湡
+        ba.BusinessADateQuotation__c = updateUserFaultInfo.UserFaultInfoDateQuotation__c;//鎶ヤ环鏃ユ湡
+        ba.BusinessAServiceContent__c = updateUserFaultInfo.UserFaultInfoServiceContent__c  ;//鏈嶅姟鍐呭(姹囨��)
+        // ba.BusinessAServiceContentNew__c = updateUserFaultInfo.UserFaultInfoServiceContentNew__c  ;//鏈嶅姟鍐呭
+        ba.BusinessAServicePlace__c = updateUserFaultInfo.UserFaultInfoServicePlace__c  ;//鏈嶅姟鍦烘墍
+        ba.BusinessABusinessTrip__c = updateUserFaultInfo.UserFaultInfoBusinessTrip__c  ;//鍑哄樊鍦�
+        ba.BusinessACompletionDate__c = updateUserFaultInfo.UserFaultInfoCompletionDate__c  ;//妗堜欢瀹屾垚鏃�
+        ba.BusinessANextService__c = updateUserFaultInfo.UserFaultInfoNextService__c  ;//涓嬫鏈嶅姟鏃堕棿
+        ba.BusinessAAccount__c = updateUserFaultInfo.UFAccount__c  ;//瀹㈡埛鍗曚綅(鏌ユ壘)
+        ba.BusinessACustomerUnit__c = updateUserFaultInfo.UserFaultInfoCustomerUnit__c ; //瀹㈡埛鍗曚綅(鏂囨湰)
+        ba.BusinessAContact__c = updateUserFaultInfo.UFContact__c  ;//鑱旂郴浜�
+        ba.BusinessAPhone__c = updateUserFaultInfo.UFPhone__c  ;//鑱旂郴鐢佃瘽
+        ba.ManagementCode__c = updateUserFaultInfo.UFManagementCode__c;
+        ba.FindManagementCode__c = updateUserFaultInfo.UFManagementCode__c;
+        ba.User_FaultInfo__c = updateUserFaultInfo.Id;
+        ba.BusinessAServiceCategory__c = updateUserFaultInfo.UserFaultInfoServiceCategory__c;//鏈嶅姟鑼冪暣
+        ba.BusinessAServiceContractNo__c = updateUserFaultInfo.UserFaultInfoServiceContractNo__c;//鏈嶅姟鍚堝悓鍙�
+        ba.BusinessAServiceResult__c = updateUserFaultInfo.UserFaultInfoServiceResult__c;//鏈嶅姟缁撴灉
+        ba.AgreeReportDate__c = updateUserFaultInfo.UserFaultInfoReportDate__c;//鎶ュ憡鏃ユ湡(鍚庡彴鐢�)
+        ba.firstInput__c = '鍚�';
+        ba.StartTimeHour__c = '0';
+        ba.StartTimeMinute__c = '00';
+        ba.EndTimeHour__c = '0';
+        ba.EndTimeMinute__c = '00';
+        ba.workingHours__c = 0.00;
+
+        //鍒ゆ柇 鐢ㄦ埛鏁呴殰淇℃伅 鏄惁鏈� 闄勪欢
+        List<String> parentIdList = new List<String>();
+        parentIdList.add(fromUserFaultInfoId);
+        List<Attachment> userFaultInfoAttachmentList = GetAttachmentList(parentIdList);
+        if (userFaultInfoAttachmentList.size() > 0) {
+            ba.BusinessAHaveAttachment__c = true;
+        }
+        ba.BaFromUserFaultInfo__c  = true;
+        // 鍒ゆ柇 鐢ㄦ埛鏁呴殰淇℃伅 鏄惁鏈� 鏁呴殰浜у搧淇℃伅
+        // List<String> ufIdList = new List<String>();
+        //     ufIdList.add(fromUserFaultInfoId);
+        // List<FailureAsset__c> failureAssetList = TSRepairUtil.GetFailureAssetList(null, ufIdList, null, null, null);
+        // if (failureAssetList.size() > 0) {
+
+        // }
+        return ba;
+    }
+
+    // 鑾峰彇瀹㈡埛
+    public static List<Account> GetAccountList(String accountId,String accountName,List<String> placeholder1,Set<String> placeholder2,String placeholder3){
+        List<Account> result = new List<Account>();
+
+        String sql = '';
+        sql += 'Select Id,Name ';
+        sql += ' from Account ';
+        if (String.isNotBlank(accountId) && String.isNotBlank(accountName)) {
+            sql += ' Where Id = \''+ accountId + '\' AND Name = \'' + accountName +'\'';
+        }
+        // 姝ゅ瑕佹坊鍔犲彧妫�绱� 鏈嶅姟瀹㈡埛
+        System.debug('sql--->'+sql);
+        result = Database.query(sql);
+
+        return result;
+    } 
+    // 鑾峰彇鑱旂郴浜�
+    public static List<Contact> GetContactList(String contactId,List<String> placeholder1,Set<String> placeholder2,String placeholder3){
+        List<Contact> result = new List<Contact>();
+        String sql = '';
+        sql += 'Select Id,Name,AccountId__c ';
+        sql += ' from Contact ';
+        if (String.isNotBlank(contactId)) {
+            sql += ' Where Id = \''+ contactId + '\'';
+        }
+        result = Database.query(sql);
+
+        return result;
+    }
+    public static Map<String,String>  GetserviceCategoryMap(){
+        Map<String,String> result = new Map<String,String>();
+        result.put('鏈嶅姟涓氬姟浜掗��', 'Association');
+        result.put('闆朵欢/鍥鸿祫绠$悊', 'Association');
+        result.put('鍝佷繚鍗忓姪', 'Association');
+        result.put('鍐呴儴娲诲姩', 'Association');
+        result.put('鏈嶅姟鍩硅(澶栭儴鍩硅)', 'Association');
+        result.put('鏈嶅姟鍩硅(鍐呴儴鍩硅)', 'Association');
+        result.put('浠g悊鍟嗙鐞�', 'Association');
+        result.put('灞曚細娲诲姩', 'Association');
+        result.put('鏍锋満瀵瑰簲', 'Association');
+        result.put('璁㈠崟涓氬姟', 'Association');
+        result.put('CIC鍛煎彨涓績', 'Sevice');
+        result.put('鍝佽川&杩斾慨妗堜欢', 'Sevice');
+        result.put('宸℃', 'Sevice');
+        result.put('閿�鍞敮鎸�', 'Sevice');
+        result.put('鎶�鏈敮鎸�', 'Sevice');
+        result.put('绉绘満/鎼', 'Sevice');
+        result.put('缁存姢淇濆吇(涓�鑸湇鍔�)', 'Sevice');
+        result.put('缁存姢淇濆吇(鏈嶅姟鍚堝悓鎵ц)', 'Sevice');
+        result.put('浜у搧瀹夎', 'Sevice');
+        result.put('鏈嶅姟鍚堝悓鎺ㄥ箍', 'Sevice');
+        result.put('鏍″噯锛圛E/NDT/ANI锛�', 'Repair');
+        result.put('杞欢淇悊', 'Repair');
+        result.put('纭欢淇悊', 'Repair');
+
+        return result;
+    } 
+
+    public static String AccountBaseRecordTypeIdSQL(){
+        // String  serviceAccountANI  = System.label.ServiceAccountANI;
+        // String  serviceAccountIE  = System.label.ServiceAccountIE;
+        // String  serviceAccountLS  = System.label.ServiceAccountLS;
+        // String  serviceAccountNDT  = System.label.ServiceAccountNDT;
+        // String  serviceAccountRVI  = System.label.ServiceAccountRVI;
+
+        String  accountANI  = '01228000000TdFL';
+        String  accountIE  = '01228000000TdF6';
+        String  accountLS  = '01228000000TdF1';
+        String  accountNDT  = '01228000000TdFG';
+        String  accountRVI  = '01228000000TdFB';
+        String sql = '';
+        // soql += ' and UFAccount__c  =\''+ accountId +'\'';
+        sql += ' (RecordTypeId  =\''+ accountANI +'\'';
+        sql += ' OR    RecordTypeId  =\''+ accountIE +'\'';
+        sql += ' OR    RecordTypeId  =\''+ accountLS +'\'';
+        sql += ' OR    RecordTypeId  =\''+ accountNDT +'\'';
+        sql += ' OR    RecordTypeId  =\''+ accountRVI +'\')';
+
+        return sql;
+    } 
+
+    public static String AccountBaseRecordTypeIdSQL2(){
+        // String  serviceAccountANI  = System.label.ServiceAccountANI;
+        // String  serviceAccountIE  = System.label.ServiceAccountIE;
+        // String  serviceAccountLS  = System.label.ServiceAccountLS;
+        // String  serviceAccountNDT  = System.label.ServiceAccountNDT;
+        // String  serviceAccountRVI  = System.label.ServiceAccountRVI;
+        String  accountANI  = '01228000000TdFL';
+        String  accountIE  = '01228000000TdF6';
+        String  accountLS  = '01228000000TdF1';
+        String  accountNDT  = '01228000000TdFG';
+        String  accountRVI  = '01228000000TdFB';
+        String sql = '';
+        // soql += ' and UFAccount__c  =\''+ accountId +'\'';
+        sql += ' (UFAccount__r.RecordTypeId  =\''+ accountANI +'\'';
+        sql += ' OR    UFAccount__r.RecordTypeId  =\''+ accountIE +'\'';
+        sql += ' OR    UFAccount__r.RecordTypeId  =\''+ accountLS +'\'';
+        sql += ' OR    UFAccount__r.RecordTypeId  =\''+ accountNDT +'\'';
+        sql += ' OR    UFAccount__r.RecordTypeId  =\''+ accountRVI +'\')';
+
+        return sql;
+    }     
+
+}
\ No newline at end of file
diff --git a/scr/classes/TSRepairUtil.cls-meta.xml b/scr/classes/TSRepairUtil.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TSRepairUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TS_SearchAccountController.cls b/scr/classes/TS_SearchAccountController.cls
new file mode 100644
index 0000000..b3c6586
--- /dev/null
+++ b/scr/classes/TS_SearchAccountController.cls
@@ -0,0 +1,67 @@
+public without sharing class TS_SearchAccountController {
+    public List<Account> results {get; private set;}
+    public Boolean getIsOverLimit() {
+        if (results != null && results.size() > 50) {
+            return true;
+        }
+        return false;
+    }
+
+    public TS_SearchAccountController () {
+        this.results = new List<Account>();
+    }
+
+    public void search() {
+        // 妞滅储鏉′欢銈掔敤鎰�
+        String query = System.currentPageReference().getParameters().get('q');
+        system.debug('query--->'+query);
+        String reporterState = System.currentPageReference().getParameters().get('r');
+        reporterState = reporterState == 'LS' ? 'BS':reporterState;
+
+        if ('NDT/ANI'.equals(reporterState)) {
+            reporterState = '';
+            reporterState +=  ' ( ProductSegmentF__c = \'' +'NDT' +'\' OR ';
+            reporterState +=  ' ProductSegmentF__c = \'' +'ANI' +'\') AND ';
+        } else if ('System'.equals(reporterState)) {
+            reporterState = '';
+            reporterState +=  ' ( ProductSegmentF__c = \'' +'NDT' +'\' OR ';
+            reporterState +=  ' ProductSegmentF__c = \'' +'BS' +'\' OR ';
+            reporterState +=  ' ProductSegmentF__c = \'' +'IE' +'\' OR ';
+            reporterState +=  ' ProductSegmentF__c = \'' +'RVI' +'\' OR ';
+            reporterState +=  ' ProductSegmentF__c = \'' +'ANI' +'\') AND ';
+        } else {
+            reporterState =  ' ProductSegmentF__c = \'' +reporterState +'\' AND ';
+        }
+        if (query == null || query == '') {
+            return;
+        }
+
+        this.search(query, reporterState);
+    }
+
+
+    public void search(String query, String reporterState) {
+        List<String> qwords = new List<String>();
+        List<String> qwordstmp = query.split(' ');
+        String nameCondition = '';
+        for (String qword : qwordstmp) {
+            if (String.isBlank(qword) == false) {
+                qwords.add('%' + String.escapeSingleQuotes(qword.replaceAll('%', '')) + '%');
+                nameCondition += ' Name like \'' + qwords[qwords.size() - 1] + '\' AND ';
+            }
+        }
+        
+        // 妞滅储
+        // 瀹㈡埛 璁板綍绫诲瀷
+        String accountRecordTypeId =  TSRepairUtil.AccountBaseRecordTypeIdSQL() + ' AND ';
+        // 瀹㈡埛 浜у搧鍒嗙被
+        // String accountRecordTypeDelear = ' ProductSegmentF__c = \'' +reporterState +'\' AND ';
+        // String queryString = 'select Id, ProductSegmentF__c,Name from Account where '+ nameCondition +accountRecordTypeId +accountRecordTypeDelear+' Id != null order by Name limit 51';
+         String queryString = 'select Id, ProductSegmentF__c,Name from Account where '+ nameCondition +accountRecordTypeId +reporterState+' Id != null order by Name limit 51';
+        system.debug('queryString=' + queryString);
+        Map<Id, Account> accMap = new Map<Id, Account>((List<Account>) Database.query(queryString));
+        // system.debug('accMap--->'+accMap.values());
+        this.results = accMap.values();                         // values()銇牬鍚堛�侀爢搴忋倧銇嬨倝銇亜銇с仚
+        this.results.sort();                                    // order by Name
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TS_SearchAccountController.cls-meta.xml b/scr/classes/TS_SearchAccountController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TS_SearchAccountController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TS_SearchAccountControllerTest.cls b/scr/classes/TS_SearchAccountControllerTest.cls
new file mode 100644
index 0000000..f61f069
--- /dev/null
+++ b/scr/classes/TS_SearchAccountControllerTest.cls
@@ -0,0 +1,54 @@
+@isTest
+private class TS_SearchAccountControllerTest {
+
+    public static Account account;
+    static void basicData() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        account = new Account(
+            name = 'Test20200827',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c = 'Customer IE',
+            FacilityName__c = 'abc',
+            DivisionName_D__c = 'Customer IE',
+            FacilityNameD__c = 'abc',
+            AccountStatus__c = 'Cancel',
+            PostCode__c = '123456',
+            ProductSegment__c = 'IE'
+        );
+
+        insert account;
+    }
+    // q 姝e父
+    static testMethod void testMethod1() {
+        basicData();
+        PageReference page = new PageReference('/apex/TS_SearchAccount?q=Test20200827&r=' + account.ProductSegment__c);
+        System.Test.setCurrentPage(page);
+        TS_SearchAccountController controller = new TS_SearchAccountController();
+        controller.search();
+
+        controller.getIsOverLimit();
+    }
+    // q null
+    static testMethod void testMethod2() {
+        basicData();
+        String reporterState = 'NDT/ANI';
+        PageReference page = new PageReference('/apex/TS_SearchAccount?q=&r=' + reporterState);
+        System.Test.setCurrentPage(page);
+        TS_SearchAccountController controller = new TS_SearchAccountController();
+        controller.search();
+
+        controller.getIsOverLimit();
+    }
+    // q length < 3
+    static testMethod void testMethod3() {
+        basicData();
+        String reporterState = 'System';
+        PageReference page = new PageReference('/apex/TS_SearchAccount?q=::&r=' + reporterState);
+        System.Test.setCurrentPage(page);
+        TS_SearchAccountController controller = new TS_SearchAccountController();
+        controller.search();
+
+        controller.getIsOverLimit();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TS_SearchAccountControllerTest.cls-meta.xml b/scr/classes/TS_SearchAccountControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TS_SearchAccountControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TaskTriggerHandler.cls b/scr/classes/TaskTriggerHandler.cls
new file mode 100644
index 0000000..4264ea6
--- /dev/null
+++ b/scr/classes/TaskTriggerHandler.cls
@@ -0,0 +1,43 @@
+public without sharing class TaskTriggerHandler {
+   
+     public static String recordtypeId = '';
+    public static void CreateCase(List<Task> newList, Map<Id, Task> newMap, List<Task> oldList, Map<Id, Task> oldMap) {
+        recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Case' and DeveloperName = 'Draft'].id;
+        List<Case> upsertCaseList = new List<Case>();
+        for (Task newTask : newList) {
+            Task oldServiceSummary = oldMap == null ? null : oldMap.get(newTask.Id);
+            if (oldServiceSummary != null) {
+                if (newTask.IndividualCase__c != oldServiceSummary.IndividualCase__c && newTask.IndividualCase__c) {
+                    upsertCaseList.add(CaseDate(newTask));
+                }
+            } else  if (newTask.IndividualCase__c) {
+                upsertCaseList.add(CaseDate(newTask));
+            }
+            
+        }
+
+        if (upsertCaseList.size() > 0 ) {
+            upsert upsertCaseList;
+        }
+
+    }
+
+
+    public static Case CaseDate(Task task) {
+
+        Case newCase = new Case();
+        newCase.Subject = task.ServiceSubject__c; //涓婚 
+        newCase.Description = task.Description; //鎻忚堪
+        // newCase.AccountId = task.ServiceAccount__c; //鏈嶅姟瀹㈡埛
+        newCase.Reason = task.ServiceReason__c; //涓鍘熷洜
+        newCase.Origin = task.ServiceOrigin__c; //涓鏉ユ簮
+        newCase.Priority = task.Priority; //浼樺厛绾�
+        newCase.CreatedDate = Datetime.now(); //寮�濮嬫棩鏈�/鏃堕棿
+        // newCase.CaseServiceSummary__c = task.Id;
+        newCase.Status = 'New';
+        newCase.ApprovalStatus__c = '鑽夋涓�';
+        newCase.recordtypeId = recordtypeId;
+
+        return newCase;
+    } 
+}
\ No newline at end of file
diff --git a/scr/classes/TaskTriggerHandler.cls-meta.xml b/scr/classes/TaskTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TaskTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TradeCustomerManagerController.cls b/scr/classes/TradeCustomerManagerController.cls
new file mode 100644
index 0000000..68553bf
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerController.cls
@@ -0,0 +1,300 @@
+public without sharing class TradeCustomerManagerController {
+
+    public String orderId{get;set;}
+    public String id{get;set;}
+    public String saveYes{get;set;}
+    public TradeCustomerManager__c trade{get;set;}
+    public Order order{get;set;}
+    public List<Attachment> fileList{get;set;}
+    public List<Attachment> fileListNew{get;set;}
+    public List<Attachment> militaryFileList{get;set;}
+    public List<Attachment> personalFileList{get;set;}
+    public Integer personalListSize{get;set;}
+    public Integer militaryListSize{get;set;}
+    public String errorMessage{get;set;}
+    public String fileIdDelete{get;set;}
+    public String fileIdSee{get;set;}
+    public String sendType{get;set;}
+    public Boolean isOnClick{get;set;}
+    public String oppLink{get;set;}
+    public String oppCode{get;set;}
+    public String baseUrl{get;set;}
+    public String isdeleteFile{get;set;}
+
+    public TradeCustomerManagerController() {
+        //鑾峰彇url涓惡甯︾殑鍙傛暟
+        orderId = System.currentPageReference().getParameters().get('orderId');
+        id = System.currentPageReference().getParameters().get('id');
+    }
+    public TradeCustomerManagerController(ApexPages.StandardController stdController) {
+        //鑾峰彇url涓惡甯︾殑鍙傛暟
+        orderId = System.currentPageReference().getParameters().get('orderId');
+        id = System.currentPageReference().getParameters().get('id');
+    }
+
+    public void init() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        saveYes = '';
+        isOnClick = false;
+        fileList = new List<Attachment>();
+        personalFileList = new List<Attachment>();
+        militaryFileList = new List<Attachment>();
+        fileListNew = new List<Attachment>();
+        trade = new TradeCustomerManager__c();
+        if(id != null){
+            //濡傛灉Id涓嶄负null 鏍规嵁Id鍒濆鍖朤radeCustomerManager__c
+            trade = [select Id,useNo__c,userNo__c,placeNo__c,productNo__c,useYes__c,userYes__c,placeYes__c,productYes__c,DealerId__c,
+                        customerInfoIsUpdate__c,studyDirection__c,endUser__c,model__c,PCmodel__c,contractNum__c,PCcontractNum__c,oppId__c,
+                        isAloneCustomer__c,isPC__c,isAlone__c,isHaveLink__c,peopleLink__c,opportunity__c,militaryLink__c,companyLink__c,oppCodeLink__c,
+                        application__c,work__c,watchObject__c,order__c,buyTo__c,OrderIdSave__c,remark__c,isFuelNo__c,isFuelYes__c,productSegment__c from TradeCustomerManager__c 
+                        where Id=:id];
+            order = [select Id,EndUserD__c,applicationForm__c,ProductSegment__c,tradeCustomerApplay__c,ApproveStatus__c,DealerId__c from Order where Id =:trade.OrderIdSave__c];
+            fileList = [select Id,Name,CreatedDate,BodyLength,Body,CreatedById,ParentId from Attachment where ParentId =:id];
+            for(Attachment att :fileList){
+                if(att.Name.startsWith('涓汉淇℃伅')){
+                    personalFileList.add(att);
+                }else if (att.Name.startsWith('鍐涗簨')) {
+                    militaryFileList.add(att);
+                } else{
+                    fileListNew.add(att);
+                }
+            }
+        }
+        if(orderId!=null){
+            //鐐瑰嚮鏂板缓鐢宠琛紝鏌ヨTradeCustomerManager__c  鍒ゆ柇姝ゅ悎鍚屼笅鏄惁鏈夊凡缁忓垱寤虹殑鐢宠琛�
+            order = [select Id,EndUserD__c,applicationForm__c,ProductSegment__c,tradeCustomerApplay__c,ApproveStatus__c,DealerId__c from Order where Id =:orderId];
+            List<TradeCustomerManager__c> tradeIsHaveList = [select Id,useNo__c,userNo__c,placeNo__c,productNo__c,useYes__c,userYes__c,placeYes__c,productYes__c,
+                        customerInfoIsUpdate__c,studyDirection__c,endUser__c,model__c,PCmodel__c,contractNum__c,PCcontractNum__c,oppId__c,DealerId__c,
+                        isAloneCustomer__c,isPC__c,isAlone__c,isHaveLink__c,peopleLink__c,opportunity__c,militaryLink__c,companyLink__c,
+                        application__c,work__c,watchObject__c,order__c,buyTo__c,OrderIdSave__c,remark__c,isFuelNo__c,isFuelYes__c,productSegment__c,oppCodeLink__c from TradeCustomerManager__c 
+                        where order__c=:orderId];
+            System.debug(tradeIsHaveList.size());
+            if(tradeIsHaveList != null && tradeIsHaveList.size()!=0){
+                trade = tradeIsHaveList[0];
+                fileList = [select Id,Name,CreatedDate,BodyLength,Body,CreatedById from Attachment where ParentId =:trade.Id];
+                for(Attachment att :fileList){
+                    if(att.Name.startsWith('涓汉淇℃伅')){
+                        personalFileList.add(att);
+                    }else if (att.Name.startsWith('鍐涗簨')) {
+                        militaryFileList.add(att);
+                    }else{
+                        fileListNew.add(att);
+                    }
+                }
+            }
+            trade.endUser__c = order.EndUserD__c;
+            trade.productSegment__c = order.ProductSegment__c;
+            trade.OrderIdSave__c = orderId;
+            trade.DealerId__c = order.DealerId__c;
+        }
+
+        personalListSize = personalFileList.size();
+        militaryListSize = militaryFileList.size();
+        
+        if(String.isNotBlank(trade.Id)){
+            sendType = 'init';
+            send();
+        }
+        System.debug('ApproveStatus__c:'+order.ApproveStatus__c);
+        //妫�鏌ュ悎鍚�  鍚堝悓涓烘彁浜ょ姸鎬� 鐢宠琛ㄤ笉鍏佽鎿嶄綔
+        if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
+            isOnClick = true;
+        }
+    }
+    // 淇濆瓨鐢宠琛紝蹇呭~椤归獙璇侊紝鏇存柊鍚堝悓涓殑鐢宠琛ㄦ槸鍚︽湁鏁堢殑鏍囪
+    public void send(){
+        //a 鏄惁閫氳繃蹇呭~楠岃瘉鏍囧織
+        Boolean a = true;
+        errorMessage = '1'; 
+        List<String> strList = new List<String>();
+        //蹇呭~椤归獙璇�
+        trade.Name = '璐告槗绠$悊鎮康瀹㈡埛锛圔绫伙級鐢宠琛�';
+        if(trade.isAloneCustomer__c == '鏄�' && (trade.customerInfoIsUpdate__c == null || String.isBlank(trade.oppCodeLink__c))){
+            strList.add('閲嶅瀹㈡埛閫夋嫨鏄紝瀹㈡埛鏄惁鏈夋洿鏂般�佸凡琚鏍搁�氳繃鐨勮浠峰繀濉�;');
+            a = false;
+        } else if(trade.isAloneCustomer__c == null){
+            strList.add('鏄�佸惁閲嶅瀹㈡埛蹇呴』閫夋嫨涓�涓�;');
+            a = false;
+        }
+        if(trade.work__c == null){
+            strList.add('鑱屽姟蹇呭~;');
+            a = false;
+        }
+        if(trade.watchObject__c == null){
+            strList.add('瑙傚療瀵硅薄蹇呭~;');
+            a = false;
+        }
+        if((trade.productSegment__c == 'IE' || trade.productSegment__c == 'RVI') && trade.application__c == null){
+            strList.add('宸ヤ笟閮ㄩ棬鎻愪氦锛屽簲鐢ㄩ鍩熷繀濉�;');
+            a = false;
+        }
+        if(trade.isHaveLink__c == '鏄�' && trade.peopleLink__c==null){
+            strList.add('鐢ㄦ埛鏄惁鏈変釜浜虹綉鍧�閫夋嫨鏄紝涓汉缃戝潃閾炬帴淇℃伅蹇呭~;');
+            a = false;
+        } else if(trade.isHaveLink__c == '鍚�' && trade.companyLink__c == null){
+            strList.add('鐢ㄦ埛鏄惁鏈変釜浜虹綉鍧�閫夋嫨鍚︼紝鎵�鍦ㄥ崟浣嶇綉鍧�蹇呭~;');
+            a = false;
+        } else if(trade.isHaveLink__c == null){
+            strList.add('鐢ㄦ埛鏄�佸惁鏈変釜浜虹綉鍧�蹇呴』閫夋嫨涓�涓�;');
+            a = false;
+        }
+        if(trade.isAlone__c == '鏄�' && (trade.model__c == null || trade.contractNum__c == null)){
+            strList.add('鏄惁鍗曠嫭閮ㄥ搧閲囪喘閫夋嫨鏄紝瀵瑰簲IF YES,涓绘満鍨嬪彿銆両F YES,涓绘満鍚堝悓鍙峰繀濉�;');
+            a = false;
+        } else if(trade.isAlone__c == null){
+            strList.add('鏄�佸惁鍗曠嫭閮ㄥ搧閲囪喘蹇呴』閫夋嫨涓�涓�;');
+            a = false;
+        }
+        /*if(trade.isPC__c == '鏄�' && (trade.PCmodel__c == null || trade.PCcontractNum__c == null)){
+            strList.add('鏄惁PC/鏄剧ず鍣ㄩ噰璐�夋嫨鏄紝瀵瑰簲IF YES,涓绘満鍨嬪彿銆両F YES,涓绘満鍚堝悓鍙峰繀濉�;');
+            a = false;
+        }*/
+        if(trade.militaryLink__c == null){
+            strList.add('浣跨敤鑰呯殑鍐涚敤鍏宠仈web妫�绱㈤摼鎺ュ繀濉�;');
+            a = false;
+        }
+        if ((trade.useYes__c || trade.userYes__c || trade.placeYes__c || trade.productYes__c || trade.isFuelYes__c) && (trade.remark__c == null || trade.remark__c == '纭椤圭洰鏈変换浣曚竴椤归�墆es锛屽娉ㄥ繀濉�')) {
+            strList.add('纭椤圭洰鏈変换浣曚竴椤归�墆es锛屽娉ㄥ繀濉�;');
+            trade.remark__c = '';
+            a = false;
+        }else{
+            if(trade.remark__c == '纭椤圭洰鏈変换浣曚竴椤归�墆es锛屽娉ㄥ繀濉�'){
+                trade.remark__c = '';
+            }
+        }
+        if(militaryFileList.size()!=0){
+            Integer i = 0;
+            for(Attachment att:militaryFileList){
+                if(att.Name.startsWith('鍐涗簨')){
+                    i++;
+                    break;
+                }
+            }
+            if(i == 0){
+                strList.add('闄勪欢鍛藉悕瑙勫垯锛氬啗浜�+璇环鍙�+浣跨敤鑰呬釜浜轰俊鎭紝蹇呴』涓婁紶鍐涗簨鍏宠仈web妫�绱DF鏂囦欢;');
+                a = false;
+            }
+        }else{
+            strList.add('闄勪欢鍛藉悕瑙勫垯锛氬啗浜�+璇环鍙�+浣跨敤鑰呬釜浜轰俊鎭紝蹇呴』涓婁紶鍐涗簨鍏宠仈web妫�绱DF鏂囦欢;');
+            a = false;
+        }
+        if(trade.isHaveLink__c == '鏄�'){
+            if(personalFileList.size()!=null && personalFileList.size()!=0){
+                Integer i = 0;
+                for(Attachment att:personalFileList){
+                    if(att.Name.startsWith('涓汉淇℃伅')){
+                        i++;
+                        break;
+                    }
+                }
+                if(i == 0){
+                    strList.add('闄勪欢鍛藉悕瑙勫垯锛氫釜浜轰俊鎭�+璇环鍙�+浣跨敤鑰呬釜浜轰俊鎭紝鐢ㄦ埛鏄惁鏈変釜浜虹綉鍧�閫夋嫨鏄紝蹇呴』涓婁紶涓汉缃戝潃PDF鏂囦欢;');
+                    a = false;
+                }
+            }else{
+                strList.add('闄勪欢鍛藉悕瑙勫垯锛氫釜浜轰俊鎭�+璇环鍙�+浣跨敤鑰呬釜浜轰俊鎭紝鐢ㄦ埛鏄惁鏈変釜浜虹綉鍧�閫夋嫨鏄紝蹇呴』涓婁紶涓汉缃戝潃PDF鏂囦欢;');
+                a = false;
+            }
+        }
+        trade.order__c = trade.OrderIdSave__c;
+        System.debug(sendType);
+        if(strList!=null && strList.size()!=0){
+            errorMessage = '';
+            for(String str:strList){
+                errorMessage += str + '-';
+            }
+        }
+        if(sendType != 'init'){
+            upsert trade;
+        }
+        System.debug(a);
+        System.debug(order.applicationForm__c);
+        if(a != order.applicationForm__c || (errorMessage!= '1' && order.tradeCustomerApplay__c != errorMessage)){
+            order.applicationForm__c = a;
+            order.tradeCustomerApplay__c = errorMessage;
+            update order;
+        }
+        if(a && sendType=='send'){
+            saveYes = '淇濆瓨鎴愬姛锛�';
+        }else{
+            saveYes = '';
+        }
+        return;
+    }
+    public PageReference uploadFile(){
+        sendType = 'uploadFile';
+        send();
+        String b = trade.Id;
+        if(b != null && b != ''){
+            PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + trade.Id + '&retURL=%2Fapex/TradeCustomerManager?id='+trade.Id);
+            ref.setRedirect(true);
+            return ref;
+        }
+        return null;
+    }
+
+    public void deleteFile(){
+        isdeleteFile = 'YES';
+        if(fileIdDelete!=null && fileIdDelete !=''){
+            for(Integer i=0 ; i<fileListNew.size() ; i++){
+                if(fileListNew[i].Id == fileIdDelete){
+                    TradeCustomerManager__c tra = [select Id,order__c,isHaveLink__c from TradeCustomerManager__c where Id =: fileListNew[i].ParentId];
+                    if(tra!=null){
+                        Order order = [select Id,applicationForm__c,ApproveStatus__c from Order where id=:tra.order__c];
+                        if(order!=null){
+                            if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
+                                isdeleteFile = 'NO';
+                                return;
+                            }
+                        }
+                    }
+                    delete fileListNew[i];
+                    fileListNew.remove(i);
+                    return;
+                }
+            }
+        }
+    }
+    
+    public PageReference deleteForm(){
+        if(String.isNotBlank(trade.Id)){
+            PageReference ref = new Pagereference('/'+trade.OrderIdSave__c);
+            delete trade;
+            order.applicationForm__c = false;
+            update order;
+            //ref.setRedirect(true);
+            return ref;
+        }else{
+            errorMessage = '鐢宠琛ㄦ病鏈変繚瀛橈紒';
+        }
+        return null;
+    }
+
+    public PageReference seeFile(){
+         System.debug('fileIdSee:'+fileIdSee);
+        if(fileIdSee!=null && fileIdSee !=''){
+            PageReference ref = new Pagereference('/'+fileIdSee);
+            //ref.setRedirect(true);
+            return ref;
+        }
+        return null;
+    } 
+
+    public PageReference returnOrder(){
+        /*sendType = 'send';
+        send();*/
+        PageReference ref = new Pagereference('/'+trade.OrderIdSave__c);
+        ref.setRedirect(true);
+        return ref;
+    } 
+
+    public void getOppCode(){
+        
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TradeCustomerManagerController.cls-meta.xml b/scr/classes/TradeCustomerManagerController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TradeCustomerManagerControllerTest.cls b/scr/classes/TradeCustomerManagerControllerTest.cls
new file mode 100644
index 0000000..7c529ee
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerControllerTest.cls
@@ -0,0 +1,144 @@
+@isTest
+private class TradeCustomerManagerControllerTest {
+    static testMethod void testMethod1() {
+        
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accIE;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        PriceBook2 pricebook =new PriceBook2(
+            Name = 'IE'
+        );
+        insert pricebook;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'NDT',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation'
+        );
+        insert opp;
+        
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+
+        OrderItemTriggerHandler.tess();
+
+        List<RecordType> rectOdr = [select id from RecordType where IsActive = true and SobjectType = 'Order' and Name = 'IESalesContract'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = rectOdr[0].Id,
+            SpecialDeliveryAccount__c = accIE.Id,
+            SpecialDeliveryAccount_D__c = accIE.Id,
+            SpecialDeliveryContact2_D__c = con.Id,
+            EndUser__c = con.Id
+        );
+        insert odr; 
+        PageReference page = new PageReference('/apex/TradeCustomerManager?orderId=' + odr.Id);
+        System.Test.setCurrentPage(page);
+        TradeCustomerManagerController controller = new TradeCustomerManagerController();
+        controller.init();
+        controller.deleteForm();
+        controller.send();
+        controller.trade.isAloneCustomer__c = '鏄�';
+        controller.send();
+        controller.trade.isHaveLink__c = '鏄�';
+        controller.send();
+        controller.trade.militaryLink__c = 'militaryLink';
+        controller.send();
+        controller.trade.useYes__c = true;
+        controller.send();
+        controller.trade.isHaveLink__c = '鍚�';
+        controller.trade.companyLink__c = null;
+        controller.send();
+        controller.trade.isAlone__c = '鏄�';
+        controller.trade.model__c = null;
+        controller.send();
+        controller.returnOrder();
+        TradeCustomerManager__c tra = new TradeCustomerManager__c();
+        tra.OrderIdSave__c = odr.Id;
+        tra.order__c =  odr.Id;
+        insert tra;
+
+        Attachment att = new Attachment();
+        att.Name = 'test';
+        att.Body = EncodingUtil.base64Decode('test');
+        att.ParentId = tra.Id;
+        insert att; 
+        Attachment att1 = new Attachment();
+        att1.Name = '涓汉淇℃伅';
+        att1.Body = EncodingUtil.base64Decode('test');
+        att1.ParentId = tra.Id;
+        insert att1; 
+        Attachment att2 = new Attachment();
+        att2.Name = '鍐涗簨';
+        att2.Body = EncodingUtil.base64Decode('test');
+        att2.ParentId = tra.Id;
+        insert att2;
+
+        page = new PageReference('/apex/TradeCustomerManager?id=' + tra.Id);
+        System.Test.setCurrentPage(page);
+        controller = new TradeCustomerManagerController();
+        controller.init();
+        controller.trade.militaryLink__c = 'militaryLink';
+        controller.send();
+        /*controller.upload();*/
+        page = new PageReference('/apex/TradeCustomerManager?orderId=' + odr.Id);
+        System.Test.setCurrentPage(page);
+        controller = new TradeCustomerManagerController();
+        controller.init();
+        controller.uploadFile();
+        controller.init();
+        controller.fileIdSee = att.Id;
+        controller.seeFile();
+		controller.fileIdDelete = att.Id;
+        controller.deleteFile();
+        controller.deleteForm();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TradeCustomerManagerControllerTest.cls-meta.xml b/scr/classes/TradeCustomerManagerControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TradeCustomerManagerSearchOppController.cls b/scr/classes/TradeCustomerManagerSearchOppController.cls
new file mode 100644
index 0000000..e4e725a
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerSearchOppController.cls
@@ -0,0 +1,26 @@
+public with sharing class TradeCustomerManagerSearchOppController {
+	public String DealerId {get;set;}
+	public String byName {get;set;}
+	public String byCode {get;set;}
+	public List<Opportunity> oppList {get;set;}
+
+    public TradeCustomerManagerSearchOppController() {
+        DealerId = System.currentPageReference().getParameters().get('DealerId');
+    }
+
+    public void init(){
+    	
+    }
+
+    public void doSearch(){
+		String sql = 'select Id,Name,InquiryNumber__c,Account.Name,customerType__c,Dealer__r.Name,NewInquiryDate__c from Opportunity where id != null';
+		if(String.isNotBlank(byName)){
+			sql += ' and Name like \'%'+String.escapeSingleQuotes(byName.trim().replaceAll('%', '\\%'))+'%\'';
+		}
+		if(String.isNotBlank(byCode)){
+			sql += ' and InquiryNumber__c like \'%'+String.escapeSingleQuotes(byCode.trim().replaceAll('%', '\\%'))+'%\'';
+		}
+		System.debug(sql);
+		oppList = Database.query(sql+' order by NewInquiryDate__c desc limit 100');	
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TradeCustomerManagerSearchOppController.cls-meta.xml b/scr/classes/TradeCustomerManagerSearchOppController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerSearchOppController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TradeCustomerManagerSearchOppTest.cls b/scr/classes/TradeCustomerManagerSearchOppTest.cls
new file mode 100644
index 0000000..786f684
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerSearchOppTest.cls
@@ -0,0 +1,12 @@
+@isTest
+private class TradeCustomerManagerSearchOppTest {
+    static testMethod void testMethod1() {
+    	PageReference page = new PageReference('/apex/TradeCustomerManagerSearchOpp?DealerId=' + '0010K00002FmNa2');
+        System.Test.setCurrentPage(page);
+        TradeCustomerManagerSearchOppController Controller = new TradeCustomerManagerSearchOppController();
+        Controller.init();
+        Controller.byName = 'test';
+        Controller.byCode = 'test';
+        Controller.doSearch();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TradeCustomerManagerSearchOppTest.cls-meta.xml b/scr/classes/TradeCustomerManagerSearchOppTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TradeCustomerManagerSearchOppTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TrialCustomerPortalHomePageController.cls b/scr/classes/TrialCustomerPortalHomePageController.cls
new file mode 100644
index 0000000..a91fe08
--- /dev/null
+++ b/scr/classes/TrialCustomerPortalHomePageController.cls
@@ -0,0 +1,80 @@
+public class TrialCustomerPortalHomePageController {
+   
+   User loggedInUser = [Select id,contactId,Contact.AccountId from User where id = :UserInfo.getUserId()];
+   
+   public List<Asset> MyRegisteredProducts {get; set;}
+   public List<Case> MyRecentCases {get; set;}
+   public List<Solution> TopSolutions {get; set;}
+   public List<Idea> PopularIdeas {get; set;}
+   
+   public String sortField1 {get; set;}
+   public String previousSortField1 {get; set;}
+   public String sortField2 {get; set;}
+   public String previousSortField2 {get; set;}
+   public String sortField3 {get; set;}
+   public String previousSortField3 {get; set;}
+   public String sortField4 {get; set;}
+   public String previousSortField4 {get; set;}
+            
+   public TrialCustomerPortalHomePageController() {
+        MyRegisteredProducts = [select id,Name,SerialNumber,InstallDate,UsageEndDate,Status 
+                                from Asset 
+                                where ContactId = :loggedInUser.ContactId 
+                                order by SerialNumber desc limit 3];
+        
+        MyRecentCases = [select id,CaseNumber,Subject,Status,LastModifiedDate 
+                         from Case 
+                         where ContactId = :loggedInUser.ContactId 
+                         order by LastModifiedDate desc limit 3];
+        
+        TopSolutions = [select id,SolutionName,TimesUsed,LastModifiedDate 
+                        from Solution 
+                        order by TimesUsed desc limit 3];
+                              
+        PopularIdeas = [select id,Title,Categories,VoteTotal 
+                        from Idea 
+                        order by VoteTotal desc limit 3];
+   }
+   
+   public void SortProducts(){
+        String order = 'asc';
+        if(previousSortField1 == sortField1){
+            order = 'desc';
+            previousSortField1 = null;
+        }else{
+            previousSortField1 = sortField1;
+        }
+        superSort.sortList(MyRegisteredProducts,sortField1,order);
+    }
+    public void SortCases(){
+        String order = 'asc';
+        if(previousSortField2 == sortField2){
+            order = 'desc';
+            previousSortField2 = null;
+        }else{
+            previousSortField2 = sortField2;
+        }
+        superSort.sortList(MyRecentCases,sortField2,order);
+    }
+    public void SortSolutions(){
+        String order = 'asc';
+        if(previousSortField3 == sortField3){
+            order = 'desc';
+            previousSortField3 = null;
+        }else{
+            previousSortField3 = sortField3;
+        }
+        superSort.sortList(TopSolutions,sortField3,order);
+    }
+    public void SortIdeas(){
+        String order = 'asc';
+        if(previousSortField4 == sortField4){
+            order = 'desc';
+            previousSortField4 = null;
+        }else{
+            previousSortField4 = sortField4;
+        }
+        superSort.sortList(PopularIdeas,sortField4,order);
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/TrialCustomerPortalHomePageController.cls-meta.xml b/scr/classes/TrialCustomerPortalHomePageController.cls-meta.xml
new file mode 100644
index 0000000..6dc8b22
--- /dev/null
+++ b/scr/classes/TrialCustomerPortalHomePageController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TydelikeACController.cls b/scr/classes/TydelikeACController.cls
new file mode 100644
index 0000000..56193b3
--- /dev/null
+++ b/scr/classes/TydelikeACController.cls
@@ -0,0 +1,298 @@
+public without sharing class TydelikeACController {
+	public TydelikeAccount__c tya {get;set;}
+	public TydelikeContact__c tyc {get;set;}
+	public Account acc {get;set;}
+    public String settyAcId {get;set;}
+    public String settyCoId {get;set;}
+    public Boolean settyof {get;set;}
+    public Integer lineNum {get;set;}
+    //鎶ラ敊鍙婃樉绀轰俊鎭�
+    public String errorMessage{get;set;}
+    public String accId{get;set;}
+    public String accountId{get;set;}
+    public String accname {get;set;}
+    //url
+	public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+    //妫�绱�
+    public String tycontactname { get; set; } //鑱旂郴浜哄鍚�
+    public String tycountname { get; set; }  //瀹㈡埛濮撳悕
+    public String tycountcity { get; set; }  //瀹㈡埛鐨勫煄甯�
+    // Bean
+    public List<DataLineBean> dataLines { get; set; }
+    // 琛屾暟
+    public Integer getDatalineSize() {
+        return dataLines == null ? 0 : dataLines.size();
+    }
+
+    public TydelikeACController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+    //椤甸潰鍒濆鍖�
+    public PageReference init() {
+        dataLines = new List<DataLineBean>();
+        Map<Id,TydelikeAccount__c> tyacMap = new Map<Id,TydelikeAccount__c>();
+        Map<Id,List<TydelikeContact__c>> tycoMap = new Map<Id,List<TydelikeContact__c>>();
+        List<TydelikeAccount__c> tyacList = new List<TydelikeAccount__c>();
+        List<TydelikeContact__c> tycoList = new List<TydelikeContact__c>();
+        // 鏄庣粏Bean
+        tyacList = [select id,name,OfSkrap__c,TyCity__c,TyAddress__c,TyPostCode__c,Account1__c from TydelikeAccount__c];
+        tycoList = [select id,name,OfSkrap__c,TydelikeAccount__c,TyFaxD__c,TyAddress__c,TyPhoneD__c,TyPostcode__c from TydelikeContact__c];
+        if (tyacList.size() == 0) {
+            return null;
+        }
+        if (tycoList.size() == 0) {
+            return null;
+        }
+        for (TydelikeAccount__c tyac: tyacList) {
+            tyacMap.put(tyac.Id, tyac);
+        }
+        for (TydelikeContact__c tyco: tycoList) {
+            if (tycoMap.containsKey(tyco.TydelikeAccount__c)) {
+                tycoMap.get(tyco.TydelikeAccount__c).add(tyco);
+            }else {
+                tycoMap.put(tyco.TydelikeAccount__c, new List<TydelikeContact__c>());
+                tycoMap.get(tyco.TydelikeAccount__c).add(tyco);
+            }  
+        }
+        Integer cnt = 0;
+        for (TydelikeAccount__c tyac1: tyacList) {
+            if (tycoMap.containsKey(tyac1.Id)) {
+                for(Integer i = 0; i< tycoMap.get(tyac1.Id).size(); i++){
+                DataLineBean dataLine = new DataLineBean();
+                dataLine.lineNum = cnt ;
+                cnt ++;
+                dataLine.tyacId = tyacMap.get(tyac1.Id).Id;
+                dataLine.tyacName = tyacMap.get(tyac1.Id).Name;
+                dataLine.tyacof = tyacMap.get(tyac1.Id).OfSkrap__c;
+                dataLine.tyaccity = tyacMap.get(tyac1.Id).TyCity__c;
+                dataLine.tyacadd = tyacMap.get(tyac1.Id).TyAddress__c;
+                dataLine.tyacpost = tyacMap.get(tyac1.Id).TyPostCode__c;
+                dataLine.tycoName = tycoMap.get(tyac1.Id)[i].Name;
+                dataLine.tycoId = tycoMap.get(tyac1.Id)[i].Id;
+                dataLine.tycoof = tycoMap.get(tyac1.Id)[i].OfSkrap__c;
+                dataLine.tyaccount = tycoMap.get(tyac1.Id)[i].TydelikeAccount__c;
+                dataLine.tycofax = tycoMap.get(tyac1.Id)[i].TyFaxD__c;
+                dataLine.tycoadd = tycoMap.get(tyac1.Id)[i].TyAddress__c;
+                dataLine.tycophone = tycoMap.get(tyac1.Id)[i].TyPhoneD__c;
+                dataLine.tycopost = tycoMap.get(tyac1.Id)[i].TyPostcode__c;
+                dataLines.add(dataLine);
+                System.debug('dataLine.lineNum='+dataLine.lineNum);
+                }
+            }else {
+                DataLineBean dataLine = new DataLineBean();
+                dataLine.lineNum = cnt;
+                cnt ++;
+                dataLine.tyacId = tyacMap.get(tyac1.Id).Id;
+                dataLine.tyacName = tyacMap.get(tyac1.Id).Name;
+                dataLine.tyacof = tyacMap.get(tyac1.Id).OfSkrap__c;
+                dataLine.tyaccity = tyacMap.get(tyac1.Id).TyCity__c;
+                dataLine.tyacadd = tyacMap.get(tyac1.Id).TyAddress__c;
+                dataLine.tyacpost = tyacMap.get(tyac1.Id).TyPostCode__c;
+                dataLine.tycoName = null;
+                dataLine.tycoId = null;
+                dataLine.tyaccount = null;
+                dataLine.tycofax = null;
+                dataLine.tycoadd = null;
+                dataLine.tycophone = null;
+                dataLine.tycopost = null;
+                dataLines.add(dataLine);
+                System.debug('dataLine.lineNum='+dataLine.lineNum);
+            }
+        }
+        System.debug('dataLines='+dataLines);
+    	return null;
+    }
+    //妫�绱�
+    public PageReference searchTy() {
+        dataLines = new List<DataLineBean>();
+        Map<Id,TydelikeAccount__c> tyacMap = new Map<Id,TydelikeAccount__c>();
+        Map<Id,List<TydelikeContact__c>> tycoMap = new Map<Id,List<TydelikeContact__c>>();
+        List<TydelikeAccount__c> tyacList = new List<TydelikeAccount__c>();
+        List<TydelikeContact__c> tycoList = new List<TydelikeContact__c>();
+        // 鏄庣粏Bean
+        String acsoql = 'select id,name,OfSkrap__c,TyCity__c,TyAddress__c,TyPostCode__c,Account1__c from TydelikeAccount__c WHERE Id != null';
+
+        if (String.isNotBlank(tycountname)) {
+            acsoql += ' and  Name like \'%' + String.escapeSingleQuotes(tycountname.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+        if (String.isNotBlank(tycountcity)) {
+            acsoql += ' and  TyCity__c like \'%' + String.escapeSingleQuotes(tycountcity.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+
+        String cosoql = 'select id,name,OfSkrap__c,TydelikeAccount__c,TyFaxD__c,TyAddress__c,TyPhoneD__c,TyPostcode__c from TydelikeContact__c WHERE Id != null';
+       
+        if (String.isNotBlank(tycontactname)) {
+            cosoql += ' and  Name like \'%' + String.escapeSingleQuotes(tycontactname.trim().replaceAll('%', '\\%')) + '%\'';
+        }
+
+        tyacList = Database.query(acsoql);
+        tycoList = Database.query(cosoql);
+        if (tyacList.size() == 0) {
+            return null;
+        }
+        if (tycoList.size() == 0) {
+            return null;
+        }
+        for (TydelikeAccount__c tyac: tyacList) {
+            tyacMap.put(tyac.Id, tyac);
+        }
+        for (TydelikeContact__c tyco: tycoList) {
+            if (tycoMap.containsKey(tyco.TydelikeAccount__c)) {
+                tycoMap.get(tyco.TydelikeAccount__c).add(tyco);
+            }else {
+                tycoMap.put(tyco.TydelikeAccount__c, new List<TydelikeContact__c>());
+                tycoMap.get(tyco.TydelikeAccount__c).add(tyco);
+            }
+        }
+        Integer cnt = 0;
+        for (TydelikeAccount__c tyac1: tyacList) {
+            if (tycoMap.containsKey(tyac1.Id)) {
+                for(Integer i = 0; i< tycoMap.get(tyac1.Id).size(); i++){
+                DataLineBean dataLine = new DataLineBean();
+                dataLine.lineNum = cnt ;
+                cnt ++;
+                dataLine.tyacId = tyacMap.get(tyac1.Id).Id;
+                dataLine.tyacName = tyacMap.get(tyac1.Id).Name;
+                dataLine.tyacof = tyacMap.get(tyac1.Id).OfSkrap__c;
+                dataLine.tyaccity = tyacMap.get(tyac1.Id).TyCity__c;
+                dataLine.tyacadd = tyacMap.get(tyac1.Id).TyAddress__c;
+                dataLine.tyacpost = tyacMap.get(tyac1.Id).TyPostCode__c;
+                dataLine.tycoName = tycoMap.get(tyac1.Id)[i].Name;
+                dataLine.tycoId = tycoMap.get(tyac1.Id)[i].Id;
+                dataLine.tycoof = tycoMap.get(tyac1.Id)[i].OfSkrap__c;
+                dataLine.tyaccount = tycoMap.get(tyac1.Id)[i].TydelikeAccount__c;
+                dataLine.tycofax = tycoMap.get(tyac1.Id)[i].TyFaxD__c;
+                dataLine.tycoadd = tycoMap.get(tyac1.Id)[i].TyAddress__c;
+                dataLine.tycophone = tycoMap.get(tyac1.Id)[i].TyPhoneD__c;
+                dataLine.tycopost = tycoMap.get(tyac1.Id)[i].TyPostcode__c;
+                dataLines.add(dataLine);
+                System.debug('dataLine.lineNum='+dataLine.lineNum);
+                }
+            }else {
+                if (String.isBlank(tycontactname)) {
+                    DataLineBean dataLine = new DataLineBean();
+                    dataLine.lineNum = cnt;
+                    cnt ++;
+                    dataLine.tyacId = tyacMap.get(tyac1.Id).Id;
+                    dataLine.tyacName = tyacMap.get(tyac1.Id).Name;
+                    dataLine.tyacof = tyacMap.get(tyac1.Id).OfSkrap__c;
+                    dataLine.tyaccity = tyacMap.get(tyac1.Id).TyCity__c;
+                    dataLine.tyacadd = tyacMap.get(tyac1.Id).TyAddress__c;
+                    dataLine.tyacpost = tyacMap.get(tyac1.Id).TyPostCode__c;
+                    dataLine.tycoName = null;
+                    dataLine.tycoId = null;
+                    dataLine.tyaccount = null;
+                    dataLine.tycofax = null;
+                    dataLine.tycoadd = null;
+                    dataLine.tycophone = null;
+                    dataLine.tycopost = null;
+                    dataLines.add(dataLine);
+                    System.debug('dataLine.lineNum='+dataLine.lineNum);
+                }
+            }
+        }
+        System.debug('dataLines='+dataLines);
+        return null;
+    }
+    //鍒犻櫎鍜屾壒閲忓垹闄�
+    public PageReference setOfSkrapBtn() {
+        List<Id> tycoofIdList = new List<Id>();
+        List<Id> tyacofIdList = new List<Id>();
+        for (DataLineBean d : dataLines) {
+            if(d.bondel == true){
+                if (d.tyaccount != null) {
+                    tycoofIdList.add(d.tycoId);
+                }else {
+                    tyacofIdList.add(d.tyacId);
+                }
+            }
+        }
+        System.debug('tyacofIdList='+tyacofIdList);
+
+        
+        Map<Id,TydelikeAccount__c> uptyacMap = new Map<Id,TydelikeAccount__c>();
+        List<TydelikeAccount__c> tyacofList = new List<TydelikeAccount__c>();
+        tyacofList = [select id,OfSkrap__c from TydelikeAccount__c];
+        if (tyacofIdList.size() > 0) {
+            for (TydelikeAccount__c uptyac : tyacofList) {
+                TydelikeAccount__c uptyacof = new TydelikeAccount__c();
+                if (tyacofIdList.contains(uptyac.Id)) {
+                    uptyacof.Id = uptyac.Id;
+                    uptyacof.OfSkrap__c = true;
+                    //uptyacList.add(uptyacof);
+                    uptyacMap.put(uptyacof.Id,uptyacof);
+                }
+            }
+        }
+        if (uptyacMap.size() > 0) {
+            update uptyacMap.values();
+        }
+        
+        Map<Id,TydelikeContact__c> uptycoMap = new Map<Id,TydelikeContact__c>();
+        List<TydelikeContact__c> tycoofList = new List<TydelikeContact__c>();
+        tycoofList = [select id,OfSkrap__c from TydelikeContact__c];
+        if (tycoofIdList.size() > 0) {
+            for (TydelikeContact__c uptyco : tycoofList) {
+                TydelikeContact__c uptycoof = new TydelikeContact__c();
+                if (tycoofIdList.contains(uptyco.Id)) {
+                    uptycoof.Id = uptyco.Id;
+                    uptycoof.OfSkrap__c = true;
+                    //uptyacList.add(uptyacof);
+                    uptycoMap.put(uptycoof.Id,uptycoof);
+                }
+            }
+        }
+        if (uptycoMap.size() > 0) {
+            update uptycoMap.values();
+        }
+        
+        
+        return null;
+    }
+
+    public class DataLineBean {
+        //鎵归噺
+        public Boolean bondel {get;set;}
+        //琛屽彿
+        public Integer lineNum {get;set;}
+        //涓存椂瀹㈡埛Id
+        public String tyacId {get;set;}
+        //涓存椂瀹㈡埛鍚�
+        public String tyacName {get;set;}
+        //涓存椂瀹㈡埛鏄惁鍒犻櫎
+        public Boolean tyacof {get;set;}
+        //涓存椂瀹㈡埛鍩庡競
+        public String tyaccity {get;set;}
+        //涓存椂瀹㈡埛鍦板潃
+        public String tyacadd {get;set;}
+        //涓存椂瀹㈡埛閭紪
+        public String tyacpost {get;set;}
+        //涓存椂鑱旂郴浜篒d
+        public String tycoId {get;set;}
+        //涓存椂鑱旂郴浜哄悕
+        public String tycoName {get;set;}
+        //涓存椂鑱旂郴浜烘槸鍚﹀垹闄�
+        public Boolean tycoof {get;set;}
+        //涓存椂鑱旂郴浜虹殑鏌ユ壘涓存椂瀹㈡埛 鍚屾椂涔熸槸涓存椂瀹㈡埛
+        public String tyaccount {get;set;} 
+        //涓存椂鑱旂郴浜轰紶鐪�
+        public String tycofax {get;set;}
+        //涓存椂鑱旂郴浜哄湴鍧�
+        public String tycoadd {get;set;}
+        //涓存椂鑱旂郴浜虹數璇� 
+        public String tycophone {get;set;}
+        //涓存椂鑱旂郴浜洪偖鏀跨紪鐮�
+        public String tycopost {get;set;}
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TydelikeACController.cls-meta.xml b/scr/classes/TydelikeACController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TydelikeACController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TydelikeACControllerTest.cls b/scr/classes/TydelikeACControllerTest.cls
new file mode 100644
index 0000000..02b77cd
--- /dev/null
+++ b/scr/classes/TydelikeACControllerTest.cls
@@ -0,0 +1,115 @@
+@isTest
+private class TydelikeACControllerTest {
+    static testMethod void testMethod1() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c(
+            name = '*',
+            OwnerId = UserInfo.getUserId(),
+            TyCity__c = '鍖椾含',
+            OfSkrap__c = false,
+            TyAddress__c = '11111',
+            TyPostCode__c = '123456'
+        );
+        TydelikeAccount__c acc2 = new TydelikeAccount__c(
+            name = '*',
+            OwnerId = UserInfo.getUserId(),
+            TyCity__c = '鍖椾含',
+            OfSkrap__c = false,
+            TyAddress__c = '11111',
+            TyPostCode__c = '123456'
+        );
+        TydelikeAccount__c acc3 = new TydelikeAccount__c(
+            name = '*',
+            OwnerId = UserInfo.getUserId(),
+            TyCity__c = '鍖椾含',
+            OfSkrap__c = false,
+            TyAddress__c = '11111',
+            TyPostCode__c = '123456'
+        );
+        insert new List<TydelikeAccount__c> {acc1,acc2,acc3};
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+        	tycon1.name = '*';
+        	tycon1.OfSkrap__c = false;
+        	tycon1.TydelikeAccount__c = acc1.Id;
+        	tycon1.TyAddress__c = '11111';
+        	tycon1.TyFaxD__c = '1111';
+        	tycon1.TyPhoneD__c = '15555555555';
+        	tycon1.TyPostcode__c = '111111';
+        insert tycon1;
+
+        TydelikeACController  controller = new TydelikeACController();
+
+        controller.init();
+        controller.getDatalineSize();
+
+        /*controller.tycontactname = '*';*/
+        controller.tycountname = '*';
+        controller.tycountcity = '鍖椾含';
+        controller.searchTy();
+
+        controller.dataLines[0].bondel = true;
+        controller.dataLines[1].bondel = true;
+        controller.setOfSkrapBtn();
+    }
+
+    static testMethod void testMethod2() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c(
+            name = '*',
+            OwnerId = UserInfo.getUserId(),
+            TyCity__c = '鍖椾含',
+            OfSkrap__c = false,
+            TyAddress__c = '11111',
+            TyPostCode__c = '123456'
+        );
+        TydelikeAccount__c acc2 = new TydelikeAccount__c(
+            name = '*',
+            OwnerId = UserInfo.getUserId(),
+            TyCity__c = '鍖椾含',
+            OfSkrap__c = false,
+            TyAddress__c = '11111',
+            TyPostCode__c = '123456'
+        );
+        TydelikeAccount__c acc3 = new TydelikeAccount__c(
+            name = '*',
+            OwnerId = UserInfo.getUserId(),
+            TyCity__c = '鍖椾含',
+            OfSkrap__c = false,
+            TyAddress__c = '11111',
+            TyPostCode__c = '123456'
+        );
+        insert new List<TydelikeAccount__c> {acc1,acc2,acc3};
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+            tycon1.name = '*';
+            tycon1.OfSkrap__c = false;
+            tycon1.TydelikeAccount__c = acc1.Id;
+            tycon1.TyAddress__c = '11111';
+            tycon1.TyFaxD__c = '1111';
+            tycon1.TyPhoneD__c = '15555555555';
+            tycon1.TyPostcode__c = '111111';
+        insert tycon1;
+
+        TydelikeContact__c tycon2 = new TydelikeContact__c();
+            tycon2.name = '*';
+            tycon2.OfSkrap__c = false;
+            tycon2.TydelikeAccount__c = acc1.Id;
+            tycon2.TyAddress__c = '11111';
+            tycon2.TyFaxD__c = '1111';
+            tycon2.TyPhoneD__c = '15555555555';
+            tycon2.TyPostcode__c = '111111';
+        insert tycon2;
+
+        TydelikeACController  controller = new TydelikeACController();
+
+        controller.init();
+        controller.getDatalineSize();
+
+        controller.tycontactname = '*';
+        controller.tycountname = '*';
+        controller.tycountcity = '鍖椾含';
+        controller.searchTy();
+
+        controller.dataLines[0].bondel = true;
+        controller.setOfSkrapBtn();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TydelikeACControllerTest.cls-meta.xml b/scr/classes/TydelikeACControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TydelikeACControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TydelikeAccController.cls b/scr/classes/TydelikeAccController.cls
new file mode 100644
index 0000000..127198f
--- /dev/null
+++ b/scr/classes/TydelikeAccController.cls
@@ -0,0 +1,178 @@
+public with sharing class TydelikeAccController {
+	public Account acc {get;set;}
+	public Contact con {get;set;}
+	public TydelikeAccount__c tyac {get;set;}
+	public TydelikeContact__c tyco {get;set;}
+    public String tycoId { get; set; }
+    public String tyacId { get; set; }
+
+	public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public TydelikeAccController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+    //椤甸潰鍒濆鍖�
+    public PageReference init() {
+    	tyacId = System.currentPageReference().getParameters().get('tyacId');
+    	tycoId = System.currentPageReference().getParameters().get('tycoId');
+        System.debug('tyacId='+tyacId);
+        System.debug('tycoId+'+tycoId);
+
+        //褰撳墠鐧婚檰浜篒D銆備紶浜嗕骇鍝佸垎绫诲氨鐢ㄤ紶鐨�,娌′紶灏辩敤鍙栧埌鐨勩��
+        /*String now_userId = UserInfo.getUserId();
+        now_userId.substring(0,15);
+        List<Id> uidList = new List<Id>();
+        List<user> userList = new List<user>();
+
+        userList = [select ContactId from User where Id =:now_userId]; 
+        if (userList.size() == 0) {
+            return null;
+        }
+
+        uidList.add(userList.get(0).ContactId);
+        String productSegment = '';
+        List<Contact> cprList = new List<Contact>();
+        cprList = [select ProductSegment__c from Contact where Id =:uidList];
+        if (cprList.size() == 0) {
+            return null;
+        }
+        productSegment = cprList.get(0).ProductSegment__c;
+        System.debug('productSegment='+productSegment);*/
+
+    	//鏄剧ず瀹㈡埛
+    	List<TydelikeAccount__c> tyacList = new List<TydelikeAccount__c>();
+    	tyacList = [select id,Name,AssetBS3D__c,AssetBS2D__c,OCNServiceStaff__c,AssetBS1D__c,AssetBS5D__c,ManagementCode_Ext__c,
+    	Sub_UseD__c,AssetBS4D__c,EnglishNameD__c,DepartmentNameD__c,FacilityNameD__c,IndustryCD__c,MarketVerticalsD__c,CancelReasonD__c,
+    	ExportRegulatedCustomer__c,Province__c,Whether_OEM__c,OfSkrap__c,GlobalAccountName__c,DivisionName_D__c,UseD__c,UserType__c,
+    	WebsiteD__c,KeyAccount__c,TyCity__c,TyAddress__c,TyPostCode__c,ProductSegment__c,FaxD__c,Remark__c,DealerSelectOwner__c,
+    	PhoneD__c,NationalEnterpriseUser__c 
+    	from TydelikeAccount__c where id =: tyacId];
+    	if (tyacList.size() > 0) {
+    	    tyac = tyacList[0];
+    	}
+    	System.debug('tyac='+tyac);
+
+    	//鍒濆鍖栧鎴疯祴鍊�
+    	acc = new Account();
+        acc.Name = tyac.Name;
+    	acc.AssetBS3D__c = tyac.AssetBS3D__c;
+    	acc.AssetBS2D__c = tyac.AssetBS2D__c;
+    	acc.OCNServiceStaff__c = tyac.OCNServiceStaff__c;
+    	acc.AssetBS1D__c = tyac.AssetBS1D__c;
+    	acc.AssetBS5D__c = tyac.AssetBS5D__c;
+    	acc.ManagementCode_Ext__c = tyac.ManagementCode_Ext__c;
+    	acc.Sub_UseD__c = tyac.Sub_UseD__c;
+    	acc.EnglishNameD__c = tyac.EnglishNameD__c;
+    	acc.DepartmentNameD__c = tyac.DepartmentNameD__c;
+    	acc.FacilityNameD__c = tyac.FacilityNameD__c;
+    	acc.MarketVerticalsD__c = tyac.MarketVerticalsD__c;
+    	acc.CancelReasonD__c = tyac.CancelReasonD__c;
+    	acc.ExportRegulatedCustomer__c = tyac.ExportRegulatedCustomer__c;
+    	acc.Province__c = tyac.Province__c;
+    	acc.Whether_OEM__c = tyac.Whether_OEM__c;
+    	acc.GlobalAccountName__c = tyac.GlobalAccountName__c;
+    	acc.DivisionName_D__c = tyac.DivisionName_D__c;
+    	acc.UseD__c = tyac.UseD__c;
+    	acc.UserType__c = tyac.UserType__c;
+    	acc.WebsiteD__c = tyac.WebsiteD__c;
+    	acc.CityD__c = tyac.TyCity__c;
+    	acc.Address1D__c = tyac.TyAddress__c;
+    	acc.PostCodeD__c = tyac.TyPostCode__c;
+        acc.ProductSegment__c = tyac.ProductSegment__c;
+    	/*acc.ProductSegment__c = tyac.ProductSegment__c == null?productSegment:tyac.ProductSegment__c;*/
+    	acc.FaxD__c = tyac.FaxD__c;
+    	acc.Remark__c = tyac.Remark__c;
+    	acc.DealerSelectOwner__c = tyac.DealerSelectOwner__c;
+    	acc.PhoneD__c = tyac.PhoneD__c;
+    	acc.NationalEnterpriseUser__c = tyac.NationalEnterpriseUser__c;
+        acc.AssetBS4D__c = tyac.AssetBS4D__c;
+        
+        if (String.isNotBlank(tycoId)) {
+            List<TydelikeContact__c> tycoList = [select 
+            Id,Name,TyAddress__c,TyFaxD__c,TyPhoneD__c,TyPostcode__c,EnglishAddress__c,ContactEnglishName__c 
+            from TydelikeContact__c 
+            where Id =: tycoId];
+            if (tycoList.size() > 0) {
+                tyco = tycoList[0];
+            }
+
+            //鍒濆鍖栬仈绯讳汉璧嬪��
+            con = new Contact();
+            con.LastName = tyco.Name;
+            con.Address1D__c = tyco.TyAddress__c;
+            con.FaxD__c = tyco.TyFaxD__c;
+            con.MobilePhoneD__c = tyco.TyPhoneD__c;
+            con.PostcodeD__c = tyco.TyPostcode__c;
+            con.EnglishAddress__c = tyco.EnglishAddress__c;
+            con.ContactEnglishName__c = tyco.ContactEnglishName__c;
+        }
+    	
+
+    	return null;
+    }
+
+    public PageReference save() {
+        //鍒涘缓,鑲畾鏈夊鎴枫�傝嫢鏃犺仈绯讳汉,鏄剧ず瀹㈡埛鍒涘缓椤甸潰銆�
+        //閫氳繃url浼犺繘鏉ョ殑鑱旂郴浜篿d,tycoId銆傞�氳繃url浼犺繘鏉ョ殑瀹㈡埛id,tyacId
+    	tycoId = System.currentPageReference().getParameters().get('tycoId');
+        tyacId = System.currentPageReference().getParameters().get('tyacId');
+        List<TydelikeContact__c> tyconList = new List<TydelikeContact__c>();
+        if (String.isNotBlank(tycoId)) {
+            TydelikeContact__c tycontact = new TydelikeContact__c();
+            tycontact.Id = tycoId;
+            tycontact.OfSkrap__c = true;
+            tycontact.Ofomtecon__c = true;
+            tyconList.add(tycontact);
+            System.debug('tyconList='+tyconList);
+        }
+        //OfSkrap__c,Ofomtecon__c,Ofomteacc__c,甯姪璋冩煡銆�
+        List<TydelikeAccount__c> tyacList = new List<TydelikeAccount__c>();
+        TydelikeAccount__c tyaccount = new TydelikeAccount__c();
+        tyaccount.Id = tyacId;
+        tyaccount.Ofomteacc__c = true;
+        tyacList.add(tyaccount);       
+        System.debug('tyacList='+tyacList);
+
+    	Savepoint sp = Database.setSavepoint();
+        try {
+            if (String.isNotBlank(tycoId)) {
+                update tyconList;  
+            }
+        	update tyacList;
+        	insert acc;
+            if (String.isNotBlank(tycoId)) {
+                con.AccountId = acc.Id;
+                if (acc.ProductSegment__c == 'BS') {
+                    con.ProductSegmentBS__c = true;
+                }else if(acc.ProductSegment__c == 'IE'){
+                    con.ProductSegmentIE__c = true;
+                }else if(acc.ProductSegment__c == 'NDT'){
+                    con.ProductSegmentNDT__c = true;
+                }else if(acc.ProductSegment__c == 'ANI'){
+                    con.ProductSegmentANI__c = true;
+                }else if(acc.ProductSegment__c == 'RVI'){
+                    con.ProductSegmentRVI__c = true;
+                }
+                insert con;
+            }
+        	
+            String url = baseUrl + '/apex/TydelikeAC';
+            return new Pagereference(url);
+        } catch (Exception e) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+        }
+    	return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TydelikeAccController.cls-meta.xml b/scr/classes/TydelikeAccController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TydelikeAccController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TydelikeAccControllerTest.cls b/scr/classes/TydelikeAccControllerTest.cls
new file mode 100644
index 0000000..12d4a7c
--- /dev/null
+++ b/scr/classes/TydelikeAccControllerTest.cls
@@ -0,0 +1,60 @@
+@isTest
+private class TydelikeAccControllerTest {
+    static testMethod void testMethod1() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c();
+            acc1.name = '**';
+            acc1.OwnerId = UserInfo.getUserId();
+            acc1.TyCity__c = '鍖椾含';
+            acc1.OfSkrap__c = false;
+            acc1.TyAddress__c = '11111';
+            acc1.TyPostCode__c = '123456';
+            acc1.AssetBS3D__c = '123456';
+            acc1.AssetBS2D__c = '123456';
+            acc1.OCNServiceStaff__c = UserInfo.getUserId();
+            acc1.AssetBS1D__c = '123456';
+            acc1.ManagementCode_Ext__c = '123456';
+            acc1.Sub_UseD__c = 'LED';
+            acc1.AssetBS4D__c = '123456';
+            acc1.EnglishNameD__c = '123456';
+            acc1.DepartmentNameD__c = '123456';
+            acc1.FacilityNameD__c = '123456';
+            acc1.IndustryCD__c = 'Education';
+            acc1.MarketVerticalsD__c = 'Education';
+            acc1.CancelReasonD__c = '123456';
+            acc1.ExportRegulatedCustomer__c = true;
+            acc1.Province__c = '鍖椾含';
+            acc1.Whether_OEM__c = true;
+            acc1.GlobalAccountName__c = '123456';
+            acc1.NationalEnterpriseUser__c = true;
+            acc1.DivisionName_D__c = '123456';
+            acc1.UseD__c = '(Education)Education';
+            acc1.UserType__c = 'OEM瀹㈡埛';
+            acc1.WebsiteD__c = 'http://1';
+            acc1.KeyAccount__c = 'Large Account';
+            acc1.ProductSegment__c = 'BS';
+            acc1.FaxD__c = '123456';
+            acc1.Remark__c = '123456';
+            acc1.DealerSelectOwner__c = UserInfo.getUserId();
+            acc1.PhoneD__c = '15555555555';
+        insert acc1;
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+        	tycon1.name = '*';
+        	tycon1.OfSkrap__c = false;
+        	tycon1.TydelikeAccount__c = acc1.Id;
+        	tycon1.TyAddress__c = '11111';
+        	tycon1.TyFaxD__c = '1111';
+        	tycon1.TyPhoneD__c = '15555555555';
+        	tycon1.TyPostcode__c = '111111';
+            tycon1.EnglishAddress__c = '111111';
+            tycon1.ContactEnglishName__c = '111111';
+        insert tycon1;
+        System.debug(tycon1);
+
+        PageReference page = new PageReference('/apex/TydelikeAcc?tyacId=' + acc1.Id + '&tycoId=' + tycon1.Id);
+        System.Test.setCurrentPage(page);
+        TydelikeAccController controller = new TydelikeAccController();
+        controller.init();
+        controller.save();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TydelikeAccControllerTest.cls-meta.xml b/scr/classes/TydelikeAccControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TydelikeAccControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TydelikeConController.cls b/scr/classes/TydelikeConController.cls
new file mode 100644
index 0000000..7500bea
--- /dev/null
+++ b/scr/classes/TydelikeConController.cls
@@ -0,0 +1,101 @@
+public with sharing class TydelikeConController {
+	public Account acc {get;set;}
+	public Contact con {get;set;}
+	public TydelikeContact__c tyc {get;set;}
+	public TydelikeAccount__c tya {get;set;}
+	public String accName { get; set; }
+    public String tycoId { get; set; }
+    public String tyacId { get; set; }
+
+	public String baseUrl { get; set; }
+    public String rtUrl { get; set; }
+
+    public TydelikeConController() {
+        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
+        String path = URL.getCurrentRequestUrl().getPath();
+        if (path.indexOf('/apex') > 0) {
+            baseUrl += path.substring(0,path.indexOf('/apex'));
+        } else if (path.indexOf('production/') > 0) {
+            baseUrl += '/production';
+        }
+        rtUrl = System.currentPageReference().getParameters().get('retURL');
+        if (rtUrl == null || rtUrl == 'null') {
+            rtUrl = '';
+        }
+    }
+    //椤甸潰鍒濆鍖�
+    public PageReference init() {
+        accName = System.currentPageReference().getParameters().get('accName');
+        tycoId = System.currentPageReference().getParameters().get('tycoId');
+        tyacId = System.currentPageReference().getParameters().get('tyacId');
+        //浼犳潵鐨勫鎴风殑鍚嶅瓧鏌ヨ
+        List<Account> accList = [select Id,Name,ProductSegment__c from Account where Name =: accName];
+        if (accList.size() > 0) {
+            acc = accList[0];
+        }
+        //浼犳潵鐨勮仈绯讳汉鐨刬d鏌ヨ
+        List<TydelikeContact__c> tycoList = [select 
+        Id,Name,TyAddress__c,TyFaxD__c,TyPhoneD__c,TyPostcode__c,EnglishAddress__c,ContactEnglishName__c 
+        from TydelikeContact__c 
+        where Id =: tycoId];
+        if (tycoList.size() > 0) {
+            tyc = tycoList[0];
+        }
+
+        //鍒濆鍖栭〉闈㈢殑鏄剧ず
+        con = new Contact();
+        con.AccountId = acc.Id;
+        con.LastName = tyc.Name;
+        con.Address1D__c = tyc.TyAddress__c;
+        con.FaxD__c = tyc.TyFaxD__c;
+        con.StatusD__c = '鑽夋涓�';
+        con.MobilePhoneD__c = tyc.TyPhoneD__c;
+        con.PostcodeD__c = tyc.TyPostcode__c;
+        con.EnglishAddress__c = tyc.EnglishAddress__c;
+        con.ContactEnglishName__c = tyc.ContactEnglishName__c;
+        if (acc.ProductSegment__c == 'BS') {
+            con.ProductSegmentBS__c = true;
+        }else if(acc.ProductSegment__c == 'IE'){
+        	con.ProductSegmentIE__c = true;
+        }else if(acc.ProductSegment__c == 'NDT'){
+        	con.ProductSegmentNDT__c = true;
+        }else if(acc.ProductSegment__c == 'ANI'){
+        	con.ProductSegmentANI__c = true;
+        }else if(acc.ProductSegment__c == 'RVI'){
+        	con.ProductSegmentRVI__c = true;
+        }
+
+        return null;
+    }
+
+    public PageReference save() {
+    	tycoId = System.currentPageReference().getParameters().get('tycoId');
+        tyacId = System.currentPageReference().getParameters().get('tyacId');
+    	List<TydelikeContact__c> tyconList = new List<TydelikeContact__c>();
+    	TydelikeContact__c tycontact = new TydelikeContact__c();
+    	tycontact.Id = tycoId;
+    	tycontact.OfSkrap__c = true;
+        tycontact.Ofomsa__c = true;
+    	tyconList.add(tycontact);
+
+        List<TydelikeAccount__c> tyacList = new List<TydelikeAccount__c>();
+        TydelikeAccount__c tyaccount = new TydelikeAccount__c();
+        tyaccount.Id = tyacId;
+        tyaccount.Ofomsa__c = true;
+        tyacList.add(tyaccount);
+        //涓存椂瀹㈡埛涓庤仈绯讳汉鐨凮fSkrap__c,Ofomsa__c鍙弬涓庤皟鏌ャ��
+    	Savepoint sp = Database.setSavepoint();
+        try {
+        	update tyconList;
+            update tyacList;
+            insert con;
+            
+            String url = baseUrl + '/apex/TydelikeAC';
+            return new Pagereference(url);
+        } catch (Exception e) {
+            Database.rollback(sp);
+            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
+        }
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TydelikeConController.cls-meta.xml b/scr/classes/TydelikeConController.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TydelikeConController.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/TydelikeConControllerTest.cls b/scr/classes/TydelikeConControllerTest.cls
new file mode 100644
index 0000000..8691ac1
--- /dev/null
+++ b/scr/classes/TydelikeConControllerTest.cls
@@ -0,0 +1,236 @@
+@isTest
+private class TydelikeConControllerTest {
+    static testMethod void testMethod1() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c();
+            acc1.name = '**';
+            acc1.OwnerId = UserInfo.getUserId();
+            acc1.TyCity__c = '鍖椾含';
+            acc1.OfSkrap__c = false;
+            acc1.TyAddress__c = '11111';
+            acc1.TyPostCode__c = '123456';
+        insert acc1;
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+        	tycon1.name = '*';
+        	tycon1.OfSkrap__c = false;
+        	tycon1.TydelikeAccount__c = acc1.Id;
+        	tycon1.TyAddress__c = '11111';
+        	tycon1.TyFaxD__c = '1111';
+        	tycon1.TyPhoneD__c = '15555555555';
+        	tycon1.TyPostcode__c = '111111';
+            tycon1.EnglishAddress__c = '111111';
+            tycon1.ContactEnglishName__c = '111111';
+        insert tycon1;
+        System.debug(tycon1);
+
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS'
+        );
+        insert buyer;
+        System.debug(buyer);
+        /*Account accBS = new Account(
+            Name = '12343',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName_D__c = '010',
+            FacilityNameD__c = '011',
+            DepartmentNameD__c = '001',
+            Province__c = '鍖椾含',
+            CityD__c = 'beijing',
+            Address1D__c = '7hao',
+            UserType__c = 'OEM瀹㈡埛',
+            MarketVerticalsD__c = 'Education',
+            IndustryBD__c = 'Education',
+            UseD__c = 'Education',
+
+            DivisionName__c = '010',
+            FacilityName__c = '011',
+            DepartmentName__c = '001',
+            City__c = 'beijing',
+            Address1__c = '7hao',
+            MarketVerticals__c = 'Education',
+            IndustryB__c = 'Education',
+            Use__c = 'Education',
+            ProductSegment__c = 'BS'
+        );
+        insert accBS;
+        System.debug(accBS);*/
+
+        PageReference page = new PageReference('/apex/TydelikeCon?accName=' + buyer.Name + '&tyacId=' + acc1.Id + '&tycoId=' + tycon1.Id);
+        System.Test.setCurrentPage(page);
+        TydelikeConController controller = new TydelikeConController();
+        controller.init();
+        controller.save();
+    }
+
+     static testMethod void testMethod2() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c();
+            acc1.name = '**';
+            acc1.OwnerId = UserInfo.getUserId();
+            acc1.TyCity__c = '鍖椾含';
+            acc1.OfSkrap__c = false;
+            acc1.TyAddress__c = '11111';
+            acc1.TyPostCode__c = '123456';
+        insert acc1;
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+            tycon1.name = '*';
+            tycon1.OfSkrap__c = false;
+            tycon1.TydelikeAccount__c = acc1.Id;
+            tycon1.TyAddress__c = '11111';
+            tycon1.TyFaxD__c = '1111';
+            tycon1.TyPhoneD__c = '15555555555';
+            tycon1.TyPostcode__c = '111111';
+        insert tycon1;
+        System.debug(tycon1);
+
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'IE'
+        );
+        insert buyer;
+        System.debug(buyer);
+
+        PageReference page = new PageReference('/apex/TydelikeCon?accName=' + buyer.Name + '&tyacId=' + acc1.Id + '&tycoId=' + tycon1.Id);
+        System.Test.setCurrentPage(page);
+        TydelikeConController controller = new TydelikeConController();
+        controller.init();
+        controller.save();
+    }
+
+     static testMethod void testMethod3() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c();
+            acc1.name = '**';
+            acc1.OwnerId = UserInfo.getUserId();
+            acc1.TyCity__c = '鍖椾含';
+            acc1.OfSkrap__c = false;
+            acc1.TyAddress__c = '11111';
+            acc1.TyPostCode__c = '123456';
+        insert acc1;
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+            tycon1.name = '*';
+            tycon1.OfSkrap__c = false;
+            tycon1.TydelikeAccount__c = acc1.Id;
+            tycon1.TyAddress__c = '11111';
+            tycon1.TyFaxD__c = '1111';
+            tycon1.TyPhoneD__c = '15555555555';
+            tycon1.TyPostcode__c = '111111';
+        insert tycon1;
+        System.debug(tycon1);
+
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'NDT'
+        );
+        insert buyer;
+        System.debug(buyer);
+
+        PageReference page = new PageReference('/apex/TydelikeCon?accName=' + buyer.Name + '&tyacId=' + acc1.Id + '&tycoId=' + tycon1.Id);
+        System.Test.setCurrentPage(page);
+        TydelikeConController controller = new TydelikeConController();
+        controller.init();
+        controller.save();
+    }
+
+     static testMethod void testMethod4() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c();
+            acc1.name = '**';
+            acc1.OwnerId = UserInfo.getUserId();
+            acc1.TyCity__c = '鍖椾含';
+            acc1.OfSkrap__c = false;
+            acc1.TyAddress__c = '11111';
+            acc1.TyPostCode__c = '123456';
+        insert acc1;
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+            tycon1.name = '*';
+            tycon1.OfSkrap__c = false;
+            tycon1.TydelikeAccount__c = acc1.Id;
+            tycon1.TyAddress__c = '11111';
+            tycon1.TyFaxD__c = '1111';
+            tycon1.TyPhoneD__c = '15555555555';
+            tycon1.TyPostcode__c = '111111';
+        insert tycon1;
+        System.debug(tycon1);
+
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'ANI'
+        );
+        insert buyer;
+        System.debug(buyer);
+
+        PageReference page = new PageReference('/apex/TydelikeCon?accName=' + buyer.Name + '&tyacId=' + acc1.Id + '&tycoId=' + tycon1.Id);
+        System.Test.setCurrentPage(page);
+        TydelikeConController controller = new TydelikeConController();
+        controller.init();
+        controller.save();
+    }
+
+     static testMethod void testMethod5() {
+        TydelikeAccount__c acc1 = new TydelikeAccount__c();
+            acc1.name = '**';
+            acc1.OwnerId = UserInfo.getUserId();
+            acc1.TyCity__c = '鍖椾含';
+            acc1.OfSkrap__c = false;
+            acc1.TyAddress__c = '11111';
+            acc1.TyPostCode__c = '123456';
+        insert acc1;
+
+        TydelikeContact__c tycon1 = new TydelikeContact__c();
+            tycon1.name = '*';
+            tycon1.OfSkrap__c = false;
+            tycon1.TydelikeAccount__c = acc1.Id;
+            tycon1.TyAddress__c = '11111';
+            tycon1.TyFaxD__c = '1111';
+            tycon1.TyPhoneD__c = '15555555555';
+            tycon1.TyPostcode__c = '111111';
+        insert tycon1;
+        System.debug(tycon1);
+
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'RVI'
+        );
+        insert buyer;
+        System.debug(buyer);
+
+        PageReference page = new PageReference('/apex/TydelikeCon?accName=' + buyer.Name + '&tyacId=' + acc1.Id + '&tycoId=' + tycon1.Id);
+        System.Test.setCurrentPage(page);
+        TydelikeConController controller = new TydelikeConController();
+        controller.init();
+        controller.save();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/TydelikeConControllerTest.cls-meta.xml b/scr/classes/TydelikeConControllerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/TydelikeConControllerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UpdateTotalCostPriceSchedule.cls b/scr/classes/UpdateTotalCostPriceSchedule.cls
new file mode 100644
index 0000000..c4b6d45
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSchedule.cls
@@ -0,0 +1,15 @@
+/**
+system.schedule('UpdateTotalCostPriceSchedule1','0 5 9-23 * * ? 2015-2035', new UpdateTotalCostPriceSchedule());
+system.schedule('UpdateTotalCostPriceSchedule2','0 20 9-23 * * ? 2015-2035', new UpdateTotalCostPriceSchedule());
+system.schedule('UpdateTotalCostPriceSchedule3','0 35 9-23 * * ? 2015-2035', new UpdateTotalCostPriceSchedule());
+system.schedule('UpdateTotalCostPriceSchedule4','0 50 9-23 * * ? 2015-2035', new UpdateTotalCostPriceSchedule());
+*/
+global class UpdateTotalCostPriceSchedule implements Schedulable {
+ // 姣忎釜灏忔椂鐨�5锛�20锛�35锛�50鍒嗘墽琛岋紝鍗�15鍒嗛挓鎵ц涓�娆�
+    global void execute(SchedulableContext SC) {
+       UpdateTotalCostPriceSetTextBatch u = new UpdateTotalCostPriceSetTextBatch();  
+       UpdateTotalCostPriceSetTextInquiryBatch o = new UpdateTotalCostPriceSetTextInquiryBatch();  
+       Id execBTId = Database.executeBatch(u, 100);  
+        Id execBTId2 = Database.executeBatch(o, 100);               
+        }
+}
\ No newline at end of file
diff --git a/scr/classes/UpdateTotalCostPriceSchedule.cls-meta.xml b/scr/classes/UpdateTotalCostPriceSchedule.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSchedule.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UpdateTotalCostPriceSetTextBatch.cls b/scr/classes/UpdateTotalCostPriceSetTextBatch.cls
new file mode 100644
index 0000000..8bafc3b
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextBatch.cls
@@ -0,0 +1,99 @@
+global class UpdateTotalCostPriceSetTextBatch implements Database.Batchable<sObject> {
+    private List<String> idList = null;
+    global UpdateTotalCostPriceSetTextBatch() {}
+    global UpdateTotalCostPriceSetTextBatch(List<String> temp) {
+        idList = temp;
+    }
+
+    global Database.QueryLocator start(Database.BatchableContext BC) {
+        String query;
+        query = 'select Id,Order.SAP_Order__c,Order.ProductSegment__c,Order.TradeType__c,Order.ApproveStatus__c,Order.SAP_Contract__c,TotalCostPrice__c,TotalCostPrice_Text__c,Order.IsCopy__c from OrderItem';
+        if(idList != null){
+            query = 'select Id,Order.SAP_Order__c,Order.ProductSegment__c,Order.TradeType__c,Order.ApproveStatus__c,Order.SAP_Contract__c,TotalCostPrice__c,TotalCostPrice_Text__c,Order.IsCopy__c from OrderItem where Order.Id =: idList';
+        }
+        return Database.getQueryLocator(query);
+    }
+    
+    
+     WebService static String executeWebSide1(String Orderid){
+        List<OrderItem> updList = new List<OrderItem>();
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'PushNotification';
+        iflog.Is_Error__c = 0;
+        iflog.Log__c = 'UpdateTotalCostPriceSetTextBatch start0\n';
+        iflog.ErrorLog__c = '';
+        insert iflog;
+
+        List<OrderItem> OrderDataList1 = [select Id,Order.SAP_Order__c,Order.ProductSegment__c,Order.TradeType__c,Order.ApproveStatus__c,Order.SAP_Contract__c,TotalCostPrice__c,TotalCostPrice_Text__c,Order.IsCopy__c                                            
+                                        from OrderItem where Order.Id = :Orderid];
+        List<Delivery__c> deliveryList = new List<Delivery__c>();
+        deliveryList = [select id from Delivery__c where SSBD_Contract__c = :Orderid and Delivery_Status__c = '鍏ㄩ儴鍙戣揣'];
+        if (OrderDataList1.size() == 0){ 
+        return '娌℃湁绗﹀悎鏉′欢鐨勫悎鍚屾暟鎹�';  
+        } else {
+                 for (OrderItem orderData:orderDataList1){
+            //鐜嬮箯浼熸柊鍔犳潯浠惰嚜鍔ㄦ洿鏂版潯浠舵坊鍔犲埌鎵嬪姩鏇存柊
+            //        (orderData.order.ProductSegment__c == 'BS' && orderData.order.SAP_Order__c == null && orderData.order.TradeType__c == '澶栬锤') ||
+            //        (orderData.order.ProductSegment__c != 'BS'  && orderData.order.TradeType__c == '澶栬锤' && orderData.order.ApproveStatus__c !=  'OrderPass') ||
+            //        (orderData.order.TradeType__c == '鍐呰锤' && orderData.order.SAP_Contract__c == null) ||
+            //        (orderData.order.IsCopy__c == true)
+            if (orderData.TotalCostPrice__c != orderData.TotalCostPrice_Text__c &&  deliveryList.size() == 0 && 
+                (
+                    (orderData.order.ProductSegment__c == 'BS' && orderData.order.SAP_Order__c == null && orderData.order.TradeType__c == '澶栬锤') ||
+                    (orderData.order.ProductSegment__c != 'BS'  && orderData.order.TradeType__c == '澶栬锤' && orderData.order.ApproveStatus__c !=  'OrderPass') ||
+                    (orderData.order.TradeType__c == '鍐呰锤' && orderData.order.SAP_Contract__c == null) ||
+                    (orderData.order.IsCopy__c == true)
+                  )
+                  /*(
+                    (orderData.order.ProductSegment__c == 'BS' && orderData.order.SAP_Order__c == null && orderData.order.TradeType__c == '澶栬锤') ||
+                    (( orderData.order.ProductSegment__c == 'IE' || orderData.order.ProductSegment__c == 'RVI') && orderData.order.TradeType__c == '澶栬锤' && orderData.order.ApproveStatus__c !=  'OrderPass') ||
+                    (( orderData.order.ProductSegment__c == 'BS' || orderData.order.ProductSegment__c == 'IE' || orderData.order.ProductSegment__c == 'RVI') && orderData.order.TradeType__c == '鍐呰锤' && orderData.order.SAP_Contract__c == null) ||
+                    (( orderData.order.ProductSegment__c == 'BS' || orderData.order.ProductSegment__c == 'IE' || orderData.order.ProductSegment__c == 'RVI') && orderData.order.IsCopy__c == true)
+                  )*/
+            ) {
+                orderData.TotalCostPrice_Text__c = (Decimal)orderData.TotalCostPrice__c;
+                updList.add(orderData);
+            }else{
+                //鐜嬮箯浼熸坊鍔爀lse杩斿洖
+                //return '璇ュ悎鍚屼笉绗﹀悎鏇存柊鏉′欢锛屼笉闇�瑕佹洿鏂�';
+            }
+
+        }
+        if (updList.size() > 0){ 
+            update updList;
+            return '鏇存柊鎴愬姛';
+        }else{
+             return '璇ュ悎鍚屼笉绗﹀悎鏇存柊鏉′欢锛屼笉闇�瑕佹洿鏂�';
+        }
+    }
+    }
+
+    global void execute(Database.BatchableContext BC, List<OrderItem> orderDataList) {
+        List<OrderItem> updList = new List<OrderItem>();
+        for (OrderItem orderData:orderDataList){
+            if (orderData.TotalCostPrice__c != orderData.TotalCostPrice_Text__c &&
+                 /* (
+                    (orderData.order.ProductSegment__c == 'BS' && orderData.order.SAP_Order__c == null && orderData.order.TradeType__c == '澶栬锤') ||
+                    (( orderData.order.ProductSegment__c == 'IE' || orderData.order.ProductSegment__c == 'RVI') && orderData.order.TradeType__c == '澶栬锤' && orderData.order.ApproveStatus__c !=  'OrderPass') ||
+                    (( orderData.order.ProductSegment__c == 'BS' || orderData.order.ProductSegment__c == 'IE' || orderData.order.ProductSegment__c == 'RVI') && orderData.order.TradeType__c == '鍐呰锤' && orderData.order.SAP_Contract__c == null) ||
+                    (( orderData.order.ProductSegment__c == 'BS' || orderData.order.ProductSegment__c == 'IE' || orderData.order.ProductSegment__c == 'RVI') && orderData.order.IsCopy__c == true)
+                  )*/
+                   (
+                    (orderData.order.ProductSegment__c == 'BS' && orderData.order.SAP_Order__c == null && orderData.order.TradeType__c == '澶栬锤') ||
+                    (orderData.order.ProductSegment__c != 'BS'  && orderData.order.TradeType__c == '澶栬锤' && orderData.order.ApproveStatus__c !=  'OrderPass') ||
+                    (orderData.order.TradeType__c == '鍐呰锤' && orderData.order.SAP_Contract__c == null) ||
+                    (orderData.order.IsCopy__c == true)
+                  )
+            ) {
+                orderData.TotalCostPrice_Text__c = (Decimal)orderData.TotalCostPrice__c;
+                updList.add(orderData);
+            }
+
+        }
+        if (updList.size() > 0) update updList;
+    }
+
+    global void finish(Database.BatchableContext BC) {
+        // 浠婂洖銇倓銈嬨亾銇ㄣ仾銇勩仹銇�
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/UpdateTotalCostPriceSetTextBatch.cls-meta.xml b/scr/classes/UpdateTotalCostPriceSetTextBatch.cls-meta.xml
new file mode 100644
index 0000000..cbddff8
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls b/scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls
new file mode 100644
index 0000000..9c22ba6
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls
@@ -0,0 +1,113 @@
+@isTest
+private class UpdateTotalCostPriceSetTextBatchTest {
+    static testMethod void testMethod1() {
+         List<RecordType> rectBS = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account accBS = new Account(
+            Name = '*',
+            RecordTypeId = rectBS[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer BS',
+            FacilityName__c='abc',
+            PostCode__c='000000'
+        );
+        insert accBS;
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accBS.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+
+        Id pricebookId = Test.getStandardPricebookId();
+
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'BS',
+            ProductSegment__c = 'BS',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.ProductCode = 'product1';
+        product1.Product_ECCode__c = 'product1';
+        product1.IsActive = true;
+        insert product1;
+
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true
+        );
+        insert standardPrice1;
+
+        PricebookEntry entry1 = new PricebookEntry(Pricebook2Id = pricebook.Id, Product2Id = product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        insert entry1;
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accBS.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'BS',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Machine_Parts__c = 'Machine',
+            InquiryResult__c = '112233'
+        );
+        insert opp;
+
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accBS.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            IE_SP5_D__c = true,
+            SpecialDeliveryAccount_D__c = accBS.Id,
+            SpecialDeliveryContact2_D__c = con.Id
+        );
+        insert odr;
+
+        OrderItem oi1 = new OrderItem(
+            OrderId = odr.Id,
+            PriceBookEntryId = entry1.Id,
+            Quantity = 1,
+            UnitPrice = 10
+        );
+        insert oi1;
+        List<String> ids = new List<String>();
+        ids.add(odr.Id);
+        Database.executeBatch(new UpdateTotalCostPriceSetTextBatch(), 20);  
+        Database.executeBatch(new UpdateTotalCostPriceSetTextBatch(ids), 20);	
+        UpdateTotalCostPriceSetTextBatch.executeWebSide1(odr.Id);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls-meta.xml b/scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls b/scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls
new file mode 100644
index 0000000..aa3acb9
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls
@@ -0,0 +1,86 @@
+global class UpdateTotalCostPriceSetTextInquiryBatch implements Database.Batchable<sObject> {
+    private List<String> idList = null;
+    global UpdateTotalCostPriceSetTextInquiryBatch() {}
+    global UpdateTotalCostPriceSetTextInquiryBatch(List<String> temp) {
+      idList = temp;
+    }
+
+    global Database.QueryLocator start(Database.BatchableContext BC) {
+       String query;
+       //鐜嬮箯浼熸柊鍔犳潯浠�
+       //'Opportunity.StageName != \'Closed Won\' and Opportunity.StageName != \'Closed Lost\' and Opportunity.StageName != \'Closed Cancel\' and '+
+       //'Opportunity.Model_product_cnt__c != 0 and Opportunity.ProductCount__c != 0 and Opportunity.OppBatchUpdate__c = true'
+       query = 'select TotalCostPrice__c,TotalCostPrice_Text__c,Opportunity.Model_product_cnt__c,Opportunity.ProductCount__c,Opportunity.OppBatchUpdate__c from OpportunityLineItem where '+
+       'Opportunity.StageName != \'Closed Won\' and Opportunity.StageName != \'Closed Lost\' and Opportunity.StageName != \'Closed Cancel\' '
+       /*+'and Opportunity.Model_product_cnt__c != 0 and Opportunity.ProductCount__c != 0 and Opportunity.OppBatchUpdate__c = true'*/;
+       if(idList != null){
+          query = 'select TotalCostPrice__c,TotalCostPrice_Text__c,Opportunity.Model_product_cnt__c,Opportunity.ProductCount__c,Opportunity.OppBatchUpdate__c from OpportunityLineItem where '+
+          'Opportunity.StageName != \'Closed Won\' and Opportunity.StageName != \'Closed Lost\' and Opportunity.StageName != \'Closed Cancel\' and Opportunity.Id=:idList';
+       }
+        return Database.getQueryLocator(query);
+        
+    }
+
+    WebService static String executeWebSide(String Opportunityid){
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'PushNotification';
+        iflog.Is_Error__c = 0;
+        iflog.Log__c = 'UpdateTotalCostPriceSetTextInquiryBatch start0\n';
+        iflog.ErrorLog__c = '';
+        insert iflog;
+        List<OpportunityLineItem> updateList = new List<OpportunityLineItem>();
+        List<OpportunityLineItem> OpportunityDataList1 = [select
+                                                Opportunity.StageName,
+                                                TotalCostPrice__c,
+                                                TotalCostPrice_Text__c,
+                                                Opportunity.Model_product_cnt__c,
+                                                Opportunity.ProductCount__c,
+                                                Opportunity.OppBatchUpdate__c                                              
+                                        from OpportunityLineItem where Opportunity.Id = :Opportunityid and Opportunity.StageName <> 'Closed Won' and Opportunity.StageName <> 'Closed Lost' and Opportunity.StageName <> 'Closed Cancel' 
+                                        /*and Opportunity.Model_product_cnt__c != 0 and Opportunity.ProductCount__c != 0 and Opportunity.OppBatchUpdate__c = true*/];
+        if (OpportunityDataList1.size() == 0){ 
+            return '娌℃湁绗﹀悎鏉′欢鐨勮浠锋暟鎹�';  
+        } else {
+            for (OpportunityLineItem OpportunityData:OpportunityDataList1){
+                //鐜嬮箯浼� 娣诲姞if绛涢�夋潯浠�  && OpportunityData.Opportunity.Model_product_cnt__c != 0 && OpportunityData.Opportunity.ProductCount__c != 0 &&
+                //OpportunityData.Opportunity.OppBatchUpdate__c == true   
+                if (OpportunityData.TotalCostPrice__c != OpportunityData.TotalCostPrice_Text__c && 
+                  OpportunityData.Opportunity.Model_product_cnt__c == 0 && OpportunityData.Opportunity.ProductCount__c != 0 &&
+                  OpportunityData.Opportunity.OppBatchUpdate__c == true){ 
+                      OpportunityData.TotalCostPrice_Text__c = (Decimal)OpportunityData.TotalCostPrice__c;
+                      updateList.add(OpportunityData);
+                }
+            }
+            if(updateList.size() >0){
+                update updateList;
+                return '鏇存柊鎴愬姛';
+            }else{
+                //鐜嬮箯浼熸柊鍔爀lse杩斿洖
+                return '璇ヨ浠蜂笉绗﹀悎鏇存柊鏉′欢锛屼笉闇�瑕佹洿鏂般��';
+            }
+        }
+    }
+    
+    global void execute(Database.BatchableContext BC, List<OpportunityLineItem> OpportunityDataList) {
+      //鐜嬮箯浼� 娣诲姞if绛涢�夋潯浠�
+      //&& OpportunityData.Opportunity.Model_product_cnt__c != 0 && OpportunityData.Opportunity.ProductCount__c != 0 &&
+      // OpportunityData.Opportunity.OppBatchUpdate__c == true
+      List<OpportunityLineItem> itemList = new List<OpportunityLineItem>();
+               for (OpportunityLineItem OpportunityData:OpportunityDataList){   
+                      if (OpportunityData.TotalCostPrice__c != OpportunityData.TotalCostPrice_Text__c  && 
+                        OpportunityData.Opportunity.Model_product_cnt__c == 0 && OpportunityData.Opportunity.ProductCount__c != 0 &&
+                        OpportunityData.Opportunity.OppBatchUpdate__c == true) 
+                      { 
+                        OpportunityData.TotalCostPrice_Text__c = (Decimal)OpportunityData.TotalCostPrice__c;
+                        itemList.add(OpportunityData);
+            }
+
+        }
+        if(itemList.size()>0) update itemList;
+       
+       }   
+
+    global void finish(Database.BatchableContext BC) {
+        // 浠婂洖銇倓銈嬨亾銇ㄣ仾銇勩仹銇�
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls-meta.xml b/scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextInquiryBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls b/scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls
new file mode 100644
index 0000000..2c197b0
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls
@@ -0,0 +1,150 @@
+@isTest
+private class UpdateTotalCostPriceSetTextInquiryTest {
+    static testMethod void testMethod1() {
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        List<RecordType> rectForeignCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'ForeignCompany'];
+        Id pricebookId = Test.getStandardPricebookId();
+        
+        /*PriceBook2 pricebook1 = ControllerUtil.getStandardPricebook();
+        Id pricebookId = pricebook1.id;*/
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+        
+        /*Pricebook2 pricebook =  [select Id from PriceBook2 where ProductSegment__c = 'IE' and
+         TradeType__c = 'Taxation' and SalesChannel__c = 'direct' and MachineParts__c = 'Machine' and  isActive = true limit 1];
+*/
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        product1.IsActive = true;
+        product1.ProductModels__c = false;
+
+        
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        product2.IsActive = true;
+        product2.ProductModels__c = true;
+        
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        product3.IsActive = true;
+        
+        insert new Product2[] {product1,product2,product3};
+        
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+
+        );
+        
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            CurrencyIsoCode = 'CNY',
+            IsActive = true
+        );
+        
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+
+        
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456'
+        );
+        insert accIE; 
+
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity(
+            Name = 'test opp',
+            AccountId = accIE.Id,
+            RecordTypeId = rectOpp[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            StageName = 'Phase3',
+            CurrencyIsoCode = 'CNY',
+            ProductSegment__c = 'IE',
+            CloseDate = Date.today(),
+            NewInquiryDate__c = Date.today().addDays(-2),
+            ExpectedOrderDate__c = Date.today().addDays(2),
+            SalesChannel__c = 'direct',
+            TradeType__c = 'Taxation',
+            Machine_Parts__c = 'Machine',
+            InquiryResult__c = '112233'
+            
+        );
+        insert opp;
+
+        OpportunityLineItem oli = new OpportunityLineItem();
+        oli.OpportunityId = opp.Id;
+        //oli.Product2 = prd1;
+        oli.Quantity = 2;
+        oli.UnitPrice = 111;
+        oli.Description = 'test';
+        oli.PricebookEntryId = entry1.Id;
+        insert oli;
+
+        OpportunityLineItem oli2 = new OpportunityLineItem();
+        oli2.OpportunityId = opp.Id;
+        //oli2.Product2 = prd2;
+        oli2.Quantity = 2;
+        oli2.UnitPrice = 111;
+        oli2.Description = 'test';
+        oli2.PricebookEntryId = entry1.Id;
+        insert oli2;
+
+        opp.InquiryResult__c = '112222';
+
+        update opp;
+
+        /*System.assertEquals(0, opp.Model_product_cnt__c);
+        System.assertEquals(0, opp.ProductCount__c);
+        System.assertEquals(true, opp.OppBatchUpdate__c);*/
+        List<String> ids = new List<String>();
+        ids.add(opp.Id);
+        Database.executeBatch(new UpdateTotalCostPriceSetTextInquiryBatch(), 20);
+        Database.executeBatch(new UpdateTotalCostPriceSetTextInquiryBatch(ids), 20);	
+        UpdateTotalCostPriceSetTextInquiryBatch.executeWebSide(opp.Id);
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls-meta.xml b/scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/UpdateTotalCostPriceSetTextInquiryTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UserFaultInfoHandler.cls b/scr/classes/UserFaultInfoHandler.cls
new file mode 100644
index 0000000..89b248d
--- /dev/null
+++ b/scr/classes/UserFaultInfoHandler.cls
@@ -0,0 +1,281 @@
+public without sharing class UserFaultInfoHandler {
+
+    public static void UserFaultInfoWorkingHoursAssignment(List<User_FaultInfo__c> newList, Map<Id, User_FaultInfo__c> newMap, List<User_FaultInfo__c> oldList, Map<Id, User_FaultInfo__c> oldMap, String type) {
+        // 鑾峰彇鐢ㄦ埛/鏁呴殰淇℃伅涓嬬殑涓氬姟娲诲姩
+        List<String> selectUserFaultInfoIdList = new List<String>();
+        for (User_FaultInfo__c uf : newList) {
+            selectUserFaultInfoIdList.add(uf.Id);
+        }
+
+        // 鏌ユ壘鐢ㄦ埛鏁呴殰淇℃伅涓嬫墍鏈夌殑涓氬姟娲诲姩
+        List<BusinessActivity__c> businessActivityList = TSRepairUtil.GetBusinessActivityList(null, selectUserFaultInfoIdList, null, null, null, '');
+        // 鐢ㄦ埛/鏁呴殰淇℃伅 鏍规嵁 瀹℃壒鎰忚 绫诲瀷涓� 宸ユ椂缁勬垚鐨凪ap
+        Map<String, Decimal> OpinionMap = new Map<String, Decimal>();
+        // 鐢ㄦ埛/鏁呴殰淇℃伅 Id涓庡伐鏃剁粍鎴愮殑Map
+        Map<String, Map<String, Decimal>> WorkingHourMap = new Map<String, Map<String, Decimal>>();
+        if (businessActivityList != null && businessActivityList.size() > 0) {
+
+            for (BusinessActivity__c getba : businessActivityList) {
+
+                String ufId =  getba.User_FaultInfo__c;
+                String opinion = getba.BusinessAApprovalOpinion__c;
+                Decimal workingHours = 0;
+                Map<String, Decimal> ufOpinionMap = new Map<String, Decimal>();
+
+                if (WorkingHourMap.containsKey(ufId)) {
+
+                    ufOpinionMap = WorkingHourMap.get(ufId);
+
+                    if (ufOpinionMap.containsKey(opinion)) {
+
+                        workingHours = ufOpinionMap.get(opinion);
+                        workingHours += getba.workingHours__c;
+                        ufOpinionMap.put(opinion, workingHours);
+                    } else {
+
+                        workingHours += getba.workingHours__c;
+                        ufOpinionMap.put(opinion, workingHours);
+                    }
+                } else {
+
+                    workingHours += getba.workingHours__c;
+                    ufOpinionMap.put(opinion, workingHours);
+                }
+                WorkingHourMap.put(ufId, ufOpinionMap);
+
+            }
+            List<User_FaultInfo__c> updateUserFaultInfoList = new List<User_FaultInfo__c>();
+
+            for (User_FaultInfo__c uf : newList) {
+
+                for (String ufId : WorkingHourMap.keySet() ) {
+
+                    if (uf.Id.equals(ufId)) {
+
+                        Map<String, Decimal> ufOpinionMap = WorkingHourMap.get(ufId);
+                        uf.UserFaultInfoWorkingHours__c = 0;
+                        uf.UserFaultInfoUnconfirmedTime__c = 0;
+
+                        for (String opinion : ufOpinionMap.keySet()) {
+                            if ('鍚屾剰'.equals(opinion)) {
+                                uf.UserFaultInfoWorkingHours__c = ufOpinionMap.get(opinion);
+                            } else {
+                                uf.UserFaultInfoUnconfirmedTime__c = ufOpinionMap.get(opinion);
+                            }
+                        }
+                    }
+
+                }
+
+                if ('insert'.equals(type)) {
+                    updateUserFaultInfoList.add(uf);
+                }
+            }
+
+            if (updateUserFaultInfoList.size() > 0) {
+                update updateUserFaultInfoList;
+            }
+
+
+        }
+
+    }
+
+    public static void BeforeSendEmail(List<User_FaultInfo__c> newList, Map<Id, User_FaultInfo__c> newMap, List<User_FaultInfo__c> oldList, Map<Id, User_FaultInfo__c> oldMap) {
+        for (User_FaultInfo__c newUf : newList) {
+            newUf.IsSendEmail__c = true;
+        }
+
+    }
+
+    // Case 涓� ASSIGNED TO 鍙樻洿 鍙戦�侀偖浠�
+    public static void ASSIGNEDTOChange(List<User_FaultInfo__c> newList, Map<Id, User_FaultInfo__c> newMap, List<User_FaultInfo__c> oldList, Map<Id, User_FaultInfo__c> oldMap) {
+        List<User_FaultInfo__Share> insertShareList = new List<User_FaultInfo__Share>();
+        List<String> deleteShareList = new List<String>();
+
+        for (User_FaultInfo__c newUf : newList) {
+
+            Boolean beforUpdate = false;
+            Boolean isSendEmail = false;
+
+            Boolean afterInsert = false;
+            Boolean changeASSIGNED_TO = false;
+            Boolean changeCONTACT = false;
+
+            if (Trigger.isBefore && Trigger.isUpdate) {
+                isSendEmail = true;
+                User_FaultInfo__c oldUf = oldMap.get(newUf.Id);
+                // ASSIGNED TO 鍙樻洿鏃跺彂閫侀偖浠�
+                if (String.isNotBlank(newUf.ASSIGNED_TO__c) && oldUf.ASSIGNED_TO__c != newUf.ASSIGNED_TO__c) {
+                    //鍙樻洿鏃跺彂閫侀偖浠�
+                    beforUpdate = true;
+                    changeASSIGNED_TO = true;
+                    insertShareList.add(ShareToUser(newUf.Id, newUf.ASSIGNED_TO__c));
+                    deleteShareList.add(newUf.Id);
+                }
+                // CONTACT 鍙樻洿鏃跺彂閫侀偖浠�
+                if (String.isNotBlank(newUf.CONTACT__c) && oldUf.CONTACT__c != newUf.CONTACT__c) {
+                    beforUpdate = true;
+                    changeCONTACT = true;
+                }
+
+                if (oldUf.INTERNAL_ONLY__c != newUf.INTERNAL_ONLY__c && newUf.INTERNAL_ONLY__c) {
+                    beforUpdate = true;
+                    changeASSIGNED_TO = true;
+                }
+
+                if (oldUf.SEND_TO_CUSTOMER__c != newUf.SEND_TO_CUSTOMER__c && newUf.SEND_TO_CUSTOMER__c) {
+                    beforUpdate = true;
+                    changeCONTACT = true;
+                }
+            } else if (Trigger.isAfter && Trigger.isInsert) {
+                if (String.isNotBlank(newUf.ASSIGNED_TO__c)) {
+                    insertShareList.add(ShareToUser(newUf.Id, newUf.ASSIGNED_TO__c));
+                    //鏂板鏃跺彂閫侀偖浠�
+                    afterInsert = true;
+
+                }
+            }
+
+
+            String userId = '';
+            String contactId = '';
+            String subjectStr = '';
+            String messageStr = newUf.Interactions__c  == null ? '' : newUf.Interactions__c + '\n';
+            messageStr += 'Case Details Link:\n';
+            messageStr += System.Label.EnvironmentLink + newUf.Id;
+
+            if (newUf.INTERNAL_ONLY__c || changeASSIGNED_TO) {
+                userId = newUf.ASSIGNED_TO__c;
+            }
+
+            if (newUf.SEND_TO_CUSTOMER__c || changeCONTACT) {
+                contactId =  newUf.CONTACT__c;
+            }
+            if (newUf.Interactions__c != null) {
+
+                if (afterInsert) {
+
+                } else {
+                    newUf.interactionsHistory__c =  interactionsHistory(newUf);
+                    newUf.Interactions__c = null;
+                    beforUpdate = true;
+                    if (newUf.IsSendEmail__c) {
+                        beforUpdate = false;
+                        newUf.IsSendEmail__c = false;
+                    }
+
+                }
+            } else {
+                if (isSendEmail) {
+                    if (newUf.IsSendEmail__c) {
+                        newUf.IsSendEmail__c = false;
+                    }
+                }
+
+            }
+            if (beforUpdate) {
+                subjectStr = 'You have connected a new case, please follow up in time.';
+                SendEmail(userId, contactId, newUf.Id, subjectStr, messageStr, 'update');
+
+            }
+            if (afterInsert) {
+                subjectStr = 'A case has been created, please follow up in time.';
+                SendEmail(userId, contactId , newUf.Id, subjectStr, messageStr, 'insert');
+            }
+        }
+        // 鍒犻櫎鏁版嵁鍏变韩
+        if (deleteShareList.size() > 0) {
+            String rowCause = Schema.User_FaultInfo__Share.RowCause.shareToUser__c;
+            List<User_FaultInfo__Share> deleteList = [SELECT Id FROM User_FaultInfo__Share WHERE RowCause = :rowCause AND ParentId IN :deleteShareList];
+            if (deleteList.size() > 0) {
+                delete deleteList;
+            }
+        }
+        // 鏂板鏁版嵁鍏变韩
+        if (insertShareList.size() > 0) {
+            insert insertShareList;
+        }
+    }
+
+    public static void SendEmail(String userId, String contactId, String ufId, String subjectStr, String messageStr, String type) {
+        User_FaultInfo__c getCase = [ SELECT Id, Name, NUMBER__c, SUBJECT__c, COMPANY__r.Name FROM User_FaultInfo__c WHERE Id = :ufId];
+        String caseName =  getCase.Name;
+        // 淇濆瓨涔嬪悗瑕佹嫾鎺� Case 鐨凬ame
+        if ('insert'.equals(type)) {
+            caseName = getCase.NUMBER__c + '-' + getCase.SUBJECT__c + '-' + getCase.COMPANY__r.Name;
+            if (caseName.length() > 80) {
+                caseName = caseName.substring(0, 80);
+            }
+
+        }
+
+        List<String> toAddresses = new List<String>();
+        if (String.isNotBlank(userId)) {
+            User user = [select Name, Email from User where id = :userId limit 1];
+            if (user != null && String.isNotBlank(user.Email)) {
+                toAddresses.add(user.Email);
+            }
+        }
+
+        if (String.isNotBlank(contactId)) {
+            List<Contact> contactList = [SELECT Id, Name, AccountId__c, EmailD__c FROM Contact WHERE Id = :contactId limit 1];
+            if (contactList.size() > 0 && String.isNotBlank(contactList[0].EmailD__c)) {
+                toAddresses.add(contactList[0].EmailD__c);
+            }
+        }
+
+        if (toAddresses.size() > 0) {
+
+            String subject = subjectStr + ' ~Case:' + caseName;
+            String message = messageStr;
+            List<String> ccAddresses = new List<String>();
+            Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
+            sendMail.setToAddresses(toAddresses);
+            sendMail.setSubject(subject);
+            sendMail.setPlainTextBody(message);
+            sendMail.setBccSender(false);
+            sendMail.setUseSignature(false);
+            ccAddresses.add(System.label.EmailComeBackListen);
+            ccAddresses.add('Dai_Prectech@olympus.com.cn');
+            // ccAddresses.add('xinhonglu@prec-tech.com');
+            ccAddresses.add('Xin_Prectech@olympus.com.cn');
+
+            sendMail.setCcAddresses(ccAddresses);
+            Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
+        }
+    }
+    /*
+    parentId:鏁版嵁Id
+    userOrGroupId锛氬緟鍒嗕韩鐨勭敤鎴稩d
+    鍒涘缓鏁版嵁鍏变韩
+     */
+    public static User_FaultInfo__Share ShareToUser (String parentId, String userOrGroupId) {
+        String rowCause = Schema.User_FaultInfo__Share.RowCause.shareToUser__c;
+        User_FaultInfo__Share apexShare = new User_FaultInfo__Share(
+            RowCause = rowCause,
+            ParentId = parentId,
+            UserOrGroupId = userOrGroupId,
+            AccessLevel = 'Edit');
+        return apexShare;
+    }
+    public static String interactionsHistory(User_FaultInfo__c uf) {
+        // 閫佷俊鑰�
+        String username = UserInfo.getName();
+        // 鍙戦�佹椂闂�
+        Datetime dt = Datetime.now();
+
+        // 鐜扮暀瑷�
+        String temp = '';
+        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
+        temp += uf.Interactions__c;
+        String oldResponse =  uf.interactionsHistory__c;
+        if (oldResponse != null && oldResponse.trim().length() > 0) {
+            temp += '\n\n' + oldResponse;
+        }
+        // uf.Interactions__c = null;
+        // uf.interactionsHistory__c = temp;
+        return temp;
+    }
+
+}
\ No newline at end of file
diff --git a/scr/classes/UserFaultInfoHandler.cls-meta.xml b/scr/classes/UserFaultInfoHandler.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/UserFaultInfoHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UserFaultInfoHandlerTest.cls b/scr/classes/UserFaultInfoHandlerTest.cls
new file mode 100644
index 0000000..47f897f
--- /dev/null
+++ b/scr/classes/UserFaultInfoHandlerTest.cls
@@ -0,0 +1,143 @@
+@isTest
+private class UserFaultInfoHandlerTest {
+
+    public static TS_Repair__c tsr;
+    public static TS_Repair__c tsr2;
+    public static BusinessActivity__c ba1;
+    public static BusinessActivity__c ba2;
+    public static BusinessActivity__c ba3;
+    public static BusinessActivity__c ba4;
+
+    public static User_FaultInfo__c uf1;
+    public static User_FaultInfo__c uf2;
+    public static User_FaultInfo__c uf3;
+
+    public static FailureAsset__c fa1;
+    public static FailureAsset__c fa2;
+    public static FailureAsset__c fa3;
+    static void basicData() {
+
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        Contact core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        User testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = '00e28000001sZE6',TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+
+        uf1 = new User_FaultInfo__c();
+        // uf1.ASSIGNED_TO__c = UserD().Id;
+        // uf1.Interactions__c = 'TEST01';
+        insert uf1;
+
+        tsr = new TS_Repair__c();
+        tsr.TSReportDate__c = Date.today();
+        insert tsr;    
+        tsr2 = new TS_Repair__c();
+        tsr2.TSReportDate__c = Date.today();
+        insert tsr2;
+        fa1 = new FailureAsset__c();
+        fa1.model__c = 'test1';
+        fa1.FAUserFaultInfo__c = uf1.Id;
+        insert fa1;
+        ba1 = new BusinessActivity__c();
+        ba1.BusinessATS__c = tsr.Id;
+        ba1.workingHours__c = 2;
+        ba1.BusinessAApprovalOpinion__c = '鍚屾剰';
+        ba1.User_FaultInfo__c = uf1.Id;
+        insert ba1;
+        ba4 = new BusinessActivity__c();
+        ba4.BusinessATS__c = tsr.Id;
+        ba4.workingHours__c = 7;
+        ba4.BusinessAApprovalOpinion__c = '';
+        ba4.User_FaultInfo__c = uf1.Id;
+        insert ba4;
+
+        uf2 = new User_FaultInfo__c();
+        insert uf2;
+        fa2 = new FailureAsset__c();
+        fa2.model__c = 'test2';
+        fa2.FAUserFaultInfo__c = uf2.Id;
+        insert fa2;
+        ba2 = new BusinessActivity__c();
+        ba2.BusinessATS__c = tsr2.Id;
+        ba2.workingHours__c = 2;
+        ba2.User_FaultInfo__c = uf2.Id;
+        insert ba2;
+
+        uf3 = new User_FaultInfo__c();
+        insert uf3;
+        fa3 = new FailureAsset__c();
+        fa3.model__c = 'test3';
+        fa3.FAUserFaultInfo__c = uf3.Id;
+        insert fa3;
+        ba3 = new BusinessActivity__c();
+        ba3.BusinessATS__c = tsr2.Id;
+        ba3.workingHours__c = 2;
+        ba3.User_FaultInfo__c = uf3.Id;
+        insert ba3;
+
+        Attachment att = new Attachment(
+            Name = 'ORDER-123456.pdf',
+            parentId = ba1.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att;
+
+        Attachment att2 = new Attachment(
+            Name = 'not-ORDER-123456.pdf',
+            parentId = ba2.Id,
+            Body = EncodingUtil.base64Decode('test')
+        );
+        insert att2;
+
+    }
+    static testMethod void testMethod1() {
+        basicData();
+        User user2 = UserD();
+        uf1.ASSIGNED_TO__c = user2.Id;
+        uf1.SEND_TO_CUSTOMER__c = true;
+        uf1.INTERNAL_ONLY__c = true;
+        uf1.Interactions__c = 'TEST';
+        update uf1;
+    }
+
+    static testMethod void testMethod2() {
+        // basicData();
+        // User user2 = UserD();
+        // uf1.ASSIGNED_TO__c = user2.Id;
+        // uf1.SEND_TO_CUSTOMER__c = true;
+        // uf1.INTERNAL_ONLY__c = true;
+        // // uf1.Interactions__c = 'TEST';
+        // update uf1;
+
+        User_FaultInfo__c ufn = new User_FaultInfo__c();
+        ufn.ASSIGNED_TO__c = UserD().Id;
+        ufn.Interactions__c = 'TEST01';
+        insert ufn;
+    }
+    
+
+    public static User UserD(){
+        User user2 = new User();
+        user2.LastName = 'test2';
+        user2.FirstName = 'test2';
+        user2.Alias = 'test2';
+        user2.Email = 'test2@test.com';
+        user2.Username = 'Xin_Prectech@olympus.com.cn';
+        user2.CommunityNickname = 'test2';
+        user2.IsActive = true;
+        user2.EmailEncodingKey = 'ISO-2022-JP';
+        user2.TimeZoneSidKey = 'Asia/Tokyo';
+        user2.LocaleSidKey = 'ja_JP';
+        user2.LanguageLocaleKey = 'ja';
+        user2.ProfileId = '00e28000001sZE6';//System.Label.SystemAdmin;
+        insert user2;
+
+        return user2;
+    }    
+}
\ No newline at end of file
diff --git a/scr/classes/UserFaultInfoHandlerTest.cls-meta.xml b/scr/classes/UserFaultInfoHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/UserFaultInfoHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UserViolationsTriggerHandler.cls b/scr/classes/UserViolationsTriggerHandler.cls
new file mode 100644
index 0000000..0968702
--- /dev/null
+++ b/scr/classes/UserViolationsTriggerHandler.cls
@@ -0,0 +1,43 @@
+public without sharing class UserViolationsTriggerHandler {
+        
+    /**
+     *   瑙e喕鏃跺皢鎵�鏈夎鐢ㄦ埛涓嬬殑杩濊璁板綍鐨勬槸鍚︽湁鏁堣缃负"鍚�",骞跺皢鐢ㄦ埛涓湁鏁堣繚瑙勬暟鍜岃繚瑙勪俊鎭疘D璁板綍涓烘竻绌�.
+    */  
+    public static void setOK(List<User_Violations__c> newList, Map<Id, User_Violations__c> newMap, List<User_Violations__c> oldList, Map<Id, User_Violations__c> oldMap){
+        List<User_Violations__c> uvList = new List<User_Violations__c>();
+        List<String> uvIdList = new List<String>();
+        Set<String> userIdSet = new Set<String>();
+        
+        for(User_Violations__c uv : newList){
+            User_Violations__c old = oldMap.get(uv.Id);
+            if(uv.Is_locking__c != old.Is_locking__c && uv.Is_locking__c == false && uv.is_Alone__c == false){
+                uvIdList.add(uv.Violations_User__c);
+            }
+        }
+        System.debug(uvIdList);
+        uvList = [SELECT Id,Is_effective__c,Violations_User__c,Is_locking__c FROM User_Violations__c WHERE Violations_User__c in :uvIdList AND Is_effective__c = true];
+        System.debug(uvList);
+         if(uvList.size() > 0){
+            for(User_Violations__c uv : uvList){
+                uv.Is_effective__c = false;
+                if(uv.Is_locking__c == true){
+                    uv.Is_locking__c = false;
+                    uv.Violations_Stop_Date__c = Date.today();
+                }
+                userIdSet.add(uv.Violations_User__c);
+            }
+            List<User> userList = [SELECT Id FROM User WHERE Id in :userIdSet];
+            for(User user : userList){
+                user.Return_Timeout_Number__c = 0;
+                user.Automatic_Received_Number__c = 0;
+                user.ViolationsID__c = null;
+            }
+            System.debug(uvList);
+            System.debug(userList);
+            update uvList;
+            update userList;
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/scr/classes/UserViolationsTriggerHandler.cls-meta.xml b/scr/classes/UserViolationsTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/UserViolationsTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/UserViolationsTriggerTest.cls b/scr/classes/UserViolationsTriggerTest.cls
new file mode 100644
index 0000000..3bcba32
--- /dev/null
+++ b/scr/classes/UserViolationsTriggerTest.cls
@@ -0,0 +1,162 @@
+@isTest
+private class  UserViolationsTriggerTest {
+	
+	@isTest static void test_method_one() {
+		 List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+        List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'BS'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+
+        //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER BS'];
+        Account dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'BS';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        Contact core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        User testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        Account acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'BS';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        Loaner_Set__c loanerSet = new loaner_Set__c();
+        loanerSet.Equipment_Type__c = 'BS';
+        loanerSet.Set_No__c = 'IETEST0001';
+        loanerSet.Name = 'IETEST0001';
+
+        insert loanerSet;
+
+        // 浜у搧
+        Product2 prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        Product2 prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset asset = new Asset();
+        asset.RecordTypeId = loa_number[0].Id;
+        asset.SerialNumber = 'asset';
+        asset.Name = 'asset';
+        asset.AccountId = acc.Id;
+        asset.Product2Id = prd2.Id;
+        asset.Quantity = 1;
+        asset.Status = '鍦ㄥ簱';
+        asset.Equipment_Type__c = 'BS';
+        asset.loaner_place__c = '骞垮窞鍔�';
+        asset.total_number__c = 20;
+        asset.Remarks2__c = 'asset';
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        Asset assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'BS';
+        assetC1.loaner_place__c = '骞垮窞鍔�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (鏁伴噺绠$悊)
+        Asset assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_number[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd2.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'BS';
+        assetC2.loaner_place__c = '骞垮窞鍔�';
+        assetC2.total_number__c = 20;
+        assetC2.Remarks2__c = 'asset';
+        insert new Asset[] {asset,assetC1,assetC2};
+
+        Loaner_Set_Detail__c lSD1 = new Loaner_Set_Detail__c();
+        lSD1.Loaner_Set__c = loanerSet.Id;
+        lSD1.Asset__c = asset.Id;
+        Loaner_Set_Detail__c lSD2 = new Loaner_Set_Detail__c();
+        lSD2.Loaner_Set__c = loanerSet.Id;
+        lSD2.Asset__c = assetC1.Id;
+        insert new Loaner_Set_Detail__c[] {lSD1,lSD2};
+
+        loaner_application__c loanerApp = new loaner_application__c();
+        loanerApp.Name = 'TESTYJ0001';
+        loanerApp.Approval_Step__c = 1;
+        loanerApp.Status__c = '鐢宠涓�';
+        loanerApp.Loaner_Ser__c = 'test';
+        loanerApp.Equipment_Type__c = 'BS';
+        loanerApp.RecordTypeId = rectLapp[0].Id;
+        loanerApp.Demo_purpose__c = '鍏ㄥ浗鎬у睍浼�';
+        loanerApp.Request_shipping_Date__c = Date.today().addDays(1);
+        loanerApp.Request_return_Date__c = Date.today().addDays(5);
+        loanerApp.ownerId = testUser.Id;
+        loanerApp.ProductNameNum1__c = prd2.Id;
+       loanerApp.pickup_time__c = Date.today();
+        insert loanerApp;
+
+        User_Violations__c uv = new User_Violations__c();
+
+        uv.Is_locking__c = true;
+        uv.Is_effective__c = true;
+        uv.Locking_Start_Date__c = Date.today();
+        uv.Violations_User__c =testUser.Id;
+        uv.Violations_Loaner__c = loanerApp.id;
+        insert uv;
+        User_Violations__c uv1 = new User_Violations__c();
+
+        uv1.Is_locking__c = false;
+        uv1.Is_effective__c = true;
+        uv1.Locking_Start_Date__c = Date.today();
+        uv1.Violations_User__c =testUser.Id;
+        uv1.Violations_Loaner__c = loanerApp.id;
+        insert uv1;
+        uv.Is_locking__c = false;
+        uv.Is_effective__c = false;
+
+        system.runAs(testUser){
+        	update uv;
+    	}
+	
+
+	}
+
+	
+}
\ No newline at end of file
diff --git a/scr/classes/UserViolationsTriggerTest.cls-meta.xml b/scr/classes/UserViolationsTriggerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/UserViolationsTriggerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/calendarUtil.cls b/scr/classes/calendarUtil.cls
new file mode 100644
index 0000000..d1bafba
--- /dev/null
+++ b/scr/classes/calendarUtil.cls
@@ -0,0 +1,155 @@
+public with sharing class calendarUtil {
+	//鏃ユ湡涓棿鍙栨棩鍘哅ap
+	public static Map<string,OlympusCalendar__c> getCalendarMap(Date beginDate,Date endDate){
+		Map<string,OlympusCalendar__c> calendarMap = new Map<string,OlympusCalendar__c>();
+		List<OlympusCalendar__c> calendarList = [select id,Date__c,IsWorkDay__c from OlympusCalendar__c where Date__c >= :beginDate and Date__c <= :endDate];
+		for(OlympusCalendar__c cal : calendarList){
+			Date datetemp = cal.Date__c;
+			calendarMap.put(datetemp.format(),cal);
+		}
+		return calendarMap;
+	}
+	//鑾峰彇涓や釜鏃ユ湡闂寸殑宸ヨ祫鏃�
+	public static Integer getNumfromCalendarMap (Map<string,OlympusCalendar__c> calendarMap,Date beginDate,Date endDate){
+		Integer num = 0;
+		List<OlympusCalendar__c> calendarList = new List<OlympusCalendar__c>();
+		Set<String> keys = calendarMap.keySet();
+		for(String key : keys){
+			Date keyDate = Date.valueOf(key.replace('/', '-'));
+			if(beginDate<=keyDate && keyDate <= endDate){
+				calendarList.add(calendarMap.get(key));
+			}
+		}
+		for(OlympusCalendar__c oly : calendarList){
+			if(oly.IsWorkDay__c == 1){
+				system.debug(oly.Date__c+'   '+oly.IsWorkDay__c);
+				num++;
+			}
+		}
+
+		return num;
+	}
+	//鑾峰彇鏃ユ湡num涓伐浣滄棩涔嬪悗\涔嬪墠鐨勬棩鏈�
+	public static Date getCorrespondingDate(Map<String,OlympusCalendar__c> calendarMap,Date beginDate,Integer num){
+		Integer count = 0;
+		Date temp ;
+		if(num > 0){
+			for(Integer i = 1;;i++){
+				temp = beginDate.addDays(i);
+				String str = temp.format();
+				OlympusCalendar__c oly = calendarMap.get(str);
+				if(oly.IsWorkDay__c == 1){
+					count++;
+				}
+				if(num == count){
+					break;
+				}
+			}
+		}else{
+			for(Integer i = -1;;i--){
+				temp = beginDate.addDays(i);
+				String str = temp.format();
+				OlympusCalendar__c oly = calendarMap.get(str);
+				if(oly.IsWorkDay__c == 1){
+					count--;
+				}
+				if(num == count){
+					break;
+				}
+			}
+		}
+		return temp;
+	}
+
+
+	//鑾峰彇涓や釜鏃ユ湡闂寸殑宸ヨ祫鏃�
+	public static string getWorkDayNum (String beginStr,String endStr){
+
+		Date beginDate = Date.valueOf(beginStr.replace('/', '-'));
+		Date endDate = Date.valueOf(endStr.replace('/', '-')); 
+
+		Map<String,OlympusCalendar__c> olmap = calendarUtil.getCalendarMap(beginDate.addDays(-1),endDate.addDays(1));
+
+		Integer count = calendarUtil.getNumfromCalendarMap(olmap,beginDate,endDate);
+
+		return String.valueOf(count);
+
+	}
+
+	//鑾峰彇days涓伐浣滄棩涔嬪墠鎴栦箣鍚庣殑鏃ユ湡
+	public static String getWorkDay(String beginStr,String days){
+
+		Date beginDate = Date.valueOf(beginStr.replace('/', '-'));
+		Integer num = Integer.valueOf(days);
+		Map<String,OlympusCalendar__c> olmap = new Map<String,OlympusCalendar__c>();
+		if(num<0){
+			olmap = calendarUtil.getCalendarMap(beginDate.addDays(num-20),beginDate.addDays(1));
+		}else{
+			olmap = calendarUtil.getCalendarMap(beginDate.addDays(-1),beginDate.addDays(num+20));
+		}
+
+		Date newDate = calendarUtil.getCorrespondingDate(olmap,beginDate,num);
+
+		return String.valueOf(newDate);
+	}
+
+	// 鍦ㄨ嚜瀹氫箟鏍囩涓幏鍙栬�佺殑绠�妗D  calendarUtil.getMemberProfileID
+	public static String getMemberProfileID(String memberID){
+
+		if(String.isBlank(memberID) || memberID.length()<15) return '0000000000000000';
+
+		memberID = memberID.substring(0, 15);
+		List<String> allProfile = Profile();
+		for(String profile:allProfile){
+			if(String.isNotBlank(profile) && profile.contains(':')){
+				List<String> profileList = profile.split(':');
+				if(profileList.size() > 1 && profileList[1].contains(memberID)){
+					return profileList[0];
+				}
+			}
+		}
+		return '0000000000000000';
+	}
+
+	private static List<String> Profile(){
+		List<String> profilList = new List<String>();
+		profilList.add(System.label.SSBG_ANI);
+		// profilList.add(System.label.SSBG_ANI_after);
+		profilList.add(System.label.SSBG_ANI_manager);
+		profilList.add(System.label.SSBG_IE);
+		profilList.add(System.label.SSBG_IE_Manager_Above);
+		// profilList.add(System.label.SSBG_IE_after);
+		profilList.add(System.label.SSBG_IE_One);
+		profilList.add(System.label.SSBG_IE_manager);
+		profilList.add(System.label.SSBG_LS);
+		profilList.add(System.label.SSBG_LS_Manager_Above);
+		profilList.add(System.label.SSBG_LS_OnlyLoaner);
+		profilList.add(System.label.SSBG_LS_notone);
+		profilList.add(System.label.SSBG_LS_prototype_manager);
+		profilList.add(System.label.SSBG_NDT);
+		profilList.add(System.label.SSBG_NDT_Manager_Above);
+		profilList.add(System.label.SSBG_NDT_prototype_manager);
+		profilList.add(System.label.SSBG_Read_Only);
+		profilList.add(System.label.SSBG_Read_Only_OT);
+		profilList.add(System.label.SSBG_RVI);
+		// profilList.add(System.label.SSBG_RVI_one);
+		profilList.add(System.label.SSBG_RVI_after_one);
+		profilList.add(System.label.SSBG_RVI_2);
+		profilList.add(System.label.SSBG_Scientific_management_headquarters);
+		profilList.add(System.label.SSBG_Service_Manager);
+		profilList.add(System.label.SSBG_service_department);
+		profilList.add(System.label.SSBG_Compliance_department);
+		profilList.add(System.label.SSBG_Market_promotion_department);
+		profilList.add(System.label.SSBG_Scientific_management_headquarters2);
+		profilList.add(System.label.SSBG_Business_management_department);
+		profilList.add(System.label.SSBG_Strategic_planning_department);
+		profilList.add(System.label.SSBG_Business_management_department2);
+		profilList.add(System.label.SSBG_Business_management_department_Have_price);
+		profilList.add(System.label.Trial_Customer_Portal_User);
+		profilList.add(System.label.system_administrator);
+		profilList.add(System.label.system_administrator2);
+		profilList.add(System.label.SystemAdmin_GPI_New);
+		//profilList.add(System.label.Mark_Not_change);
+		return profilList;
+	}
+}
\ No newline at end of file
diff --git a/scr/classes/calendarUtil.cls-meta.xml b/scr/classes/calendarUtil.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/calendarUtil.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/calendarUtilTest.cls b/scr/classes/calendarUtilTest.cls
new file mode 100644
index 0000000..4d618f9
--- /dev/null
+++ b/scr/classes/calendarUtilTest.cls
@@ -0,0 +1,45 @@
+@isTest
+private class calendarUtilTest {
+	
+	@isTest static void test_method_one() {
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+
+        Map<String,OlympusCalendar__c> calMap = calendarUtil.getCalendarMap(Date.today().addDays(1),Date.today().addDays(12));
+
+        Integer count = calendarUtil.getNumfromCalendarMap(calMap,Date.today().addDays(3),Date.today().addDays(8));
+
+        system.debug(calMap);
+        system.debug(count);
+
+        Date beforeDate = calendarUtil.getCorrespondingDate(calMap,Date.today().addDays(6),2);
+        Date afterDate = calendarUtil.getCorrespondingDate(calMap,Date.today().addDays(6),-2);
+        system.debug(beforeDate+'======'+afterDate);
+
+        String workdayNum = calendarUtil.getWorkDayNum(String.valueOf(Date.today().addDays(3)),String.valueOf(Date.today().addDays(8)));
+        String workday = calendarUtil.getWorkDay(String.valueOf(Date.today().addDays(3)),'5');
+        String workday1 = calendarUtil.getWorkDay(String.valueOf(Date.today().addDays(3)),'-1');
+        system.debug(workday+'===='+workdayNum+'====='+workday1);
+        
+	}
+
+	@isTest static void test_method_two() {
+	    String profileID1 = calendarUtil.getMemberProfileID(null);
+        String profileID2 = calendarUtil.getMemberProfileID('111');
+        String profileID3 = calendarUtil.getMemberProfileID('1111111111111111');
+        String profileID4 = calendarUtil.getMemberProfileID('0050K00000ABL7G');
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/calendarUtilTest.cls-meta.xml b/scr/classes/calendarUtilTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/calendarUtilTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/loanerAppTriggerHandler.cls b/scr/classes/loanerAppTriggerHandler.cls
new file mode 100644
index 0000000..983b992
--- /dev/null
+++ b/scr/classes/loanerAppTriggerHandler.cls
@@ -0,0 +1,679 @@
+public without sharing class loanerAppTriggerHandler {
+    /**
+     * [changeFollowOpp description] 璺熻繘璇环鏀瑰彉鏃朵慨鏀硅窡杩涜浠�(鏂囨湰)
+     * Date 2020/8/20
+     */
+    public static void changeFollowOpp(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
+        //List<loaner_application__c> upList = new List<loaner_application__c>();
+        List<String> idList = new List<String>();
+        for(loaner_application__c la : newList){
+            loaner_application__c oldla = oldMap.get(la.Id);
+            if(la.Equipment_Type__c == 'BS' && la.Follow_Opp__c != oldla.Follow_Opp__c && la.Follow_Opp__c != null){
+                idList.add(la.Follow_Opp__c);
+            }
+            if(la.Equipment_Type__c == 'BS' && la.Follow_Opp__c != oldla.Follow_Opp__c && la.Follow_Opp__c == null){
+                la.Follow_Opp_text__c = null;
+            }
+        }
+
+        if(idList.size() > 0){
+
+            List<Opportunity> oppList = new List<Opportunity>();
+            oppList = [select id,InquiryNumber__c from Opportunity where id in :idList];
+            for(loaner_application__c la : newList){
+                if(idList.contains(la.Follow_Opp__c)){
+                    for(Opportunity opp : oppList){
+                        if(opp.Id == la.Follow_Opp__c){
+                            la.Follow_Opp_text__c = opp.InquiryNumber__c;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    public static void transferBack(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
+        List<String> idList = new List<String>();
+        for(loaner_application__c la : newList){
+            loaner_application__c old = oldMap.get(la.Id);
+            if(old.Status__c == '鐢宠涓�' && la.Status__c == '鑽夋涓�' && la.Equipment_Type__c == 'BS' && la.Loaner_LendOrder__c == true){
+                idList.add(la.Id);
+            }
+        }
+        System.debug(idList);
+        if(idList.size() > 0){
+            List<String> laIdList = new List<String>();
+            List<Asset> pss = new List<Asset>();
+            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
+                                                        LOANER__r.RecordTypeId,LOANER__r.status,
+                                                        loaner_application__r.Loaner_LendOrder__c
+                                                From loaner_application_detail__c
+                                                Where loaner_application__c in: idList];
+            for(loaner_application_detail__c l2s : ps){
+                Asset p2s = new Asset();
+                p2s.Id =  l2s.LOANER__c;
+                p2s.Status = '鍑哄��';
+                pss.add(p2s);
+                laIdList.add(l2s.LOANER__c);
+            }
+            if(pss.size() > 0 ) update pss;
+            if(laIdList.size() > 0){
+                List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣' or RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭')];
+                System.debug('^^^^^^^'+ladList);
+                if(ladList.size() > 0){
+                    for (loaner_application_detail__c lad : ladList ) {
+                        lad.is_distribution__c = false;
+                    }
+                    System.debug('^^^^^^^'+ladList);
+                    update(ladList);
+                }
+            }
+        }
+        List<String> idList2 = new List<String>();
+        for(loaner_application__c la : newList){
+            loaner_application__c old = oldMap.get(la.Id);
+            if( la.Status__c == '鐢宠涓�' && la.Equipment_Type__c == 'BS' && la.Loaner_LendOrder__c == true){
+                idList2.add(la.Id);
+            }
+        }
+        System.debug('!@#'+idList2);
+        if(idList2.size() > 0){
+            List<String> laIdList = new List<String>();
+            List<Asset> pss = new List<Asset>();
+            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
+                                                        LOANER__r.RecordTypeId,LOANER__r.status,
+                                                        loaner_application__r.Loaner_LendOrder__c
+                                                From loaner_application_detail__c
+                                                Where loaner_application__c in: idList2];
+            for(loaner_application_detail__c l2s : ps){
+                laIdList.add(l2s.LOANER__c);
+            }
+            //if(pss.size() > 0 ) update pss;
+            if(laIdList.size() > 0){
+                List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣' or RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭')];
+                System.debug('^^^^^^^'+ladList);
+                if(ladList.size() > 0){
+                    for (loaner_application_detail__c lad : ladList ) {
+                        lad.is_distribution__c = true;
+                    }
+                    System.debug('^^^^^^^'+ladList);
+                    update(ladList);
+                }
+            }
+        }
+    }
+
+    public static String upsertAssetSubmit(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
+    {
+        List<String> p2ids = new List<String>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            if ((old.Status__c != local.Status__c || (local.Equipment_Type__c == 'IE' && local.Approval_Step__c == 2)) && local.Status__c == '鐢宠涓�') {
+                p2ids.add(local.id);
+            }
+        }
+
+        List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
+                                                        LOANER__r.RecordTypeId,LOANER__r.status,
+                                                        loaner_application__r.Loaner_LendOrder__c
+                                                From loaner_application_detail__c
+                                                Where loaner_application__c in: p2ids];
+        List<Asset> pss = new List<Asset>();
+        for(loaner_application_detail__c l2s : ps){
+            if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 
+                && l2s.loaner_application__r.Loaner_LendOrder__c == false){
+                if (l2s.LOANER__r.status != '鍦ㄥ簱' )
+                {
+                    return '鏍锋満 ' + l2s.LOANER__r.Name + ' 鐩墠鐘舵�佹槸' + l2s.LOANER__r.status + ',璇风‘璁�';
+                }
+                else{
+                    Asset p2s = new Asset();
+                    p2s.Id =  l2s.LOANER__c;
+                    p2s.Status = '鍐荤粨';
+                    pss.add(p2s);
+                }
+            }
+            l2s.RAESD_Status__c = '鐢宠涓�';
+        }
+        upsert(pss);
+        upsert(ps);
+        return '';
+    }
+    public static void upsertAssetApproval(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
+    {
+        List<String> p2ids = new List<String>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            if (old.Status__c != local.Status__c && local.Status__c == '宸叉壒鍑�') {
+                p2ids.add(local.id);
+            }
+        }
+         List<loaner_application_detail__c> ps = new List<loaner_application_detail__c>();
+        if(p2ids.size() > 0){
+            ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
+                    LOANER__r.RecordTypeId,LOANER__r.status,
+                    loaner_application__r.Loaner_LendOrder__c
+                    From loaner_application_detail__c
+                    Where loaner_application__c in: p2ids];
+        
+            //Map <String,Asset> psmap = new Map<String,Asset>();
+            List<Asset> pss = new List<Asset>();
+            for(loaner_application_detail__c l2s : ps){
+                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
+                    if (l2s.LOANER__r.status == '鍦ㄥ簱' && l2s.loaner_application__r.Loaner_LendOrder__c == false){
+                        Asset p2s = new Asset();
+                        p2s.Id =  l2s.LOANER__c;
+                        p2s.Status = '鍐荤粨';
+                        pss.add(p2s);
+                    }
+                }
+                l2s.RAESD_Status__c = '宸叉壒鍑�';
+            }
+            if(pss.size()>0) upsert(pss);
+            if(ps.size() >0) upsert(ps);
+        }
+    }
+
+    public static void cancelLoanerApplication(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
+    {
+        List<String> p2ids = new List<String>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            if (old.Status__c != local.Status__c && local.Status__c == '鍙栨秷') {
+                p2ids.add(local.id);
+            }
+        }
+        if(p2ids.size() >0){
+            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,Equipment_Type__c,
+                                                            LOANER__r.RecordTypeId,LOANER__r.status,loaner_application__r.Loaner_LendOrder__c
+                                                        From loaner_application_detail__c
+                                                        Where loaner_application__c in: p2ids];
+            List<Asset> pss = new List<Asset>();
+            List<String> laIdList = new List<String>();
+            for(loaner_application_detail__c l2s : ps){
+                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
+                    if (l2s.LOANER__r.status != '鍦ㄥ簱' && l2s.loaner_application__r.Loaner_LendOrder__c == false){
+                        Asset p2s = new Asset();
+                        p2s.Id =  l2s.LOANER__c;
+                        p2s.Status = '鍦ㄥ簱';
+                        pss.add(p2s);
+                    }else if(l2s.loaner_application__r.Loaner_LendOrder__c == true && l2s.Equipment_Type__c == 'BS'){
+                        Asset p2s = new Asset();
+                        p2s.Id =  l2s.LOANER__c;
+                        p2s.Status = '鍑哄��';
+                        pss.add(p2s);
+                        laIdList.add(l2s.LOANER__c);
+                    }
+                }
+                l2s.RAESD_Status__c = '鍙栨秷';
+                l2s.Cancel_Date__c  = Date.today();
+                System.debug('@@@@@@@@@'+laIdList);
+                if(laIdList.size() > 0){
+                    List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣' or RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭')];
+                    System.debug('@@@@@@@@@@@'+ladList);
+                    if(ladList.size() > 0){
+                        for (loaner_application_detail__c lad : ladList ) {
+                            lad.is_distribution__c = false;
+                        }
+                        System.debug('@@@@@@@@@@@'+ladList);
+                        update(ladList);
+                    }
+                }
+            }
+            if(pss.size() > 0) upsert(pss);
+            if(ps.size() > 0) upsert(ps);
+        }
+    }
+    public static void upsertAssetCancle(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
+    {
+        List<String> p2ids = new List<String>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            if (old.Status__c != local.Status__c && local.Status__c == '椹冲洖') {
+                p2ids.add(local.id);
+            }
+        }
+        if(p2ids.size() > 0){
+            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
+                                                            LOANER__r.RecordTypeId,LOANER__r.status,Equipment_Type__c,
+                                                            loaner_application__r.Loaner_LendOrder__c 
+                                                        From loaner_application_detail__c 
+                                                        Where loaner_application__c in: p2ids];
+            //Map <String,Asset> psmap = new Map<String,Asset>();
+            List<Asset> pss = new List<Asset>();
+            List<String> laIdList = new List<String>();
+            for(loaner_application_detail__c l2s : ps){
+                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 
+                    && l2s.loaner_application__r.Loaner_LendOrder__c == false){
+                    Asset p2s = new Asset();
+                    p2s.Id =  l2s.LOANER__c;
+                    p2s.Status = '鍦ㄥ簱';
+                    pss.add(p2s);
+                }else if(String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 
+                    && l2s.loaner_application__r.Loaner_LendOrder__c == true && l2s.Equipment_Type__c == 'BS'){
+                    Asset p2s = new Asset();
+                    p2s.Id = l2s.LOANER__c;
+                    p2s.Status = '鍑哄��';
+                    pss.add(p2s);
+                    laIdList.add(l2s.LOANER__c);
+                }
+                l2s.RAESD_Status__c = '椹冲洖';
+                System.debug('#######'+laIdList);
+                if(laIdList.size() > 0){
+                    List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '鐢宠鑰呭凡鏀惰揣' or RAESD_Status__c = '鐢宠鑰呭凡瑁呮満纭')];
+                    System.debug('#######'+ladList);
+                    if(ladList.size() > 0){
+                        for (loaner_application_detail__c lad : ladList ) {
+                            lad.is_distribution__c = false;
+                        }
+                        System.debug('#######'+ladList);
+                        update(ladList);
+                    }
+                }
+            }
+            if(pss.size() > 0) upsert(pss);
+            if(ps.size() > 0) upsert(ps);
+        }
+    }
+
+    public static void upsertAssetcallback(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
+    {
+        List<String> p2ids = new List<String>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            if ((old.Status__c != local.Status__c && old.Status__c == '鐢宠涓�' && local.Status__c == '鑽夋涓�') 
+                || (old.Status__c == '鐢宠涓�' && local.Status__c == '閿�鍞媴褰撴壒鍑�' && local.Equipment_Type__c == 'IE')) {
+                p2ids.add(local.id);
+            }
+        }
+        if(p2ids.size() >0 ){
+            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,LOANER__r.RecordTypeId,
+                                                            LOANER__r.status,loaner_application__r.Loaner_LendOrder__c 
+                                                            From loaner_application_detail__c 
+                                                            Where loaner_application__c in: p2ids];
+            //Map <String,Asset> psmap = new Map<String,Asset>();
+            List<Asset> pss = new List<Asset>();
+            for(loaner_application_detail__c l2s : ps){
+                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 && l2s.loaner_application__r.Loaner_LendOrder__c == false){
+                    Asset p2s = new Asset();
+                    p2s.Id =  l2s.LOANER__c;
+                    p2s.Status = '鍦ㄥ簱';
+                    pss.add(p2s);
+                }
+                l2s.RAESD_Status__c = '宸插垎閰�';
+            }
+            if(pss.size() > 0) upsert(pss);
+            if(ps.size() > 0) upsert(ps);
+        }
+    }
+    //RVI鏍锋満绠$悊鍛樺鎵规椂锛屽垽鏂湁娌℃湁濉啓鍊熷嚭寮�濮嬫棩鍜屽�熷嚭缁撴潫鏃�
+    public static void rental_Datejudgment(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
+        LoanerAppDetailTriggerHandler.runTrigger = false;
+        List<String> p2ids = new List<String>();
+        List<String> detids = new List<String>();
+        Map<Id,loaner_application_detail__c> olddetsMap = new Map<Id,loaner_application_detail__c>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c oldLA = oldMap.get(local.Id);
+            if (local.RVI_Manager_Approval__c != oldLA.RVI_Manager_Approval__c && local.RVI_Manager_Approval__c == true && (local.Rental_Start_Date__c == null || local.Rental_End_Date__c == null)){
+                local.addError('璇疯緭鍏ュ�熷嚭寮�濮嬫棩鍜屽�熷嚭缁撴潫鏃ャ��');
+            }
+            if(local.Loaner_LendOrder__c == true && local.Detail_count__c  == 0 && (local.Status__c == '宸叉壒鍑�' || local.Status__c == '閿�鍞媴褰撴壒鍑�')){
+                local.addError('璇峰厛鍒嗛厤鏍锋満鍦ㄥ鎵归�氳繃');
+            }
+        }
+        
+    }
+    public static void serviceApproval(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
+        LoanerAppDetailTriggerHandler.runTrigger = false;
+        for(loaner_application__c la : newList){
+            loaner_application__c old = oldMap.get(la.Id);
+            if(la.Service_Approval__c != old.Service_Approval__c && la.Service_Approval__c == true && la.Engineer_FW__c == null){
+                la.addError('瀹℃壒鍓嶈濉啓:宸ョ▼甯堝悕绉�(鏈嶅姟).');
+            }
+            if(la.Product_Approval__c != old.Product_Approval__c && la.Product_Approval__c == true && la.Engineer_CP__c == null){
+                la.addError('瀹℃壒鍓嶈濉啓:宸ョ▼甯堝悕绉�(浜у搧).');
+            }
+        }
+
+    }
+    //杞�熸壒鍑嗗悗锛岀姸鎬佹敼涓� 鍏ㄩ儴鍙戣揣
+    public static void GoToNextStatusHead(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
+        LoanerAppDetailTriggerHandler.runTrigger = false;
+        List<String> p2ids = new List<String>();
+        List<String> detids = new List<String>();
+        Map<Id,loaner_application_detail__c> olddetsMap = new Map<Id,loaner_application_detail__c>();
+        for (loaner_application__c local : newList) {
+            loaner_application__c oldLA = oldMap.get(local.Id);
+            if (local.Status__c != oldLA.Status__c && local.Status__c == '鐢宠涓�'){
+                if((String.isBlank(local.Loaner_receive_staff__c)|| String.isBlank(local.direct_shippment_address__c)|| String.isBlank(local.Loaner_receive_staff_phone__c)|| 
+                   String.isBlank(local.Post_Code__c)) && local.pickup_time__c == null){
+                    local.addError('鏀惰揣浜轰俊鎭垨鑰呰嚜鎻愭椂闂磋濉啓涓�椤广��');
+                }
+                if((!String.isBlank(local.Loaner_receive_staff__c)||!String.isBlank(local.direct_shippment_address__c)|| !String.isBlank(local.Loaner_receive_staff_phone__c)|| 
+                   !String.isBlank(local.Post_Code__c)) && local.pickup_time__c != null){
+                    local.addError('鏀惰揣浜轰俊鎭垨鑰呰嚜鎻愭椂闂磋濉啓涓�椤广��');
+                }
+            }
+        }
+        for (loaner_application__c local : newList) {
+            loaner_application__c oldLA = oldMap.get(local.Id);
+            if (local.Status__c != oldLA.Status__c && local.Status__c == '宸叉壒鍑�' && (local.Rental_Start_Date__c == null || local.Rental_End_Date__c == null)){
+                local.addError('璇疯緭鍏ュ�熷嚭寮�濮嬫棩鍜屽�熷嚭缁撴潫鏃ャ��');
+            }
+        }
+        for (loaner_application__c local : newList) {
+            loaner_application__c oldLA = oldMap.get(local.Id);
+            if (local.Status__c != oldLA.Status__c && local.Status__c == '閿�鍞媴褰撴壒鍑�' && local.Detail_count__c == 0 && local.Approval_Step__c  == 1 && local.Equipment_Type__c  == 'IE'){
+                local.addError('蹇呴』鍏堝仛鏍锋満鍒嗛厤鍚庡啀瀹℃壒.');
+            }
+        }
+    }
+
+
+    public static void setSubmitUser(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            Id submitUser = UserInfo.getUserId();
+            if (old.Status__c != local.Status__c && (local.Status__c == '宸叉彁浜�' || local.Status__c == '鐢宠涓�')
+                && String.isBlank(local.ApplyPerson__c)) {
+                local.ApplyPerson__c = submitUser;
+            }
+        }
+    }
+
+    public static void setApprover(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
+        List<String> ApproverIdList = new List<String>();
+        List<String> loaner_appList = new List<String>();
+        List<String> productIDList = new List<String>();
+        Map<String,String> loanerapplicationToApprover = new Map<String,String>();
+        For (loaner_application__c newloanerapplication: newList) {
+            loaner_application__c oldloanerapplication = oldMap.get(newloanerapplication.Id);
+//            if (oldloanerapplication.Approver__c != newloanerapplication.Approver__c || Trigger.isInsert == true) {
+                loaner_appList.add(newloanerapplication.Id);
+                ApproverIdList.add(newloanerapplication.Approver__c);
+                loanerapplicationToApprover.put(newloanerapplication.Id, newloanerapplication.Approver__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum1__c)) productIDList.add(newloanerapplication.ProductNameNum1__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum2__c)) productIDList.add(newloanerapplication.ProductNameNum2__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum3__c)) productIDList.add(newloanerapplication.ProductNameNum3__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum4__c)) productIDList.add(newloanerapplication.ProductNameNum4__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum5__c)) productIDList.add(newloanerapplication.ProductNameNum5__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum6__c)) productIDList.add(newloanerapplication.ProductNameNum6__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum7__c)) productIDList.add(newloanerapplication.ProductNameNum7__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum8__c)) productIDList.add(newloanerapplication.ProductNameNum8__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum9__c)) productIDList.add(newloanerapplication.ProductNameNum9__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum10__c)) productIDList.add(newloanerapplication.ProductNameNum10__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum11__c)) productIDList.add(newloanerapplication.ProductNameNum11__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum12__c)) productIDList.add(newloanerapplication.ProductNameNum12__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum13__c)) productIDList.add(newloanerapplication.ProductNameNum13__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum14__c)) productIDList.add(newloanerapplication.ProductNameNum14__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum15__c)) productIDList.add(newloanerapplication.ProductNameNum15__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum16__c)) productIDList.add(newloanerapplication.ProductNameNum16__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum17__c)) productIDList.add(newloanerapplication.ProductNameNum17__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum18__c)) productIDList.add(newloanerapplication.ProductNameNum18__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum19__c)) productIDList.add(newloanerapplication.ProductNameNum19__c);
+                if(String.isNotBlank(newloanerapplication.ProductNameNum20__c)) productIDList.add(newloanerapplication.ProductNameNum20__c);
+//            }
+        }
+        Map<Id, Product2> copyProductMap = new Map<Id, Product2>([
+            SELECT Id, Product_ECCode__c
+            FROM Product2
+            WHERE Id IN :productIDList
+        ]);
+        Map<Id, User> copyUserMap = new Map<Id, User>([
+            SELECT Id, Name, SalesAsistManager__c, BusinessDepOwner_Tax__c,BusinessDepOwner_WithoutTax__c, 
+                SalesManager__c, AsistGenManger__c,CRM_Owner__c 
+            FROM User 
+            WHERE Id IN :ApproverIdList
+        ]);
+        Map<Id, loaner_application__c> loaner_appMap = new Map<Id, loaner_application__c>([
+            select id,name,CreatorUserType__c,CreatedBy.Contact.AccountId__c,AccountId__c,ProductNameNum1__c,
+                   ProductNameNum2__c,ProductNameNum3__c,ProductNameNum4__c,ProductNameNum5__c,
+                   ProductNameNum6__c,ProductNameNum7__c,ProductNameNum8__c,ProductNameNum9__c,
+                   ProductNameNum10__c,ProductNameNum11__c,ProductNameNum12__c,ProductNameNum13__c,
+                   ProductNameNum14__c,ProductNameNum15__c,ProductNameNum16__c,ProductNameNum17__c,
+                   ProductNameNum18__c,ProductNameNum19__c,ProductNameNum20__c
+              from  loaner_application__c WHERE Id IN :loaner_appList
+        ]);
+
+        for (loaner_application__c newloanerapplication: newList){
+            loaner_application__c oldloanerapplication = loaner_appMap.get(newloanerapplication.Id);
+            newloanerapplication.EC_Code_1__c = '';
+            newloanerapplication.EC_Code_2__c = '';
+            newloanerapplication.EC_Code_3__c = '';
+            newloanerapplication.EC_Code_4__c = '';
+            newloanerapplication.EC_Code_5__c = '';
+            newloanerapplication.EC_Code_6__c = '';
+            newloanerapplication.EC_Code_7__c = '';
+            newloanerapplication.EC_Code_8__c = '';
+            newloanerapplication.EC_Code_9__c = '';
+            newloanerapplication.EC_Code_10__c = '';
+            newloanerapplication.EC_Code_11__c = '';
+            newloanerapplication.EC_Code_12__c = '';
+            newloanerapplication.EC_Code_13__c = '';
+            newloanerapplication.EC_Code_14__c = '';
+            newloanerapplication.EC_Code_15__c = '';
+            newloanerapplication.EC_Code_16__c = '';
+            newloanerapplication.EC_Code_17__c = '';
+            newloanerapplication.EC_Code_18__c = '';
+            newloanerapplication.EC_Code_19__c = '';
+            newloanerapplication.EC_Code_20__c = '';
+
+            if(String.isNotBlank(newloanerapplication.ProductNameNum1__c)) newloanerapplication.EC_Code_1__c = copyProductMap.get(newloanerapplication.ProductNameNum1__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum2__c)) newloanerapplication.EC_Code_2__c = copyProductMap.get(newloanerapplication.ProductNameNum2__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum3__c)) newloanerapplication.EC_Code_3__c = copyProductMap.get(newloanerapplication.ProductNameNum3__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum4__c)) newloanerapplication.EC_Code_4__c = copyProductMap.get(newloanerapplication.ProductNameNum4__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum5__c)) newloanerapplication.EC_Code_5__c = copyProductMap.get(newloanerapplication.ProductNameNum5__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum6__c)) newloanerapplication.EC_Code_6__c = copyProductMap.get(newloanerapplication.ProductNameNum6__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum7__c)) newloanerapplication.EC_Code_7__c = copyProductMap.get(newloanerapplication.ProductNameNum7__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum8__c)) newloanerapplication.EC_Code_8__c = copyProductMap.get(newloanerapplication.ProductNameNum8__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum9__c)) newloanerapplication.EC_Code_9__c = copyProductMap.get(newloanerapplication.ProductNameNum9__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum10__c)) newloanerapplication.EC_Code_10__c = copyProductMap.get(newloanerapplication.ProductNameNum10__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum11__c)) newloanerapplication.EC_Code_11__c = copyProductMap.get(newloanerapplication.ProductNameNum11__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum12__c)) newloanerapplication.EC_Code_12__c = copyProductMap.get(newloanerapplication.ProductNameNum12__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum13__c)) newloanerapplication.EC_Code_13__c = copyProductMap.get(newloanerapplication.ProductNameNum13__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum14__c)) newloanerapplication.EC_Code_14__c = copyProductMap.get(newloanerapplication.ProductNameNum14__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum15__c)) newloanerapplication.EC_Code_15__c = copyProductMap.get(newloanerapplication.ProductNameNum15__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum16__c)) newloanerapplication.EC_Code_16__c = copyProductMap.get(newloanerapplication.ProductNameNum16__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum17__c)) newloanerapplication.EC_Code_17__c = copyProductMap.get(newloanerapplication.ProductNameNum17__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum18__c)) newloanerapplication.EC_Code_18__c = copyProductMap.get(newloanerapplication.ProductNameNum18__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum19__c)) newloanerapplication.EC_Code_19__c = copyProductMap.get(newloanerapplication.ProductNameNum19__c).Product_ECCode__c;
+            if(String.isNotBlank(newloanerapplication.ProductNameNum20__c)) newloanerapplication.EC_Code_20__c = copyProductMap.get(newloanerapplication.ProductNameNum20__c).Product_ECCode__c;
+            if (oldloanerapplication.CreatorUserType__c == 'PowerPartner' ) {
+                newloanerapplication.Agent__c = oldloanerapplication.AccountId__c;
+            }
+        }
+
+        for (loaner_application__c newloanerapplication: newList){
+            loaner_application__c oldloanerapplication = oldMap.get(newloanerapplication.Id);
+                User u = copyUserMap.get(loanerapplicationToApprover.get(newloanerapplication.Id));
+                if (u != null && (u.SalesAsistManager__c != null || u.BusinessDepOwner_Tax__c != null || u.BusinessDepOwner_WithoutTax__c != null || u.SalesManager__c != null || u.AsistGenManger__c != null)) {
+                    newloanerapplication.DeputyApproveManager__c = u.SalesAsistManager__c == null ? u.Id : u.SalesAsistManager__c;
+                    newloanerapplication.ApproveManager__c = u.SalesManager__c == null ? u.Id : u.SalesManager__c;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'IE' &&  newloanerapplication.loaner_place__c == '涓婃捣OSH'){
+                    newloanerapplication.loaner_Manager__c = System.label.IE_SH;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '涓婃捣鍢夊崕'){
+                     newloanerapplication.loaner_Manager__c = System.label.IE_SHJH;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '骞垮窞鍔�'){
+                    newloanerapplication.loaner_Manager__c = System.label.IE_GZB;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '鍖椾含閰掍粰妗�'){
+                    newloanerapplication.loaner_Manager__c = System.label.IE_BJ;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '涓婃捣鏄庡洯'){
+                    newloanerapplication.loaner_Manager__c = System.label.IE_SHMY;
+                }
+
+                if(newloanerapplication.Equipment_Type__c == 'RVI'){
+                    newloanerapplication.loaner_Manager__c = System.label.RVI_Manager;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'BS' && newloanerapplication.loaner_place__c == '鍖椾含閰掍粰妗�'){
+                     newloanerapplication.loaner_Manager__c = System.label.BS_JXQ;
+                }
+                if(newloanerapplication.Equipment_Type__c == 'BS' && newloanerapplication.loaner_place__c == '骞垮窞鍔�'){
+                    newloanerapplication.loaner_Manager__c = System.label.BS_GZB;
+                }
+//            }
+        }
+    }
+
+    public static void BackToPreStatus(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
+        if(oldMap == null){
+            return;
+        }
+        for (loaner_application__c newLA : newList) {
+            if(newLA == null){
+                break;
+            }
+            loaner_application__c oldLA = oldMap.get(newLA.Id);
+            // String profileId = UserInfo.getProfileId();
+            if (newLA.BackToPreStatus__c != oldLA.BackToPreStatus__c && newLA.BackToPreStatus__c == true){
+                newLA.Status__c = newLA.BeforeSubmitStatus__c;
+                newLA.BackToPreStatus__c = false;
+            }
+        }
+        Map<String,Date> dateRangeMap = new Map<String,Date>();
+
+        for (loaner_application__c local : newList) {
+            loaner_application__c old = oldMap.get(local.Id);
+            if (old.Status__c != local.Status__c && local.Status__c == '鐢宠涓�') {
+                if(local.Request_shipping_Date__c!= null){
+                    if(!dateRangeMap.containsKey('BigDate')){
+                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
+                    }else if(local.Request_shipping_Date__c > dateRangeMap.get('BigDate')){
+                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
+                    }
+
+                    if(!dateRangeMap.containsKey('SmaDate')){
+                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
+                    }else if(local.Request_shipping_Date__c < dateRangeMap.get('SmaDate')){
+                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
+                    }
+                }
+            }
+        }
+        if(dateRangeMap.size()>0){
+            Map<String,OlympusCalendar__c> olyCalendarMap = calendarUtil.getCalendarMap(dateRangeMap.get('SmaDate').addDays(-15),dateRangeMap.get('BigDate').addDays(1));
+
+            for (loaner_application__c local : newList) {
+                if(local.Request_shipping_Date__c != null){
+                    local.Remind_Date__c = calendarUtil.getCorrespondingDate(olyCalendarMap,local.Request_shipping_Date__c,-3);
+                }
+            }
+        }
+
+        
+    }
+
+
+    public static void setRemind_Date(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
+        Map<String,Date> dateRangeMap = new Map<String,Date>();
+
+        for (loaner_application__c local : newList) {
+            //if (local.CreatorUserType__c == 'Standard' ) {
+                if(local.Request_shipping_Date__c!= null ){
+                    System.debug('Request_shipping_Date__c:'+local.Request_shipping_Date__c);
+                    if(!dateRangeMap.containsKey('BigDate')){
+                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
+                    }else if(local.Request_shipping_Date__c > dateRangeMap.get('BigDate')){
+                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
+                    }
+
+                    if(!dateRangeMap.containsKey('SmaDate')){
+                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
+                    }else if(local.Request_shipping_Date__c < dateRangeMap.get('SmaDate')){
+                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
+                    }   
+                }
+            //}
+            System.debug('dateRangeMap:'+dateRangeMap);
+        }
+        if(dateRangeMap.size()>0){
+            System.debug(dateRangeMap.get('SmaDate'));
+            System.debug(dateRangeMap.get('BigDate'));
+            Map<String,OlympusCalendar__c> olyCalendarMap = calendarUtil.getCalendarMap(dateRangeMap.get('SmaDate').addDays(-40),dateRangeMap.get('BigDate').addDays(15));
+            System.debug(olyCalendarMap);
+            for (loaner_application__c local : newList) {
+                if(local.Request_shipping_Date__c != null){
+                    local.Remind_Date__c = calendarUtil.getCorrespondingDate(olyCalendarMap,local.Request_shipping_Date__c,-3);
+                }
+            }
+        }
+    }
+
+
+    public static void emailDate(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
+        List<String> remindId = new List<String>();
+        for(loaner_application__c la : newList){
+            loaner_application__c old = oldMap.get(la.id);
+            if(la.Rental_End_Date__c != old.Rental_End_Date__c){
+                remindId.add(la.id);
+            }
+        }
+        Map<String,OlympusCalendar__c> oCalendar = calendarUtil.getCalendarMap(Date.today().addDays(-240),Date.today().addDays(240));
+        List<loaner_application__c> remindList = new List<loaner_application__c>();
+        if(remindId.size()>0){
+            remindList = [select id,Rental_End_Date__c,Equipment_Type__c from loaner_application__c where id= :remindId];
+            for(loaner_application__c remind : remindList){
+                if(remind.Equipment_Type__c == 'NDT' || remind.Equipment_Type__c == 'ANI'){
+                    remind.Remind_Request_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,-1);
+                    remind.First_timeOut__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,2);
+                    remind.Second_timeOut__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,4);
+
+                }else{
+                    remind.Remind_Request_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,-3);
+                }
+            }
+        }
+        if(remindList.size()>0) update remindList;
+    }
+
+   /* public static void unlock(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
+        List<String> laIdList = new List<String>();
+
+        for(loaner_application__c la : newList){
+            loaner_application__c old = oldMap.get(la.Id);
+            if(la.Status__c != old.Status__c && la.Status__c == '鍏ㄩ儴鍥炴敹' 
+                && (la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI') 
+                && la.Is_time_out__c){
+                laIdList.add(la.Id);
+            }
+        }
+
+        if(laIdList.size() == 0){
+            return;
+        }
+        //
+        List<String> userIdList = new List<String>();
+        List<User_Violations__c> uvList = [SELECT Id,Violations_User__c FROM User_Violations__c WHERE Violations_Loaner__c IN :laIdList];
+
+        if(uvList != null && uvList.size() > 0){
+            for(User_Violations__c uv : uvList){
+                uv.Is_effective__c = false;
+                uv.Is_locking__c = false;
+                uv.is_Alone__c = true;
+                userIdList.add(uv.Violations_User__c);
+            }
+        }
+
+        List<User_Violations__c> uv1List = [select id,Violations_User__c,Is_locking__c from User_Violations__c where Is_effective__c = true order by Violations_User__c];
+        Map<String,Integer> userMap = new Map<String,Integer>();
+        Map<String,String> user_vMap = new Map<String,String>();
+        for(User_Violations__c uv : uv1List){
+            if(userMap.containsKey(uv.Violations_User__c)){
+                userMap.put(uv.Violations_User__c, userMap.get(uv.Violations_User__c)+1);
+            }else{
+                userMap.put(uv.Violations_User__c, 1);
+            }
+            if(uv.Is_locking__c = true){
+                user_vMap.put(uv.Violations_User__c,uv.Id);
+            }
+        }
+
+
+    }*/
+   
+
+}
\ No newline at end of file
diff --git a/scr/classes/loanerAppTriggerHandler.cls-meta.xml b/scr/classes/loanerAppTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..9aeda45
--- /dev/null
+++ b/scr/classes/loanerAppTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/loanerAppTriggerHandlerTest.cls b/scr/classes/loanerAppTriggerHandlerTest.cls
new file mode 100644
index 0000000..af7b715
--- /dev/null
+++ b/scr/classes/loanerAppTriggerHandlerTest.cls
@@ -0,0 +1,197 @@
+@isTest
+private class loanerAppTriggerHandlerTest {
+	
+	@isTest static void test_method_one() {
+
+        OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc111 = new OlympusCalendar__c(Date__c = Date.today().addDays(-1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc112 = new OlympusCalendar__c(Date__c = Date.today().addDays(-2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc113 = new OlympusCalendar__c(Date__c = Date.today().addDays(-3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc114 = new OlympusCalendar__c(Date__c = Date.today().addDays(-4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc115 = new OlympusCalendar__c(Date__c = Date.today().addDays(-5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc116 = new OlympusCalendar__c(Date__c = Date.today().addDays(-6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc117 = new OlympusCalendar__c(Date__c = Date.today().addDays(-7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc118 = new OlympusCalendar__c(Date__c = Date.today().addDays(-8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc119 = new OlympusCalendar__c(Date__c = Date.today().addDays(-9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc1110 = new OlympusCalendar__c(Date__c = Date.today().addDays(-10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc1111 = new OlympusCalendar__c(Date__c = Date.today().addDays(-11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc1112 = new OlympusCalendar__c(Date__c = Date.today().addDays(-12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc221 = new OlympusCalendar__c(Date__c = Date.today().addDays(-13), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc222 = new OlympusCalendar__c(Date__c = Date.today().addDays(-14), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc223 = new OlympusCalendar__c(Date__c = Date.today().addDays(-15), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc224 = new OlympusCalendar__c(Date__c = Date.today().addDays(-16), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc225 = new OlympusCalendar__c(Date__c = Date.today().addDays(-17), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc226 = new OlympusCalendar__c(Date__c = Date.today().addDays(-18), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc227 = new OlympusCalendar__c(Date__c = Date.today().addDays(-19), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc228 = new OlympusCalendar__c(Date__c = Date.today().addDays(-20), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc229 = new OlympusCalendar__c(Date__c = Date.today().addDays(-21), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2210 = new OlympusCalendar__c(Date__c = Date.today().addDays(-22), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2211 = new OlympusCalendar__c(Date__c = Date.today().addDays(-23), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2212 = new OlympusCalendar__c(Date__c = Date.today().addDays(-24), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc331 = new OlympusCalendar__c(Date__c = Date.today().addDays(-25), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc332 = new OlympusCalendar__c(Date__c = Date.today().addDays(-26), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc333 = new OlympusCalendar__c(Date__c = Date.today().addDays(-27), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc334 = new OlympusCalendar__c(Date__c = Date.today().addDays(-28), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc335 = new OlympusCalendar__c(Date__c = Date.today().addDays(-29), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc336 = new OlympusCalendar__c(Date__c = Date.today().addDays(-30), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc337 = new OlympusCalendar__c(Date__c = Date.today().addDays(-31), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc338 = new OlympusCalendar__c(Date__c = Date.today().addDays(-32), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc339 = new OlympusCalendar__c(Date__c = Date.today().addDays(-33), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3310 = new OlympusCalendar__c(Date__c = Date.today().addDays(-34), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3311 = new OlympusCalendar__c(Date__c = Date.today().addDays(-35), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3312 = new OlympusCalendar__c(Date__c = Date.today().addDays(-36), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3313 = new OlympusCalendar__c(Date__c = Date.today().addDays(-37), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3314 = new OlympusCalendar__c(Date__c = Date.today().addDays(-38), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3315 = new OlympusCalendar__c(Date__c = Date.today().addDays(-39), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3316 = new OlympusCalendar__c(Date__c = Date.today().addDays(-40), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12,oc111, oc112 ,oc113, oc114, oc115, oc116, oc117, oc118, oc119, oc1110,oc1111,oc1112,oc221, oc222, oc223, oc224, oc225, oc226, oc227, oc228, oc229, oc2210,oc2211,oc2212,oc331, oc332, oc333, oc334, oc335, oc336, oc337, oc338, oc339, oc3310,oc3311,oc3312,oc3313,oc3314,oc3315,oc3316};
+		// Implement test code
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+      
+       // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(4);
+        loaner.Request_return_Date__c = Date.today().addDays(5);
+        loaner.Status__c = '宸插嚭搴撴寚绀�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        //loaner.pickup_time__c = Date.today().addDays(3);
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+	}
+	
+	@isTest static void test_method_two() {
+
+		OlympusCalendar__c oc1 = new OlympusCalendar__c(Date__c = Date.today().addDays(1), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc2 = new OlympusCalendar__c(Date__c = Date.today().addDays(2), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc3 = new OlympusCalendar__c(Date__c = Date.today().addDays(3), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc4 = new OlympusCalendar__c(Date__c = Date.today().addDays(4), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc5 = new OlympusCalendar__c(Date__c = Date.today().addDays(5), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc6 = new OlympusCalendar__c(Date__c = Date.today().addDays(6), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc7 = new OlympusCalendar__c(Date__c = Date.today().addDays(7), ChangeToHoliday__c=true, ChangeToWorkday__c=false);
+        OlympusCalendar__c oc8 = new OlympusCalendar__c(Date__c = Date.today().addDays(8), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc9 = new OlympusCalendar__c(Date__c = Date.today().addDays(9), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc10 = new OlympusCalendar__c(Date__c = Date.today().addDays(10), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc11 = new OlympusCalendar__c(Date__c = Date.today().addDays(11), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+        OlympusCalendar__c oc12 = new OlympusCalendar__c(Date__c = Date.today().addDays(12), ChangeToHoliday__c=false, ChangeToWorkday__c=true);
+
+        insert new OlympusCalendar__c[] {oc1,oc2,oc3,oc4,oc5,oc6,oc7,oc8,oc9,oc10,oc11,oc12};
+		List<RecordType> rectLo = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];   
+       	List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer IE'];
+        // 鏂板缓澶囧搧鍊熷嚭鐢宠
+        loaner_application__c loaner = new loaner_application__c();
+        loaner.Name = 'TEST';
+        loaner.RecordTypeId = rectLo[0].id;
+        loaner.EC_CODE_1__C = 'DV2-CAMELEONS-CUBE';
+        loaner.DEMO_PURPOSE__C = '婕旂ず';
+        loaner.Request_shipping_Date__c = Date.today().addDays(10);
+        loaner.Request_return_Date__c = Date.today().addDays(10);
+        loaner.Status__c = '宸叉彁浜�';
+        loaner.Return_Track_Company__c = '鐗╂祦鍏徃';
+        loaner.Loaner_receive_staff__c = '1';
+        loaner.direct_shippment_address__c = '1';
+        loaner.Loaner_receive_staff_phone__c = '1';
+        loaner.Post_Code__c = '1';
+        //loaner.pickup_time__c = Date.today().addDays(3);
+        //loaner.Return_Trake_Staff__c = '杩斿搧浜�';
+        insert loaner;
+        // 鏂板缓 瀹㈡埛
+        Account acc = new Account();
+        acc.RecordTypeId = rectCo[0].Id;
+        acc.Name         = '瀹㈡埛銉嗐偣銉�1';
+        acc.DivisionName__c = 'DivisionName__c';
+        acc.FacilityName__c = 'FacilityName__c';
+        acc.PostCode__c='000000';
+        insert acc;
+
+        List<Asset> In_asset = new List<Asset>();
+
+        Asset asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�1';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        asset.Status = '鍦ㄥ簱';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�2';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        asset = new Asset();
+        asset.Name = '銉嗐偣銉堟鍣�3';
+        asset.AccountId = acc.Id;
+        asset.SerialNumber = 'testserial';
+        In_asset.add(asset);
+
+        insert In_asset;
+
+
+        // 鏂板缓 鍊熷嚭鏄庣粏
+        List<loaner_application_detail__c> In_detail = new List<loaner_application_detail__c>();
+        loaner_application_detail__c detail = new loaner_application_detail__c();
+
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[0].id;
+        detail.name = '000';
+        detail.RAESD_STATUS__C = '宸插垎閰�';
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[1].id;
+        detail.name = '111';
+        detail.RAESD_STATUS__C = '宸插垎閰�';
+		//detail.Shipment_Request_Date__c = Date.today();
+        In_detail.add(detail);
+
+        detail = new loaner_application_detail__c();
+        detail.loaner_application__c = loaner.Id;
+        detail.loaner__c = In_asset[2].id;
+        detail.name = '222';
+        detail.RAESD_STATUS__C = '宸插垎閰�';
+        In_detail.add(detail);
+
+        insert In_detail;
+System.Test.startTest();
+        loaner.Status__c  = '鐢宠涓�';
+        loaner.Rental_End_Date__c = Date.today().addDays(10);
+        update loaner;
+
+        loaner.Status__c = '椹冲洖';
+        update loaner;
+
+		loaner.Status__c  = '鐢宠涓�';
+        loaner.Rental_End_Date__c = Date.today().addDays(10);
+        update loaner;
+
+        loaner.Status__c = '閿�鍞媴褰撴壒鍑�';
+        update loaner;
+
+        loaner.Status__c = '宸叉壒鍑�';
+        loaner.Rental_Start_Date__c = Date.today().addDays(9);
+        loaner.Rental_End_Date__c = Date.today().addDays(10);
+        update loaner;
+
+        loaner.Status__c = '鍙栨秷';
+        update loaner;
+System.Test.stopTest();
+	}
+	
+}
\ No newline at end of file
diff --git a/scr/classes/loanerAppTriggerHandlerTest.cls-meta.xml b/scr/classes/loanerAppTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..38aa015
--- /dev/null
+++ b/scr/classes/loanerAppTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/loanerChangeRecordTriggerHandler.cls b/scr/classes/loanerChangeRecordTriggerHandler.cls
new file mode 100644
index 0000000..e819296
--- /dev/null
+++ b/scr/classes/loanerChangeRecordTriggerHandler.cls
@@ -0,0 +1,33 @@
+public without sharing class loanerChangeRecordTriggerHandler {
+
+ public static void SetAssetStatus(List<LoanerChangeRecord__c> newList, Map<Id, LoanerChangeRecord__c> newMap, List<LoanerChangeRecord__c> oldList, Map<Id, LoanerChangeRecord__c> oldMap) {
+        List<Asset> updList = new List<Asset>();
+        Map<String, String> updMap = new Map<String, String>();       
+        for (LoanerChangeRecord__c newLoachange : newList){
+            LoanerChangeRecord__c oldLoachange = oldMap == null ? new LoanerChangeRecord__c() : oldMap.get(newLoachange.Id);
+            if (newLoachange.ApproveIndex__c == true && newLoachange.ApproveIndex__c != oldLoachange.ApproveIndex__c){
+                Asset as1 = new Asset();
+                as1.Id = newLoachange.Loanerid__c;
+                as1.Status = newLoachange.ChangeToStatus__c;
+                updList.add(as1);
+            }
+            
+            else if (newLoachange.RequestIndex__c == true && newLoachange.RequestIndex__c != oldLoachange.RequestIndex__c){
+                Asset as1 = new Asset();
+                as1.Id = newLoachange.Loanerid__c;
+                as1.Status = '寮傚姩鐢宠涓�';
+                updList.add(as1);
+            }  
+            
+            else if (newLoachange.RequestIndex__c == false && newLoachange.RequestIndex__c != oldLoachange.RequestIndex__c){
+                Asset as1 = new Asset();
+                as1.Id = newLoachange.Loanerid__c;
+                as1.Status = newLoachange.LoanerStatus__c;
+                updList.add(as1);
+            }
+             
+        }
+        if (updList.size() > 0) update updList;
+    }
+    
+}
\ No newline at end of file
diff --git a/scr/classes/loanerChangeRecordTriggerHandler.cls-meta.xml b/scr/classes/loanerChangeRecordTriggerHandler.cls-meta.xml
new file mode 100644
index 0000000..45aa0a0
--- /dev/null
+++ b/scr/classes/loanerChangeRecordTriggerHandler.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>44.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/loanerChangeRecordTriggerHandlerTest.cls b/scr/classes/loanerChangeRecordTriggerHandlerTest.cls
new file mode 100644
index 0000000..90e38a1
--- /dev/null
+++ b/scr/classes/loanerChangeRecordTriggerHandlerTest.cls
@@ -0,0 +1,119 @@
+@isTest
+private class loanerChangeRecordTriggerHandlerTest {
+
+    static Product2 prd1;
+    static Product2 prd2;
+    static Account acc;
+    static Account dealer;
+    static Contact core;
+    static User testUser;
+    static Asset asset;
+    static Asset assetC1;
+    static Asset assetC2;
+ static void setupTestData() {   
+     List<RecordType> dealerIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        if (dealerIE.size() == 0) {
+            return;
+        }
+        List<RecordType> olyCompany = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'OlympusCompany'];
+        if (olyCompany.size() == 0) {
+            return;
+        }
+
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_number = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_鏁伴噺绠$悊'];
+        if (loa_number.size() == 0) {
+            return;
+        }
+ 
+     //浠g悊鍟嗙敤鎴�
+        List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+        Profile prof = [select Id from Profile where Name ='SSBG DEALER IE'];
+        dealer = new Account();
+        dealer.Name = 'test dealer';
+        dealer.RecordTypeId = rectDealer[0].Id;
+        dealer.ProductSegment__c = 'IE';
+        dealer.PostCode__c='000000';
+        insert dealer;
+        core = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',accountid=dealer.id);
+        insert core;
+        testUser = New User(ContactId = core.id,Alias = 'newUser',Email='newuser@testorg.com',EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='zh_CN',LocaleSidKey='zh_CN', ProfileId = prof.Id,TimeZoneSidKey='Asia/Shanghai', UserName='testUser01@prectech.com');
+        insert testUser;
+
+        //鏍锋満瀹㈡埛
+        acc = new Account();
+        acc.Name = 'test dealer';
+        acc.RecordTypeId = olyCompany[0].Id;
+        acc.ProductSegment__c = 'IE';
+        acc.PostCode__c='000000';
+        insert acc;
+
+    // 浜у搧
+        prd1 = new Product2();
+        prd1.Product_ECCode__c      = 'testSBG001';
+        prd1.ProductCode            = 'testSBG001';
+        prd1.Name                   = 'testSBG001';
+        prd1.IsActive               = true;
+
+        prd2 = new Product2();
+        prd2.Product_ECCode__c      = 'testSBG002';
+        prd2.ProductCode            = 'testSBG002';
+        prd2.Name                   = 'testSBG002';
+        prd2.IsActive               = true;
+        insert new Product2[] {prd1, prd2};
+
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        assetC1 = new Asset();
+        assetC1.RecordTypeId = loa_individual[0].Id;
+        assetC1.SerialNumber = 'assetC1';
+        assetC1.Name = 'assetC1';
+        assetC1.AccountId = acc.Id;
+        assetC1.Product2Id = prd1.Id;
+        assetC1.Quantity = 1;
+        assetC1.Status = '鍦ㄥ簱';
+        assetC1.Equipment_Type__c = 'IE';
+        assetC1.loaner_place__c = '鍖椾含閰掍粰妗�';
+        assetC1.Remarks2__c = 'assetC1';
+        
+        // 淇濇湁璁惧 (涓綋绠$悊)
+        assetC2 = new Asset();
+        assetC2.RecordTypeId = loa_individual[0].Id;
+        assetC2.SerialNumber = 'assetC2';
+        assetC2.Name = 'assetC2';
+        assetC2.AccountId = acc.Id;
+        assetC2.Product2Id = prd2.Id;
+        assetC2.Quantity = 1;
+        assetC2.Status = '鍦ㄥ簱';
+        assetC2.Equipment_Type__c = 'IE';
+        assetC2.loaner_place__c = '鍖椾含閰掍粰妗�';
+        insert new Asset[] {assetC2,assetC1};
+        
+ }       
+     @isTest static void test_method_one() { 
+     
+    setupTestData();
+
+    List<RecordType> rectLapp = [select Id from RecordType where IsActive = true and SobjectType = 'loaner_application__c' and Name = 'IE'];
+        if (rectLapp.size() == 0) {
+            return;
+        }
+        List<RecordType> loa_individual = [select Id from RecordType where IsActive = true and SobjectType = 'Asset' and Name = '鏍锋満_涓綋绠$悊'];
+        if (loa_individual.size() == 0) {
+            return;
+        }
+   
+     // Implement test code
+    LoanerChangeRecord__c cr1 = new LoanerChangeRecord__c();
+        cr1.Loaner__c = assetC1.Id;
+        cr1.LoanerStatus__c = '鍦ㄥ簱';
+        cr1.ChangeToStatus__c = '鍐荤粨';
+        cr1.ChangeReason__c = 'test1';
+        insert cr1;
+     }  
+        
+        
+        
+    }
\ No newline at end of file
diff --git a/scr/classes/loanerChangeRecordTriggerHandlerTest.cls-meta.xml b/scr/classes/loanerChangeRecordTriggerHandlerTest.cls-meta.xml
new file mode 100644
index 0000000..45aa0a0
--- /dev/null
+++ b/scr/classes/loanerChangeRecordTriggerHandlerTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>44.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/oppbatch.cls b/scr/classes/oppbatch.cls
new file mode 100644
index 0000000..b846113
--- /dev/null
+++ b/scr/classes/oppbatch.cls
@@ -0,0 +1,234 @@
+global class oppbatch implements Database.Batchable<sObject> {
+    public String query;
+
+    global oppbatch() {
+        
+    }
+
+    global oppbatch(String str) {
+        this.query = str;
+    }
+
+
+    global Database.QueryLocator start(Database.BatchableContext bc) {
+        if(query == null || query  == ''){
+            return Database.getQueryLocator([select id,SyncedQuoteId from Opportunity ]);
+
+        }else{
+            return Database.getQueryLocator([select id,SyncedQuoteId from Opportunity where id =:query]);
+        }
+    }
+
+    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
+
+        List<String> targetList = new List<String>();
+        List<Opportunity> oppList = new List<Opportunity>();
+        for(SObject s : scope){
+            Opportunity opp = (Opportunity) s;
+            oppList.add(opp);
+            targetList.add(opp.id);
+        }
+
+        List<OpportunityLineItem> oliList = [select Id, ProductCode, ECCode__c, Quantity, OpportunityId, Opportunity.Amount from OpportunityLineItem where OpportunityId = :targetList order by OpportunityId, Id];
+            Map<String, String> itemMap = new Map<String, String>();
+           
+            for (OpportunityLineItem oli : oliList) {
+                if (itemMap.containsKey(oli.OpportunityId) == false) {
+                    itemMap.put(oli.OpportunityId, oli.ProductCode + '|' + oli.Quantity);
+                   
+                } else {
+                    String tmp = itemMap.get(oli.OpportunityId);
+                    itemMap.put(oli.OpportunityId, tmp + ',\r\n' + oli.ProductCode + '|' + oli.Quantity);
+                }
+            }
+
+
+            for (Opportunity newOpp : oppList) {
+                //Opportunity oldOpp = oldMap.get(newOpp.Id);
+                if (newOpp.SyncedQuoteId == null) {
+                    newOpp.OpportunityLineItemOT_text__c = itemMap.get(newOpp.Id);
+                }
+            }
+
+            if(oppList.size() > 0){
+                update oppList;
+            }
+    }
+
+    global void finish(Database.BatchableContext BC) {
+
+    }
+
+    public static void come(){
+        Integer i = 1;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+        i++;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/oppbatch.cls-meta.xml b/scr/classes/oppbatch.cls-meta.xml
new file mode 100644
index 0000000..91b23b8
--- /dev/null
+++ b/scr/classes/oppbatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>46.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/oppbatchTest.cls b/scr/classes/oppbatchTest.cls
new file mode 100644
index 0000000..cd1b3ab
--- /dev/null
+++ b/scr/classes/oppbatchTest.cls
@@ -0,0 +1,6 @@
+@isTest
+private class oppbatchTest {
+    static testMethod void testMethod1() {
+        oppbatch.come();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/oppbatchTest.cls-meta.xml b/scr/classes/oppbatchTest.cls-meta.xml
new file mode 100644
index 0000000..91b23b8
--- /dev/null
+++ b/scr/classes/oppbatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>46.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/setOrderShareBatch.cls b/scr/classes/setOrderShareBatch.cls
new file mode 100644
index 0000000..9679a25
--- /dev/null
+++ b/scr/classes/setOrderShareBatch.cls
@@ -0,0 +1,171 @@
+global class setOrderShareBatch implements Database.Batchable<sObject>, Database.Stateful {
+    // public String query;
+    
+    public List<String> accountIdList;
+    public Boolean sharedFlag = false;
+    public Integer total = 0;
+    public Map<String,String> accountIdMap = new Map<String,String>(); 
+    public Integer accounttotal = 0;
+    global setOrderShareBatch() {
+
+    }
+    global setOrderShareBatch(Boolean sharedFlag) {
+        this.sharedFlag = sharedFlag;
+    }
+
+    global setOrderShareBatch(List<String> accountIdList) {
+        this.accountIdList = accountIdList;
+    }
+
+    global Database.QueryLocator start(Database.BatchableContext bc) {
+
+        if (accountIdList != null && accountIdList.size() > 0) {
+            return Database.getQueryLocator([SELECT Id,OwnerId,Owner.IsActive,AccountId FROM  order WHERE AccountId IN:accountIdList order by createdDate ]);    
+        } else if (sharedFlag) {
+            return Database.getQueryLocator([SELECT Id,OwnerId,Owner.IsActive,AccountId FROM  order WHERE SharedFlag__c = true order by createdDate ]);  
+        } else {
+            return Database.getQueryLocator([SELECT Id,OwnerId,Owner.IsActive,AccountId FROM  order order by createdDate ]);  
+        }
+        
+    }
+
+    global void execute(Database.BatchableContext BC, List<Order> orderList) {
+
+        // 鑾峰彇鍚堝悓涓婂鎴峰悕Id 
+        Set<Id> accountIdSet = new Set<Id>();
+        for(Order order:orderList){
+            String accountId = order.AccountId;
+            if (!accountIdMap.containsKey(accountId)) {
+                accountIdSet.add(order.AccountId);
+                accountIdMap.put(accountId,accountId);    
+            }
+            accounttotal++;
+            
+        }
+
+        // 1.鏍规嵁瀹㈡埛Id锛屾煡鎵惧叧鑱旂殑鎵�鏈夊悎鍚�
+        List<Order> getOrderList = [SELECT Id,OwnerId,Owner.IsActive,AccountId 
+                                        FROM  order 
+                                        WHERE AccountId IN:accountIdSet ORDER BY AccountId];
+        // 瀹㈡埛Id 鍚堝悓鎵�鏈変汉Id 鍚堝悓鎵�鏈変汉瀵瑰簲鐨勫叏閮ㄥ悎鍚孖d闆嗗悎
+        Map<Id,Map<Id,List<Id>>> accountId_orderOwnerId_orderIdMap = new Map<Id,Map<Id,List<Id>>>();
+        for (Order order:getOrderList ) {
+            String accountId = order.AccountId;
+            
+            // 鍚堝悓鎵�鏈変汉 浠栧悕涓嬬殑鍚堝悓Id闆嗗悎
+            Map<Id,List<Id>> orderOwnerId_orderIdMap = new Map<Id,List<Id>>();
+            if (accountId_orderOwnerId_orderIdMap.containsKey(accountId)) {
+                orderOwnerId_orderIdMap = accountId_orderOwnerId_orderIdMap.get(accountId);
+            }
+
+            List<Id> orderIdList = new List<Id>();
+            String orderOwnerId = order.OwnerId;
+            if (orderOwnerId_orderIdMap.containsKey(orderOwnerId)) {
+                orderIdList = orderOwnerId_orderIdMap.get(orderOwnerId);
+            }
+            orderIdList.add(order.Id);
+
+ 
+            orderOwnerId_orderIdMap.put(orderOwnerId, orderIdList);
+            // 瀹㈡埛涓� 鍚堝悓鎵�鏈変汉涓庡悎鍚孖d
+            accountId_orderOwnerId_orderIdMap.put(accountId, orderOwnerId_orderIdMap);
+            
+        }
+        // 鏍规嵁瀹㈡埛Id锛屾煡鎵惧鎴蜂笅 瀹㈡埛鍥㈤槦鐢ㄦ埛 
+        List<AccountTeamMember> accountTeamMemberList = new List<AccountTeamMember>();
+        accountTeamMemberList = [SELECT Id, AccountId, UserId, user.IsActive  
+                                    FROM AccountTeamMember 
+                                    WHERE user.IsActive = true 
+                                        AND AccountId IN:accountIdSet ORDER BY AccountId];
+
+        // 鎺掗櫎 鍚堝悓鎵�鏈変汉鍚� 灏嗗悎鍚屽叡浜粰鏈夋晥鐨勭敤鎴�
+        if (accountTeamMemberList.size() > 0) {
+
+            Map<String,OrderShare> orderShareMap = new Map<String,OrderShare>();
+            for (AccountTeamMember atm:accountTeamMemberList ) {
+                // 
+                String accountId = atm.AccountId;
+                String userId = atm.UserId;
+                if (accountId_orderOwnerId_orderIdMap.containsKey(accountId)) {
+                    Map<Id,List<Id>> orderOwnerId_orderIdMap = accountId_orderOwnerId_orderIdMap.get(accountId);
+
+                    for (Id orderOwnerId : orderOwnerId_orderIdMap.keySet()) {
+                        
+                        if (userId != orderOwnerId) {
+                            for (Id orderId:orderOwnerId_orderIdMap.get(orderOwnerId) ) {
+                                String kv =  orderId+'_' +userId;
+                                OrderShare aos = new OrderShare(
+                                    RowCause = 'Manual',
+                                    orderId = orderId,
+                                    UserOrGroupId = userId,
+                                    OrderAccessLevel = 'Edit');
+                                orderShareMap.put(kv, aos);
+                            }
+                        }
+                    }
+                }
+            }
+
+            Savepoint sp = Database.setSavepoint();
+            try {
+                if (orderShareMap.size() > 0) {
+                    insert orderShareMap.values();
+                }  
+                if(Test.isRunningTest()){
+                    Integer num = Integer.valueOf('TestError');
+                }
+            } catch (Exception ex) {
+                Database.rollback(sp);
+                BatchIF_Log__c iflog = new BatchIF_Log__c();
+                iflog.Type__c = 'OrderShare';
+                String datetimeStr = String.valueOf(Datetime.now()).replace('-','').replace(' ','').replace(':','');
+                iflog.MessageGroupNumber__c = datetimeStr;
+                iflog.Log__c = 'Account Id \n';
+                for (Id accountId :accountIdSet ) {
+                    iflog.Log__c += accountId +',\n';
+                }
+                
+                iflog.ErrorLog__c = '';
+                insert iflog;
+            }
+            total += orderShareMap.size();
+           
+        }
+        try {
+            update orderList;
+
+            if(Test.isRunningTest()){
+                Integer num = Integer.valueOf('TestError');
+            }
+        } catch (Exception ex) {
+
+                BatchIF_Log__c iflog = new BatchIF_Log__c();
+                iflog.Type__c = 'OrderShare';
+                String datetimeStr = String.valueOf(Datetime.now()).replace('-','').replace(' ','').replace(':','');
+                iflog.MessageGroupNumber__c = datetimeStr;
+                iflog.Log__c = 'Order Id \n';
+                for (order orderId :orderList ) {
+                    iflog.Log__c += orderId +',\n';
+                }
+                
+                iflog.ErrorLog__c = '';
+                insert iflog;
+            }
+    }
+
+    global void finish(Database.BatchableContext BC) {
+        System.debug('accountIdMap--->'+accountIdMap);
+        System.debug('total--->'+total);
+
+        BatchIF_Log__c iflog = new BatchIF_Log__c();
+        iflog.Type__c = 'OrderShare';
+        String datetimeStr = String.valueOf(Datetime.now()).replace('-','').replace(' ','').replace(':','');
+        iflog.MessageGroupNumber__c = datetimeStr;
+        iflog.Log__c = 'Account Count \n';
+        iflog.Log__c += accountIdMap.size() +'\n';
+        iflog.Log__c += 'OrderShare Count \n';
+        iflog.Log__c += total +'\n';
+        iflog.ErrorLog__c = '';
+        insert iflog;
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/setOrderShareBatch.cls-meta.xml b/scr/classes/setOrderShareBatch.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/setOrderShareBatch.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/setOrderShareBatchSchedule.cls b/scr/classes/setOrderShareBatchSchedule.cls
new file mode 100644
index 0000000..69b2b59
--- /dev/null
+++ b/scr/classes/setOrderShareBatchSchedule.cls
@@ -0,0 +1,5 @@
+global class setOrderShareBatchSchedule implements Schedulable {
+    global void execute(SchedulableContext SC) {
+            Id execBTId = Database.executeBatch(new setOrderShareBatch(), 1);
+        }
+}
\ No newline at end of file
diff --git a/scr/classes/setOrderShareBatchSchedule.cls-meta.xml b/scr/classes/setOrderShareBatchSchedule.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/setOrderShareBatchSchedule.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/setOrderShareBatchTest.cls b/scr/classes/setOrderShareBatchTest.cls
new file mode 100644
index 0000000..568f290
--- /dev/null
+++ b/scr/classes/setOrderShareBatchTest.cls
@@ -0,0 +1,272 @@
+@isTest
+private class setOrderShareBatchTest {
+    static testMethod void testMethod1() {
+        Id pricebookId = Test.getStandardPricebookId();
+        Pricebook2 pricebook = new Pricebook2(
+            Name = 'IE',
+            ProductSegment__c = 'IE',
+            TradeType__c = 'Taxation',
+            SalesChannel__c = 'direct',
+            MachineParts__c = 'Machine',
+            isActive = true
+        );
+        insert pricebook;
+        Product2 product1 = new Product2();
+        product1.Name = 'product1';
+        Product2 product2 = new Product2();
+        product2.Name = 'product2';
+        Product2 product3 = new Product2();
+        product3.Name = 'product3';
+        insert new Product2[] {product1,product2,product3};
+        PricebookEntry standardPrice1 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product1.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        PricebookEntry standardPrice2 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product2.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        PricebookEntry standardPrice3 = new PricebookEntry(
+            Pricebook2Id = pricebookId,
+            Product2Id = product3.Id,
+            UnitPrice = 0,
+            IsActive = true,
+            CurrencyIsoCode = 'CNY'
+        );
+        insert new PricebookEntry[] {standardPrice1,standardPrice2,standardPrice3};
+        PricebookEntry entry1 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product1.Id);
+        entry1.UnitPrice = 0;
+        entry1.IsActive = true;
+        entry1.UseStandardPrice = false;
+        entry1.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry2 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product2.Id);
+        entry2.UnitPrice = 0;
+        entry2.IsActive = true;
+        entry2.UseStandardPrice = false;
+        entry2.CurrencyIsoCode = 'CNY';
+        PricebookEntry entry3 = new PricebookEntry( Pricebook2Id=pricebook.Id, Product2Id=product3.Id);
+        entry3.UnitPrice = 0;
+        entry3.IsActive = true;
+        entry3.UseStandardPrice = false;
+        entry3.CurrencyIsoCode = 'CNY';
+        insert new PricebookEntry[] {entry1,entry2,entry3};
+        List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+        Account accIE = new Account(
+            Name = '*',
+            RecordTypeId = rectIE[0].Id,
+            OwnerId = UserInfo.getUserId(),
+            DivisionName__c='Customer IE',
+            FacilityName__c='abc',
+            PostCode__c = '123456',
+            DummyDealer__c = true
+        );
+        insert accIE; 
+         List<RecordType> rectDealer = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Dealer'];
+    //    List<RecordType> rectIE = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = 'Customer BS'];
+
+        Account buyer = new Account(
+            Name = '*',
+            FacilityName__c = 'buyer',
+            PostCode__c = '123456',
+            RecordTypeId = rectDealer[0].Id,
+            ProductSegment__c = 'BS',
+            DummyDealer__c = true
+        );
+
+        Contact con = new Contact();
+        con.LastName = 'test';
+        con.AccountId = accIE.Id;
+        con.MobilePhone = 'MobilePhoneD__c';
+        con.OtherPhone = 'OtherPhoneD__c';
+        con.Fax = 'FaxD__c';
+        con.Email = 'EmailD__c@test.com';
+        con.Phone = 'PhoneD__c';
+        con.Title = 'TitleD__c';
+        con.Address1__c = 'Address1D__c';
+        con.Address2__c = 'Address2D__c';
+        con.Address3__c = 'Address3D__c';
+        con.Postcode__c = '100111';
+        con.ContactStatus__c = 'ContactStatusD__c';
+        con.CancelReason__c = 'CancelReasonD__c';
+        con.StatusD__c = 'Pass';
+
+        insert con;
+        Date day1 = Date.today();
+        List<RecordType> rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity'];
+        // 鏈夐瀹氫笅鍗曟棩
+        Opportunity opp = new Opportunity();
+        opp.Name = 'test opp';
+        opp.AccountId = accIE.Id;
+        opp.Dealer__c = buyer.Id;
+        opp.RecordTypeId = rectOpp[0].Id;
+        opp.OwnerId = UserInfo.getUserId();
+        opp.StageName = 'Phase3';
+        opp.CurrencyIsoCode = 'CNY';
+        opp.ProductSegment__c = 'IE';
+        opp.CloseDate = Date.today();
+        opp.NewInquiryDate__c = Date.today().addDays(-2);
+        opp.ExpectedOrderDate__c = Date.today().addDays(2);
+        opp.ApprovalStatus_D__c = 'Pass';
+        opp.LeadSource = 'LeadSource_D__c';
+        opp.BudgetAmount__c = 111;
+        opp.CancelReasonText__c = 'Cancel_Reason_Text_D__c';
+        opp.CancelReason__c = 'Cancel_reason_D__c';
+        opp.CompetitorCompany__c = 'Competitor_Company_D__c';
+        opp.Competitor_Product__c = 'Competitor_Product_D__c';
+        opp.Competitor_Product2__c = 'Competitor_Product2_D__c';
+        opp.Competitor_Product3__c = 'Competitor_Product3_D__c';
+        opp.Competitor_Product4__c = 'Competitor_Product4_D__c';
+        opp.Competitor_Product5__c = 'Competitor_Product5_D__c';
+        opp.Competitor_Product6__c = 'Competitor_Product6_D__c';
+        opp.Competitor_Product7__c = 'Competitor_Product7_D__c';
+        opp.Competitor_Product8__c = 'Competitor_Product8_D__c';
+        opp.CompetitorProductCode__c = 'Competitor_Product_Code_D__c';
+        opp.CompetitorProductCode2__c = 'Competitor_Product_Code2_D__c';
+        opp.CompetitorProductCode3__c = 'Competitor_Product_Code3_D__c';
+        opp.CompetitorProductCode4__c = 'Competitor_Product_Code4_D__c';
+        opp.CompetitorProductCode5__c = 'Competitor_Product_Code5_D__c';
+        opp.CompetitorProductCode6__c = 'Competitor_Product_Code6_D__c';
+        opp.CompetitorProductCode7__c = 'Competitor_Product_Code7_D__c';
+        opp.CompetitorProductCode8__c = 'Competitor_Product_Code8_D__c';
+        opp.DealerSalesStaffName__c = 'Dealer_Sales_Staff_Name_D__c';
+        opp.DealerService__c = 'Dealer_Service_D__c';
+        opp.ExpectedDeliveryDate__c = day1;
+        opp.InquiryResult__c = 'InquiryResultD__c';
+        //opp.InquiryResultCancel__c = day1;
+        //opp.InquiryResultLost__c = day1;
+        opp.InquiryResultOrder__c = day1;
+        opp.LostAmount__c = 111;
+        opp.LostCompetitorProduct__c = 'Lost_competitor_product_D__c';
+        opp.LostReasonText__c = 'LostReasonText_D__c';
+        opp.LostReason__c = 'Lostreason_D__c';
+        opp.Phase1Date__c = day1;
+        opp.Phase2Date__c = day1;
+        opp.Phase3Date__c = day1;
+        opp.SalesChannel__c = 'Sales_Channel_D__c';
+        //opp.SalesChannel__c = 'direct';
+        //opp.Machine_Parts__c = 'Parts';
+
+        opp.SubDealer__c = 'Sub_Dealer_D__c';
+        opp.TradeType__c = 'Trade_Type_D__c';
+        //opp.Pricebook2Id = pricebook.Id;
+
+        insert opp;
+
+        OpportunityContactRole role = new OpportunityContactRole(
+            Role  = 'End user',
+            IsPrimary = true,
+            OpportunityId = opp.Id,
+            ContactId = con.Id
+            );
+        insert role;
+         Quote quo = new Quote(
+            Name = 'quo',
+            OpportunityId = opp.Id,
+            //Pricebook2Id = pricebook.Id,
+            SetName1__c = 'setname1',
+            SetQty1__c = 1,
+            SetName2__c = 'setname2',
+            SetQty2__c = 2,
+            Custom_Price_Total_Text__c = 1000
+            //IsSyncing = true
+        );
+        insert quo;
+
+        opp.SyncedQuoteId = quo.Id;
+        update opp;
+
+        List<productSet__c>  insertproductSets = new  List<productSet__c>();
+        productSet__c proSet1 = new productSet__c();
+        proSet1.Code__c = 'IXP-7P2';
+        proSet1.Name = 'IXP-7P2';
+        proSet1.IsValid__c = true;
+        proSet1.Name = 'IXP-7P2';
+        insertproductSets.add(proSet1);
+        productSet__c proSet2 = new productSet__c();
+        proSet2.Code__c = 'IXP-7P1SC';
+        proSet2.Name = 'IXP-7P1SC';
+        proSet2.IsValid__c = true;
+        proSet2.Name = 'IXP-7P1SC';
+        insertproductSets.add(proSet2);
+        productSet__c proSet3 = new productSet__c();
+        proSet3.Code__c = 'IXSP-T7LED';
+        proSet3.Name = 'IXSP-T7LED';
+        proSet3.IsValid__c = true;
+        proSet3.Name = 'IXSP-T7LED';
+        insertproductSets.add(proSet3);
+
+
+        insert insertproductSets;
+        User user = new User();
+        user.LastName = 'testAccount';
+        user.FirstName = 'test';
+        user.Alias = '2105';
+        user.Email = 'testAccount@test.com';
+        user.Username = 'testAccount@test222.com';
+        user.CommunityNickname = 'testAccount';
+        user.IsActive = true;
+        user.EmailEncodingKey = 'ISO-2022-JP';
+        user.TimeZoneSidKey = 'Asia/Tokyo';
+        user.LocaleSidKey = 'ja_JP';
+        user.LanguageLocaleKey = 'ja';
+        user.ProfileId = System.Label.SystemAdmin;
+        insert user;
+
+        AccountTeamMember atm = new AccountTeamMember();
+        atm.accountId = accIE.Id;
+        atm.userId = user.Id;//'005280000071H0s';
+        atm.teamMemberRole = 'Sales Manager';
+        atm.ACCOUNTACCESSLEVEL = 'Edit';
+        atm.CONTACTACCESSLEVEL = 'Edit';
+        atm.OPPORTUNITYACCESSLEVEL = 'None';
+        atm.CASEACCESSLEVEL = 'None';
+        upsert atm;
+
+        List<RecordType> rectOrder = [select id from RecordType where IsActive = true and SobjectType = 'Order'];
+        Order odr = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = '01228000000NJt6',
+            confirm__c = false,
+            SP_21__c = true,
+            EndUser__c = con.Id
+        );
+        insert odr;
+        Order odr1 = new Order(
+            Name = '',
+            Status = 'Draft',
+            AccountId = accIE.Id,
+            ApproveStatus__c = 'Draft',
+            OpportunityId = opp.Id,
+            EffectiveDate = Date.today(),
+            RecordTypeId = '01228000000NJt6',
+            confirm__c = false,
+            SP_21__c = true,
+            EndUser__c = con.Id
+        );
+        insert odr1;
+        List<String> orderIdList = new List<String>();
+        orderIdList.add(odr.Id);
+        database.executebatch(new setOrderShareBatch(),10);
+        database.executebatch(new setOrderShareBatch(true),10);
+        database.executebatch(new setOrderShareBatch(orderIdList),10);
+    }
+
+    @isTest static void test_method_one() {
+        String CRON_EXP = '0 0 0 3 9 ? 2022';
+        System.Test.startTest();
+        String jobId = system.schedule('setOrderShareBatchScheduleTest', CRON_EXP, new setOrderShareBatchSchedule());
+        
+        System.Test.StopTest();
+    }
+}
\ No newline at end of file
diff --git a/scr/classes/setOrderShareBatchTest.cls-meta.xml b/scr/classes/setOrderShareBatchTest.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/setOrderShareBatchTest.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/superSort.cls b/scr/classes/superSort.cls
new file mode 100644
index 0000000..5bf2bc2
--- /dev/null
+++ b/scr/classes/superSort.cls
@@ -0,0 +1,139 @@
+public class superSort {
+
+    /*This method takes 3 arguments, the List of objects to sort, the field to sort, 
+    and the order, asc or desc*/
+    
+    public static void sortList(List<sObject> items, String sortField, String order){
+        /*I must give credit where it is due as the sorting algorithm I am using is the 
+        one supplied by Andrew Waite here: http://blog.sforce.com/sforce/2008/09/sorting-collect.html */
+        
+        Boolean isSortFieldReference = false;
+        Map<Id,String> referenceName;
+         
+        /*Determine the type of the field that needs to be sorted, if it is a 
+        reference we will want sort by the name of the related object, not the 
+        ID itself*/
+        if(items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getType().Name() == 'REFERENCE'){
+            isSortFieldReference = true;
+            referenceName = new Map<Id,String>();
+            
+            /*Determine the type of this object and populate the Id to Name map*/
+            Set<Id> referenceIds = new Set<Id>();
+            for(sObject s : items){
+               referenceIds.add((Id)s.get(sortField));
+            }
+            
+            String objectID = (String)items[0].get(sortField);
+            String prefix = objectID.substring(0,3);
+            String objectType;
+            Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
+            for(Schema.SObjectType s : gd.values()){
+                if(prefix == s.getDescribe().getKeyPrefix()){
+                    objectType = s.getDescribe().Name;
+                }
+            }
+            
+            //Query the related objects for the name and populate the Id -> Name map
+            String queryString = 'select Id, Name from ' + objectType + ' where ID IN :referenceIDs';
+            for(sObject s : Database.query(queryString )){
+                referenceName.put((Id)s.get('Id'),(String)s.get('Name'));
+            }
+        }
+                
+        /*Declare a list that will contain the sorted results. I think this is one of the 
+        coolest parts of this method as the system will not let you declare a list of 
+        sObjects (List<sObject> objects = new List<sObjects>();) but using a 
+        wrapper class you can bypass this system limitation to create this type of list */
+        List<cObject> resultList = new List<cObject>();
+    
+        //Create a map that can be used for sorting 
+        Map<object, List<cObject>> objectMap = new Map<object, List<cObject>>();
+        
+        for(sObject ob : items){
+            if(isSortFieldReference == false){
+                if(objectMap.get(ob.get(sortField)) == null){ 
+                    objectMap.put(ob.get(sortField), new List<cObject>()); 
+                }
+                cObject o = new cObject(ob);
+                objectMap.get(ob.get(sortField)).add(o);
+            }else{
+                if(objectMap.get(referenceName.get((Id)ob.get(sortField))) == null){ 
+                    objectMap.put(referenceName.get((Id)ob.get(sortField)), new List<cObject>()); 
+                }
+                cObject o = new cObject(ob);
+                objectMap.get(referenceName.get((Id)ob.get(sortField))).add(o);
+            }
+        }
+        
+        //Sort the keys
+        List<object> keys = new List<object>(objectMap.keySet());
+        keys.sort();
+        
+        for(object key : keys){ 
+            resultList.addAll(objectMap.get(key)); 
+        }
+        
+        //Apply the sorted values to the source list
+        items.clear();
+        if(order.toLowerCase() == 'asc'){
+            for(cObject ob : resultList){
+                items.add(ob.obj);  
+            }
+        }else if(order.toLowerCase() == 'desc'){
+            for(integer i = resultList.size()-1; i >= 0; i--){
+                items.add(resultList[i].obj);   
+            }
+        }
+    }
+    
+    public class cObject{
+        sObject obj {get; set;}
+        
+        public cObject(sObject obj){
+            this.obj = obj; 
+        }
+    }
+    
+    /*Some test methods that provide 100% coverage 
+    public static testMethod void sortAscendingTest(){
+        
+        List<Opportunity> opps = new List<Opportunity>();
+        for(integer i = 0; i<1000; i++){
+            opps.add(new Opportunity(Name = 'test' + i, Amount = 1000 * Math.random()));
+        }
+        
+        Test.startTest();
+        Long start = system.currentTimeMillis();
+        sortList(opps,'Amount','asc');
+        system.debug(system.currentTimeMillis() - start);
+        Test.stopTest();
+        
+        //Assert the list was sorted correctly
+        Decimal assertValue = -1;
+        for(Opportunity o : opps) {
+            System.debug('Opp value: ' + o.amount);
+            System.assert(assertValue <= o.amount);
+            assertValue = o.amount;
+        }  
+    }
+    
+    public static testMethod void sortDescendingTest(){
+        
+        List<Opportunity> opps = new List<Opportunity>();
+        for(integer i = 0; i<1000; i++){
+            opps.add(new Opportunity(Name = 'test' + i, Amount = 1000 * Math.random()));
+        }
+        
+        Test.startTest();
+        sortList(opps,'Amount','desc');
+        Test.stopTest();
+        
+        //Assert the list was sorted correctly
+        Decimal assertValue = 1001;
+        for(Opportunity o : opps) {
+            System.debug('Opp value: ' + o.amount);
+            System.assert(assertValue >= o.amount);
+            assertValue = o.amount;
+        }  
+    }*/
+}
\ No newline at end of file
diff --git a/scr/classes/superSort.cls-meta.xml b/scr/classes/superSort.cls-meta.xml
new file mode 100644
index 0000000..6dc8b22
--- /dev/null
+++ b/scr/classes/superSort.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/classes/test001Controller.cls b/scr/classes/test001Controller.cls
new file mode 100644
index 0000000..809250d
--- /dev/null
+++ b/scr/classes/test001Controller.cls
@@ -0,0 +1,9 @@
+public with sharing class test001Controller {
+    
+    public test001Controller() {
+        
+    }
+
+    
+
+}
\ No newline at end of file
diff --git a/scr/classes/test001Controller.cls-meta.xml b/scr/classes/test001Controller.cls-meta.xml
new file mode 100644
index 0000000..f3bac1f
--- /dev/null
+++ b/scr/classes/test001Controller.cls-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexClass>
diff --git a/scr/components/PDFWbr.component b/scr/components/PDFWbr.component
new file mode 100644
index 0000000..d2f1f2a
--- /dev/null
+++ b/scr/components/PDFWbr.component
@@ -0,0 +1,7 @@
+<apex:component access="global" controller="PDFWbrController" >
+    <apex:attribute name="targetStr" assignTo="{!tstr}" description="" type="String" required="false" />
+    <apex:repeat value="{!wbrStr}" var="s">
+        <apex:outputText value="{!s}"/>
+        <apex:outputPanel rendered="{!IF((s == '鍙�' && wbrFlag == true),true,false)}">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</apex:outputPanel><wbr/>
+    </apex:repeat>
+</apex:component>
\ No newline at end of file
diff --git a/scr/components/PDFWbr.component-meta.xml b/scr/components/PDFWbr.component-meta.xml
new file mode 100644
index 0000000..4597396
--- /dev/null
+++ b/scr/components/PDFWbr.component-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexComponent xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <label>PDFWbr</label>
+</ApexComponent>
diff --git a/scr/components/SiteFooter.component b/scr/components/SiteFooter.component
new file mode 100644
index 0000000..2023a51
--- /dev/null
+++ b/scr/components/SiteFooter.component
@@ -0,0 +1,3 @@
+<apex:component id="footerComponent">
+  <c:SitePoweredBy />
+</apex:component>
\ No newline at end of file
diff --git a/scr/components/SiteFooter.component-meta.xml b/scr/components/SiteFooter.component-meta.xml
new file mode 100644
index 0000000..3b013f9
--- /dev/null
+++ b/scr/components/SiteFooter.component-meta.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexComponent xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <description>榛樿 Force.com 绔欑偣椤佃剼缁勪欢</description>
+    <label>SiteFooter</label>
+</ApexComponent>
diff --git a/scr/components/SiteHeader.component b/scr/components/SiteHeader.component
new file mode 100644
index 0000000..3ebfbe7
--- /dev/null
+++ b/scr/components/SiteHeader.component
@@ -0,0 +1,15 @@
+<apex:component id="headerComponent">
+  <apex:panelGrid cellpadding="0" cellspacing="0" width="98%" border="0" columns="2" style="text-align: left;" id="theHeader">
+    <apex:image url="{!$Site.Prefix}/img/sites/force_logo.png" style="align: left;" alt="Salesforce" width="233" height="55" title="Salesforce"/>
+    <apex:panelGrid cellpadding="0" cellspacing="0" width="100%" border="0" columns="1" style="text-align: right;" id="Links">
+	  <apex:panelGroup rendered="{!AND(ISPICKVAL($User.UserType,'Guest'), $Site.LoginEnabled)}">
+		<apex:outputLink value="/site/SiteLogin.apexp">{!$Label.site.login_button}</apex:outputLink>
+		<apex:outputText value=" | "/>
+		<apex:outputLink value="/site/ForgotPassword.apexp">{!$Label.site.forgot_your_password_q}</apex:outputLink>
+		<apex:outputText value=" | " rendered="{!$Site.RegistrationEnabled}"/>
+		<apex:outputLink value="/site/SiteRegister.apexp" rendered="{!$Site.RegistrationEnabled}">{!$Label.site.new_user_q}</apex:outputLink>
+	  </apex:panelGroup>
+	  <apex:outputLink value="{!$Site.Prefix}/secur/logout.jsp" rendered="{!NOT(ISPICKVAL($User.UserType,'Guest'))}">{!$Label.site.logout}</apex:outputLink>
+    </apex:panelGrid>
+  </apex:panelGrid>
+</apex:component>
\ No newline at end of file
diff --git a/scr/components/SiteHeader.component-meta.xml b/scr/components/SiteHeader.component-meta.xml
new file mode 100644
index 0000000..28b0e7d
--- /dev/null
+++ b/scr/components/SiteHeader.component-meta.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexComponent xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <description>榛樿 Force.com 绔欑偣椤电湁缁勪欢</description>
+    <label>SiteHeader</label>
+</ApexComponent>
diff --git a/scr/components/SiteLogin.component b/scr/components/SiteLogin.component
new file mode 100644
index 0000000..ec891e0
--- /dev/null
+++ b/scr/components/SiteLogin.component
@@ -0,0 +1,23 @@
+<apex:component controller="SiteLoginController" id="loginComponent">
+  <apex:form id="loginForm" forceSSL="true">
+    <apex:outputPanel layout="block">
+      <apex:pageMessages id="error"/>
+      <apex:panelGrid columns="2" style="margin-top:1em;">
+        <apex:outputLabel value="{!$Label.site.username}" for="username"/>
+        <apex:inputText id="username" value="{!username}"/>
+        <apex:outputLabel value="{!$Label.site.password}" for="password"/>
+        <apex:inputSecret id="password" value="{!password}"/>
+        <apex:outputText value=""/>
+        <apex:commandButton action="{!login}" value="{!$Label.site.login_button}" id="loginButton"/>
+        <apex:outputText value=""/>
+        <apex:outputText value=""/>
+        <apex:outputText value=""/>
+        <apex:panelGroup id="theLinks">
+          <apex:outputLink value="{!$Page.ForgotPassword}"> {!$Label.site.forgot_your_password_q}</apex:outputLink>
+          <apex:outputText value=" | " rendered="{!$Site.RegistrationEnabled}" />
+          <apex:outputLink value="{!$Page.SiteRegister}" rendered="{!$Site.RegistrationEnabled}">{!$Label.site.new_user_q}</apex:outputLink>
+        </apex:panelGroup>
+      </apex:panelGrid> 
+    </apex:outputPanel>
+  </apex:form>
+</apex:component>
\ No newline at end of file
diff --git a/scr/components/SiteLogin.component-meta.xml b/scr/components/SiteLogin.component-meta.xml
new file mode 100644
index 0000000..1a19a4a
--- /dev/null
+++ b/scr/components/SiteLogin.component-meta.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexComponent xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <description>榛樿 Force.com 鐧诲綍缁勪欢</description>
+    <label>SiteLogin</label>
+</ApexComponent>
diff --git a/scr/components/SitePoweredBy.component b/scr/components/SitePoweredBy.component
new file mode 100644
index 0000000..52b3779
--- /dev/null
+++ b/scr/components/SitePoweredBy.component
@@ -0,0 +1,8 @@
+<apex:component id="poweredbyComponent">
+  <apex:panelGrid cellpadding="0" cellspacing="0" width="100%" border="0" style="text-align: right;" columns="1" id="thePoweredByTop">
+    <apex:panelGroup id="poweredBy">
+      <apex:outputText style="font-size: smaller" value="{!$Label.site.powered_by}"/>
+      <apex:outputLink value="http://www.force.com"><apex:image url="{!URLFOR($Resource.SiteSamples, 'img/poweredby.png')}" styleClass="poweredByImage"/></apex:outputLink>
+    </apex:panelGroup>
+   </apex:panelGrid>
+</apex:component>
\ No newline at end of file
diff --git a/scr/components/SitePoweredBy.component-meta.xml b/scr/components/SitePoweredBy.component-meta.xml
new file mode 100644
index 0000000..5529109
--- /dev/null
+++ b/scr/components/SitePoweredBy.component-meta.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexComponent xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <description>鍩轰簬缁勪欢鐨勯粯璁� Force.com 绔欑偣</description>
+    <label>SitePoweredBy</label>
+</ApexComponent>
diff --git a/scr/pages/AccountOpenAlert.page b/scr/pages/AccountOpenAlert.page
new file mode 100644
index 0000000..443b527
--- /dev/null
+++ b/scr/pages/AccountOpenAlert.page
@@ -0,0 +1,78 @@
+<apex:page standardController="Account" showHeader="false" sidebar="false">
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        var is_new = '{!Account.IsNew__c}' == 'true';
+        var approval_status = '{!Account.stautesD__c}';
+
+        if ('{!Account.DealerSelectOwner__c}' != '' && '{!Account.DealerSelectOwner__c}' != '{!Account.OwnerId}') {
+            var aid = "{!Account.Id}";
+            var oldo = "{!Account.OwnerId}";
+            var newo = "{!Account.DealerSelectOwner__c}";
+
+            var rs = sforce.apex.execute("AccountWebService", "UpdateShare", {accountId: aid, ownerOld: oldo, ownerNew: newo});
+            if (rs == '1') {
+                window.top.location.reload();
+            } else {
+                alert(rs);
+            }
+        } else {
+            var now_status = '{!Account.AccountStatus_IsChanged__c}' == 'true' || 
+                '{!Account.Address1_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI4_IsChanged__c}' == 'true' || 
+                '{!Account.CancelReason_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE7_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT7_IsChanged__c}' == 'true' || 
+                '{!Account.City_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI5_IsChanged__c}' == 'true' || 
+                '{!Account.English_Name_IsChanged__c}' == 'true' || 
+                '{!Account.Fax_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI2_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT4_IsChanged__c}' == 'true' || 
+                '{!Account.IndustryC_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI4_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI3_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE5_IsChanged__c}' == 'true' || 
+                '{!Account.AssetBS3_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE3_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI7_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT6_IsChanged__c}' == 'true' || 
+                '{!Account.Market_Verticals_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE6_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE2_IsChanged__c}' == 'true' || 
+                '{!Account.AssetBS2_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI3_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE1_IsChanged__c}' == 'true' || 
+                '{!Account.AssetBS1_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI1_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT1_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI1_IsChanged__c}' == 'true' || 
+                '{!Account.AssetBS5_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE8_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI8_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT8_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI8_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI5_IsChanged__c}' == 'true' || 
+                '{!Account.Phone_IsChanged__c}' == 'true' || 
+                '{!Account.Postcode_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI6_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI2_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT3_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT2_IsChanged__c}' == 'true' || 
+                '{!Account.AssetANI6_IsChanged__c}' == 'true' || 
+                '{!Account.Sub_Use_IsChanged__c}' == 'true' || 
+                '{!Account.Use_IsChanged__c}' == 'true' || 
+                '{!Account.AssetRVI7_IsChanged__c}' == 'true' || 
+                '{!Account.Website_IsChanged__c}' == 'true' || 
+                '{!Account.AssetBS4_IsChanged__c}' == 'true' || 
+                '{!Account.AssetIE4_IsChanged__c}' == 'true' || 
+                '{!Account.AssetNDT5_IsChanged__c}' == 'true' ||
+                '{!Account.FacilityName_IsChanged__c}' == 'true' || 
+                '{!Account.DivisionName_IsChanged__c}' == 'true' || 
+                '{!Account.DepartmentName_IsChanged__c}' == 'true' ;
+            if ((is_new || now_status) && approval_status != 'Submit') {
+                alert("鏂板缓鎴栦慨鏀瑰鎴蜂俊鎭悗锛岃鍙婃椂鎻愪氦瀹℃壒銆�");
+            }
+        }
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/AccountOpenAlert.page-meta.xml b/scr/pages/AccountOpenAlert.page-meta.xml
new file mode 100644
index 0000000..e26454f
--- /dev/null
+++ b/scr/pages/AccountOpenAlert.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>AccountOpenAlert</label>
+</ApexPage>
diff --git a/scr/pages/AllAsset.page b/scr/pages/AllAsset.page
new file mode 100644
index 0000000..476f31f
--- /dev/null
+++ b/scr/pages/AllAsset.page
@@ -0,0 +1,180 @@
+<apex:page Controller="AllAssetController" showHeader="false" sidebar="false" id="allPage" action="{!init}" >
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+	<script>
+		function searchProductJs() {
+		    blockme(); 
+		    searchLoanerApp();
+		}
+		function notArrDetJs(setid,deatilNo){
+		    blockme();
+		    getLoanerSetdet(setid);
+		    var productCount = j$(escapeVfId('loanerSetNo')).value();
+		    for (var i = 0; i < productCount; i++) {
+		        j$(escapeVfId('allPage:allForm:dataBlock0:loanerSetTable:' + i +':loanerSetNamelinK')).css('color', 'black');
+		    }
+		    j$(escapeVfId('allPage:allForm:dataBlock0:loanerSetTable:' + deatilNo +':loanerSetNamelinK')).css('color', 'red');
+		}
+		
+	</script>
+	<apex:form id="allForm">
+		<apex:outputPanel id="message">
+            <apex:pageMessages />
+        </apex:outputPanel>
+		<apex:actionFunction name="getLoanerSetdet" action="{!getLoanerSetdet}" rerender="dataBlock, message" onComplete="unblockUI();">
+	        <apex:param name="firstParam" assignTo="{!setId}" value="" />
+	    </apex:actionFunction>
+
+	    <apex:actionFunction name="searchLoanerApp" action="{!searchLoanerApp}" rerender="dataBlock, message" onComplete="unblockUI();overwriteRedJs();">
+	     </apex:actionFunction>
+	    <!-- 鎼滅储 -->
+		<apex:pageBlock id="searchBlock">
+	        <table style="border-collapse: collapse;table-layout:fixed; width:1200px" >
+	            <colgroup>
+	                <col width="8%"/>
+	                <col width="25%"/>
+	                <col width="9%"/>
+	                <col width="25%"/>
+	                <col width="8%"/>
+	                <col width="25%"/>
+	            </colgroup>
+	            <tr>
+	                <td align="right">鏈鸿韩鍙�</td>
+	                <td><apex:inputField value="{!rec.SerialNumber}" style="width:150px"/></td>
+	                <td align="right">{!$ObjectType.Asset.fields.EC_Code__c.label}</td>
+	                <td><apex:inputText value="{!assECcode}" style="width:150px"/></td>
+	                <td align="right">{!$ObjectType.Asset.fields.OT_Code__c.label}</td>
+	                <td><apex:inputText value="{!rec.OT_Code__c}" style="width:150px"/></td>
+	            </tr>
+	            <tr>
+	                <td align="right">{!$ObjectType.Asset.fields.Equipment_Type__c.label}</td>
+	                <td><apex:inputField value="{!rec.Equipment_Type__c}" style="width:150px"/></td>
+	                <td align="right">{!$ObjectType.Asset.fields.loaner_place__c.label}</td>
+	                <td><apex:inputField value="{!rec.loaner_place__c}" style="width:150px"/></td>
+	                <td align="right">{!$ObjectType.Asset.fields.Status.label}</td>
+	                <td><apex:inputField value="{!rec.Status}" style="width:150px"/></td>
+	            </tr>
+	            <tr>
+	                <td align="right" >鏍锋満鍚嶇О</td>
+	                <td><apex:inputText value="{!assName}" style="width:150px"/></td>
+	                <td align="right">{!$ObjectType.Asset.fields.Internal_Asset_number__c.label}</td>
+	                <td><apex:inputText value="{!rec.Internal_Asset_number__c}" style="width:150px"/></td>
+	                <td align="center"  ></td>
+	                <td ><apex:commandButton value="鎼滅储" style="width: 120px;" onclick="searchProductJs(); return false;" /></td>
+	            </tr>
+	        </table>
+	    </apex:pageBlock>
+	    <!-- 鏍锋満濂楄 -->
+	    <div style="position: relative;top:0;height:100%;overflow:hidden;overflow-y:auto;-webkit-overflow-scrolling: touch;">
+	        <input type="hidden" id="loanerSetNo" value="{!loanerSetNo}" />
+	        <apex:pageBlock id="dataBlock0" title="鏍锋満濂楄涓�瑙�">
+		        <div style="position: relative;top:0;height:150px;overflow:hidden;overflow-y:auto;-webkit-overflow-scrolling: touch;">
+		            <table class="list" border="0" cellpadding="0" cellspacing="0" id="example0">
+		                <tr class="headerRow">
+		                    <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Name.label}</th>
+	                        <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.SerialNumber__c.label}</th>
+	                        <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Internal_Asset_number__c.label}</th>
+	                        <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.status__c.label}</th>
+		                    <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Equipment_Type__c.label}</th>
+		                    <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.loaner_place__c.label}</th>
+                            <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Reservation_information__c.label}</th>
+		                </tr>
+		                <apex:repeat value="{!loanerSetRecords}" var="records" id="loanerSetTable">
+			                <tr class="dataRow">
+			                    <td class="dataCell" align="center">
+			                        <apex:outputLink onclick="notArrDetJs('{!records.lSet.Id}','{!records.deatilNo}'); return false;" id="loanerSetNamelinK" ><apex:outputField value="{!records.lSet.Name}" id="loanerSetName"/></apex:outputLink>
+			                    </td>		                   
+		                        <td class="dataCell" align="center">{!records.lSet.SerialNumber__c}</td>
+		                        <td class="dataCell" align="center">{!records.lSet.Internal_Asset_number__c}</td>
+		                        <td class="dataCell" align="center">{!records.lSet.status__c}</td>		                   
+			                    <td class="dataCell" align="center">{!records.lSet.Equipment_Type__c}</td>
+			                    <td class="dataCell" align="center">{!records.lSet.loaner_place__c}</td>
+                                <td class="dataCell" align="center">{!records.lSet.Reservation_information__c}</td>
+			                </tr>
+		                </apex:repeat>
+		            </table>
+		        </div>
+	        </apex:pageBlock>
+	    </div>
+
+	    <div style="position: relative;top:0;height:700px;overflow:hidden;overflow-y:auto;-webkit-overflow-scrolling: touch;">
+                <apex:pageBlock id="dataBlock">
+                <input type="hidden" id="pageRecordNo" value="{!pageRecordNo}" />
+                    <table class="list" border="0" cellpadding="0" cellspacing="0" id="example">
+                        <tr class="headerRow">
+                            <th style="text-align: center;">鏍锋満鍚嶇О</th> 
+                            <th style="text-align: center;">鏍锋満绫诲瀷</th> 
+                            <!-- <th style="text-align: center;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th> -->
+                            <th style="text-align: center;"><a href="#" onclick="sortTableJs('0');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</a></th>
+                            <!-- <th style="text-align: center;"><a href="#" onclick="sortTableJs('1');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</a></th> -->
+                            <th style="text-align: center;"><a href="#" onclick="sortTableJs('2');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</a></th>
+                            <th style="text-align: center;"><a href="#" onclick="sortTableJs('3');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.loaner_place__c.label}</a></th>
+                            <th style="text-align: center;width: 50Px;"><a href="#" onclick="sortTableJs('4');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.loaner_Status__c.label}</a></th>
+                            <th style="text-align: center;">鍊熺敤浠g悊鍟�</th>
+                            <th style="text-align: center;">鍊熷嚭寮�濮嬫棩</th>
+                            <th style="text-align: center;">鍊熷嚭缁撴潫鏃�</th>
+                            <th style="text-align: center;">鏁伴噺</th>
+                            <th style="text-align: center;">鎻忚堪</th>
+                            <th style="text-align: center;">{!$ObjectType.loaner_application_detail__c.fields.Remark__c.label}</th>
+                        </tr>
+                        <apex:repeat value="{!equipmentSetRecords}" var="records" id="equipmentSetTable">
+                        <tr class="dataRow">
+                            <td class="dataCell" align="center">
+                                 {!records.aset.Name}
+                            </td>
+                            <td class="dataCell" align="center">
+                                 {!records.aset.AssetType__c}
+                            </td>
+                           <!--  <td class="dataCell" align="center">
+                                 {!records.aset.Internal_Asset_number__c}
+                            </td> -->
+                            <td class="dataCell" align="center">
+                                {!records.aset.SerialNumber}
+                            </td>
+                           <!--  <td class="dataCell" align="center">
+                                {!records.aset.OT_Code__c}
+                            </td> -->
+                            <td class="dataCell" align="center">
+                                {!records.aset.EC_Code__c}
+                            </td>
+                            <td class="dataCell" align="center">
+                                {!records.aset.loaner_place__c}
+                            </td>
+                            <td class="dataCell" align="center">
+                                <apex:variable var="v" value="" rendered="{!!records.showNo}" > {!records.aset.Status}</apex:variable>
+                                <apex:variable var="v" value="" rendered="{!records.showNo}"> {!records.aset.Count_can_allocate_F__c} </apex:variable>
+                            </td>
+
+                            <td class="dataCell" align="center">
+                                {!records.aset.Rental_Customer__r.Name}
+                            </td>
+                            <td class="dataCell" align="center">
+                                {!records.aset.Rental_Start_Date__c}
+                            </td>
+                            <td class="dataCell" align="center">
+                                {!records.aset.Rental_End_Date__c}
+                            </td>
+
+                            <td class="dataCell" align="center">
+                            <apex:variable var="v" value="" rendered="{!!records.canInput}" ><apex:outputText id="ProductIdOut" value="{!records.deatilNo}"/> </apex:variable>
+                            <apex:variable var="v" id="ProductCountIn" value="" rendered="{!records.canInput}" ><apex:inputText id="ProductCount" value="{!records.deatilNo}" onblur="ComputePriceJs(this)" style="width: 50Px;text-align: right;"/>
+                            </apex:variable>
+                            </td>
+
+                            <td class="dataCell" align="center">
+                                {!records.aset.Description}
+                            </td>
+
+                            <td class="dataCell" align="center">
+                            <apex:inputText id="ProductCount" value="{!records.remark}" style="text-align: right;"/>
+                            </td>
+                           
+                        </tr>
+                        </apex:repeat>
+                    </table>
+                </apex:pageBlock>
+                </div>
+
+	</apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/AllAsset.page-meta.xml b/scr/pages/AllAsset.page-meta.xml
new file mode 100644
index 0000000..3f047c6
--- /dev/null
+++ b/scr/pages/AllAsset.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>AllAsset</label>
+</ApexPage>
diff --git a/scr/pages/AnswersHome.page b/scr/pages/AnswersHome.page
new file mode 100644
index 0000000..a305b75
--- /dev/null
+++ b/scr/pages/AnswersHome.page
@@ -0,0 +1 @@
+<apex:page action="{!URLFOR('/answers/answersHome.apexp')}"/>
\ No newline at end of file
diff --git a/scr/pages/AnswersHome.page-meta.xml b/scr/pages/AnswersHome.page-meta.xml
new file mode 100644
index 0000000..8e4d0a2
--- /dev/null
+++ b/scr/pages/AnswersHome.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Answer 绔欑偣鐨勯粯璁� Force.com 涓婚〉</description>
+    <label>AnswersHome</label>
+</ApexPage>
diff --git a/scr/pages/ApplicationMessage.page b/scr/pages/ApplicationMessage.page
new file mode 100644
index 0000000..026d153
--- /dev/null
+++ b/scr/pages/ApplicationMessage.page
@@ -0,0 +1,35 @@
+<apex:page standardController="loaner_application__c" extensions="ApplicationMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    //blockme();
+    window.open('/apex/ApplicationMessagePopUp?raid=' + '{!URLENCODE(loaner_application__c.Id)}',
+                'loaner_application__cNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+}
+
+function reloadjs() {
+    //blockme();
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="鐣欒█" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!ra.OCN_Internal_Notes__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ApplicationMessage.page-meta.xml b/scr/pages/ApplicationMessage.page-meta.xml
new file mode 100644
index 0000000..ed9eb9c
--- /dev/null
+++ b/scr/pages/ApplicationMessage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>42.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>ApplicationMessage</label>
+</ApexPage>
diff --git a/scr/pages/ApplicationMessagePopUp.page b/scr/pages/ApplicationMessagePopUp.page
new file mode 100644
index 0000000..3032367
--- /dev/null
+++ b/scr/pages/ApplicationMessagePopUp.page
@@ -0,0 +1,51 @@
+<apex:page Controller="ApplicationMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.loaner_application__c.fields.OCN_Internal_Notes__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="鐣欒█" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra1.OCN_Internal_Notes__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ApplicationMessagePopUp.page-meta.xml b/scr/pages/ApplicationMessagePopUp.page-meta.xml
new file mode 100644
index 0000000..b6091d8
--- /dev/null
+++ b/scr/pages/ApplicationMessagePopUp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>42.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>ApplicationMessagePopUp</label>
+</ApexPage>
diff --git a/scr/pages/AssetNumberChange.page b/scr/pages/AssetNumberChange.page
new file mode 100644
index 0000000..166ba56
--- /dev/null
+++ b/scr/pages/AssetNumberChange.page
@@ -0,0 +1,82 @@
+<apex:page standardController="Asset" extensions="AssetNumberChangeController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="搴撳瓨璋冩暣">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    blockme();
+    saveBtn();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="headBlock" title="鏍锋満淇℃伅">
+                <table border="0" style="border-collapse: collapse;width:900px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.name.label}锛�</td>
+                        <td><apex:outputField value="{!ast.Name}"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.AccountId.label}锛�</td>
+                        <td colspan="3"><apex:outputField value="{!ast.AccountId}"/></td>
+                    </tr>
+                    <tr>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.Equipment_Type__c.label}锛�</td>
+                        <td><apex:outputField value="{!ast.Equipment_Type__c}"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.EC_Code__c.label}锛�</td>
+                        <td><apex:outputField value="{!ast.EC_Code__c}"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.SerialNumber.label}锛�</td>
+                        <td><apex:outputField value="{!ast.SerialNumber}"/></td>
+                    </tr>
+                    <tr>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.loaner_place__c.label}锛�</td>
+                        <td><apex:outputField value="{!ast.loaner_place__c}"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.lonar_owner__c.label}锛�</td>
+                        <td><apex:outputField value="{!ast.lonar_owner__c}"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Asset.fields.total_number__c.label}锛�</td>
+                        <td><apex:outputField value="{!ast.total_number__c}"/></td>
+                    </tr>
+                </table>
+            </apex:pageBlock>
+
+            <apex:pageBlock id="allBlock" title="搴撳瓨璋冩暣">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="saveJs();" value="淇濆瓨" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton action="{!cancelBtn}" value="鍙栨秷" rerender="dummy" style="width: 70px;"/>
+                </apex:pageBlockButtons>
+
+                <table border="0" style="border-collapse: collapse;width:900px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <td style="text-align: right;">{!$ObjectType.Loaner_change_history__c.fields.Name.label}锛�</td>
+                        <td><apex:inputField value="{!lch.Name}" style="width:90%;"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Loaner_change_history__c.fields.change_content__c.label}锛�</td>
+                        <td><apex:inputField value="{!lch.change_content__c}" style="width:90%;"/></td>
+                        <td style="text-align: right;">{!$ObjectType.Loaner_change_history__c.fields.change_number__c.label}锛�</td>
+                        <td><apex:inputField value="{!lch.change_number__c}" style="width:90%;"/></td>
+                    </tr>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/AssetNumberChange.page-meta.xml b/scr/pages/AssetNumberChange.page-meta.xml
new file mode 100644
index 0000000..4f5e089
--- /dev/null
+++ b/scr/pages/AssetNumberChange.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>AssetNumberChange</label>
+</ApexPage>
diff --git a/scr/pages/BandwidthExceeded.page b/scr/pages/BandwidthExceeded.page
new file mode 100644
index 0000000..4d9fdfa
--- /dev/null
+++ b/scr/pages/BandwidthExceeded.page
@@ -0,0 +1,17 @@
+<apex:page showHeader="false" title="{!$Label.site.bandwidth_limit_exceeded}">
+  <apex:composition template="StdExceptionTemplate">
+    <apex:define name="icon">
+      <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/warning.png')}"/>
+    </apex:define>
+    <apex:define name="error">
+      <apex:outputText styleClass="title" value="{!$Label.site.limit_exceeded}"/>
+      <br/>
+      <br/>
+      <apex:outputText value="{!$Label.site.sorry_for_inconvenience}"/>
+      <apex:outputText escape="false" value=" {!$Label.site.get_in_touch}">
+      <apex:param value="mailto:{!$Site.AdminEmailAddress}"/>
+      <apex:param value="{!$Label.site.email_us}"/>
+    </apex:outputText>
+   </apex:define> 
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/BandwidthExceeded.page-meta.xml b/scr/pages/BandwidthExceeded.page-meta.xml
new file mode 100644
index 0000000..a778889
--- /dev/null
+++ b/scr/pages/BandwidthExceeded.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 瓒呭嚭闄愬埗椤甸潰</description>
+    <label>BandwidthExceeded</label>
+</ApexPage>
diff --git a/scr/pages/CTITest.page b/scr/pages/CTITest.page
new file mode 100644
index 0000000..26052d9
--- /dev/null
+++ b/scr/pages/CTITest.page
@@ -0,0 +1,853 @@
+<apex:page showChat="false" showHeader="false" sidebar="false">
+
+<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<head>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+    <title></title>
+    <style type="text/css">
+        #Text1 {
+            width: 236px;
+        }
+
+        #TextArea1 {
+            height: 192px;
+            width: 472px;
+        }
+
+        #txtLog {
+            height: 201px;
+            width: 503px;
+        }
+
+        #btnConfig {
+            width: 60px;
+        }
+
+        #btnLogin {
+            width: 60px;
+        }
+
+        #btnLogout {
+            width: 60px;
+        }
+
+        #btnReady {
+            width: 60px;
+        }
+
+        #btnNotReady {
+            width: 60px;
+        }
+
+        #btnMakeCall {
+            width: 78px;
+        }
+
+        #btnAnswer {
+            width: 78px;
+        }
+
+        #btnDTMF {
+            width: 78px;
+        }
+
+        #btnHangup {
+            width: 78px;
+        }
+
+        #btnHold {
+            width: 78px;
+        }
+
+        #btnUnhold {
+            width: 78px;
+        }
+
+        #btnMuteOn {
+            width: 78px;
+        }
+
+        #btnMuteOff {
+            width: 78px;
+        }
+
+        #btnFinish {
+            width: 78px;
+        }
+
+        #btnUnhold {
+            width: 78px;
+        }
+
+        #btnConsultOut {
+            width: 94px;
+        }
+
+        #btnConsultInner {
+            width: 94px;
+        }
+
+        #btnCompleteTransfer {
+            width: 94px;
+        }
+
+        #btnCompleteTransfer0 {
+            width: 94px;
+        }
+
+        #btnCancelTransfer {
+            width: 94px;
+        }
+
+        #btnCompleteTransfer0 {
+            width: 94px;
+        }
+
+        #btnTransOut {
+            width: 94px;
+        }
+
+        #btnTransInner {
+            width: 94px;
+        }
+
+        #btnTransIVR {
+            width: 94px;
+        }
+
+        #btnConsultIVR {
+            width: 94px;
+        }
+
+        #btnCancelConsult {
+            width: 94px;
+        }
+
+        #btnDTMF0 {
+            width: 78px;
+        }
+
+        #btnDTMF1 {
+            width: 78px;
+        }
+
+        #btnMakeCall0 {
+            width: 78px;
+        }
+
+        #btnCallOut {
+            width: 78px;
+        }
+
+        #btnAnswer0 {
+            width: 78px;
+        }
+
+        #btnConsultOut0 {
+            width: 94px;
+        }
+
+        #btnConsultOut1 {
+            width: 94px;
+        }
+
+        #btnConsultOut2 {
+            width: 94px;
+        }
+
+        #btnForceOut0 {
+            width: 83px;
+        }
+
+        #btnForceOut1 {
+            width: 83px;
+        }
+
+        #btnForceOut2 {
+            width: 83px;
+        }
+
+        #btnForceOut3 {
+            width: 83px;
+        }
+
+        #btnListen {
+            width: 81px;
+        }
+
+        #btnInsert {
+            width: 88px;
+        }
+    </style>
+</head>
+<body>
+    <!-- <script type="text/javascript" src="cti.js"></script> -->
+    <apex:includeScript value="{!URLFOR($Resource.cti)}"/>
+    <p>
+        <input id="btnLogin" type="button" value="鐧诲綍" onclick="login()" />
+        <input id="btnLogout" type="button" value="娉ㄩ攢" onclick="logout()" />
+        <input id="btnReady" type="button" value="绀洪棽" onclick="setReady()" />
+        <input id="btnNotReady" type="button" value="绀哄繖" onclick="setNotReady()" />
+        <input id="btnQueryAllAgents" type="button" value="鏌ヨ搴у腑鐘舵��" onclick="queryAllAgentStatus()" />
+    </p>
+
+
+    <p>
+        <input id="txtNumber" type="text" />
+        <input id="btnCallOut" type="button" value="鎷ㄦ墦" onclick="callOut()" />
+        <input id="btnCallInner" type="button" value="鍛煎彨搴у腑" onclick="callInner()" />
+        <input id="btnAnswer" type="button" value="鎺ュ惉" onclick="answer()" />&nbsp;
+        <input id="btnCallInfo" type="button" value="鍛煎彨淇℃伅" onclick="showCallInfo()" />
+    </p>
+    <p>
+        <input id="txtDTMF" type="text" />
+        <input id="btnDTMF" type="button" value="浜屾鎷ㄥ彿" onclick="sendDTMF()" />
+    </p>
+    <p>
+        <input id="txtCallData" type="text" />
+        <input id="btnDTMF0" type="button" value="璇婚殢璺暟鎹�" onclick="getCallData()" />
+        <input id="btnDTMF1" type="button" value="鍐欓殢璺暟鎹�" onclick="setCallData()" />
+    </p>
+    <p>
+        <input id="btnHold" type="button" value="淇濇寔" onclick="hold()" />
+        <input id="btnUnhold" type="button" value="鍙栦繚鎸�" onclick="unhold()" />
+        <input id="btnMuteOn" type="button" value="璁剧疆闈欓煶" onclick="setmuteon()" />
+        <input id="btnMuteOff" type="button" value="鍙栨秷闈欓煶" onclick="setmuteoff()" />
+        <input id="btnHangup" type="button" value="鎸傛柇" onclick="hangup()" />
+        <input id="btnFinish" type="button" value="缁撴潫閫氳瘽" onclick="finish()" />
+    </p>
+    <p>
+        <input id="txtTransNum" type="text" />
+    </p>
+    <p>
+        <input id="btnTransOut" type="button" value="鍗曟杞绾�" onclick="transOut()" />
+        <input id="btnTransInner" type="button" value="鍗曟杞唴绾�" onclick="transInner()" />
+        <input id="btnTransQueue" type="button" value="杞槦鍒�" onclick="transQueue()" />
+        <input id="btnTransIVR" type="button" value="鍗曟杞琁VR" onclick="transIVR()" />
+        <input id="btnConsultIVR" type="button" value="鎸傝捣杞琁VR" onclick="consultIVR()" />&nbsp;&nbsp;
+    </p>
+    <p>
+        <input id="btnConsultOut" type="button" value="鍗忓晢澶栫嚎" onclick="consultOut()" />
+        <input id="btnConsultInner" type="button" value="鍗忓晢搴у腑" onclick="consultInner()" />
+        <input id="btnCompleteTransfer" type="button" value="瀹屾垚杞帴" onclick="consultTransfer()" />
+        <input id="btnCompleteTransfer0" type="button" value="涓夋柟閫氳瘽" onclick="consultConference()" />
+        <input id="btnCancelConsult" type="button" value="鍙栨秷鍗忓晢" onclick="cancelConsult()" />
+    </p>
+    <p>
+        <input id="txtAgentId" type="text" />&nbsp;
+    </p>
+    <p>
+        <input id="btnForceBusy" type="button" value="寮哄埗绀哄繖" onclick="forceBusy()" />
+        <input id="btnForceReady" type="button" value="寮哄埗绀洪棽" onclick="forceReady()" />
+        <input id="btnForceOut" type="button" value="寮哄埗绛惧嚭" onclick="forceOut()" />
+        <input id="btnListen" type="button" value="鐩戝惉" onclick="listen()" />
+        <input id="btnStopListen" type="button" value="鍋滄鐩戝惉" onclick="stopListen()" />
+        <input id="btnInsert" type="button" value="鎻掑叆" onclick="insert()" />
+        <input id="btnStopInsert" type="button" value="鍋滄鎻掑叆" onclick="stopInsert()" />
+    </p>
+
+    <script type="text/javascript">
+
+        var cti;
+        var stateDescrArray = ["鏈櫥褰�", "绀哄繖", "绀洪棽", "灏忎紤", "鎸搩", "鎷ㄥ彿", "閫氳瘽", "璇濆悗"];
+        var consultStateDescrArray = ["鏈煡鐘舵��", "姝e湪鍛煎彨", "鍗忓晢鎺ラ��", "涓夋柟閫氳瘽", "涓夋柟澶辫触"];
+         
+        try {
+            cti = createCTI();
+            cti.onAgentStateChanged = function (e) { 
+				AppendLog("鐘舵�佹敼鍙�, 褰撳墠鐘舵�侊細 " + getStateDescr(e.NewState.StateCode)); 
+            };
+            cti.onAnswerRequest = function () { AppendLog("璇锋眰搴旂瓟"); };
+            cti.onRecordStart = function (e) { AppendLog("褰曢煶寮�濮嬶細 CallId = " + e.CallId + ", 鏂囦欢鍚� = " + e.RecordFileName) };
+            cti.onRecordStop = function (e) { AppendLog("褰曢煶鍋滄锛� CallId = " + e.CallId + ", 鏂囦欢鍚� = " + e.RecordFileName) };
+            cti.onConsultStateChange = function (e) { AppendLog("涓夋柟鐘舵�佹敼鍙橈細   " + getConsultStateDescr(e.NewState.StateCode));  };
+            cti.onAgentAsrNotify = function (e) { AppendLog("璇煶璇嗗埆锛�   ")  };
+			cti.onQueueNumNotify = function (e) { AppendLog(e)  };
+            cti.attachEvent();
+        }
+        catch (e) {
+            alert(e.message);
+        }
+        function getConsultStateDescr(stateCode) {
+
+            if (stateCode < 0 || stateCode >= consultStateDescrArray.length) {
+                return "鏈煡鐘舵��";
+            }
+
+            return consultStateDescrArray[stateCode];
+        }
+
+        function getStateDescr(stateCode) {
+
+            if (stateCode < 0 || stateCode >= stateDescrArray.length) {
+                return "鏈煡鐘舵��";
+            }
+
+            return stateDescrArray[stateCode];
+        }
+        var GetConfig = function (domain, serverAddress, serverPort, agentID, agentPassword,
+            useWebVoip, webVoipSIPServerIP, webVoipSIPServerPort, webVoipAccount, webVoipPassword) {
+
+            return {
+                "CTI.Provider": "Lusca.LuscaCTIProvider, Lusca"                           // 鎻愪緵绋嬪簭
+                , "CTI.Timeout": "30000"                                                          // 瓒呮椂璁剧疆
+                , "CTI.Lusca.ServerAddress": serverAddress                 // 鏈嶅姟鍣ㄥ湴鍧� |domain
+                , "CTI.Lusca.ServerPort": serverPort                                                 // 鏈嶅姟鍣ㄧ鍙e彿
+                , "CTI.Lusca.EventPollUrl": "http://"+serverAddress+":"+serverPort + "/as/event?agent_id="+agentID
+                , "CTI.Lusca.UseWebVoip": useWebVoip                                              // 鏄惁浣跨敤杞數璇�
+                , "CTI.Lusca.WebVoipSIPServerIP": webVoipSIPServerIP                              // 杞數璇濇湇鍔″櫒鍦板潃
+                , "CTI.Lusca.WebVoipSIPServerPort": webVoipSIPServerPort                                      // 杞數璇濇湇鍔″櫒绔彛
+                , "CTI.Lusca.WebVoipAccount": webVoipAccount                                            // 杞數璇濊处鍙�
+                , "CTI.Lusca.WebVoipPassword": webVoipPassword                                       // 杞數璇濆瘑鐮�
+                , "CTI.AgentID": agentID                                                           // 搴у腑宸ュ彿
+                , "CTI.AgentPassword": agentPassword                                                // 搴у腑瀵嗙爜
+                , "CTI.Lusca.TenantId": "as"
+                , "CTI.Lusca.QueueName": "support@default"   //闃熷垪
+                , "CTI.UpdatePath": "ftp://192.168.17.141//Lusca"
+                , "CTI.UpdateMode": "0" //0:ftp 1:netbios
+                , "CTI.AutoLogout": "true"
+                , "CTI.EnableVoiceAnalysis": "false"
+                , "CTI.LocalRecording.Mode": ""
+                , "CTI.LocalRecording.Path": ""
+                , "CTI.Lusca.Domain": ""//domain
+            }
+        }
+
+        // 閰嶇疆鍙傛暟
+        function config() {
+            try {
+                //var config = GetConfig(鏈嶅姟鍣ㄥ湴鍧�, 绔彛, 鍧愬腑鍙�, "as", 鏄惁寮�鍚蒋鐢佃瘽,杞數璇濆湴鍧�, 绔彛鍙�,杞數璇濆彿鐮�, 瀵嗙爜);
+                var config = GetConfig("domain_ysb", "223.112.26.254", "9528", "10005", "1234", "true", "223.112.26.254|domain_ysb", "63000", "80005", "1234");
+				//var config = GetConfig("domain_ysb", "223.112.26.254", "9528", "10200", "1234", "true", "223.112.26.254|domain_ysb", "9060", "80200", "pactera_op");
+                cti.setConfig(config);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鐧诲綍
+        function login() {
+            try {
+                config();
+                var result = cti.agentLogin(false);
+
+                if (result == 1) {
+                    if (confirm("搴у腑宸茬粡鐧诲綍锛岃寮哄埗鐧诲綍鍚楋紵")) {
+                        cti.agentLogin(true);
+                    }
+                    else {
+                        return;
+                    }
+                }
+
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 娉ㄩ攢
+        function logout() {
+            try {
+                cti.agentLogout();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 绀洪棽
+        function setReady() {
+            try {
+                cti.agentSetReady();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 绀哄繖
+        function setNotReady() {
+            try {
+                cti.agentSetNotReady();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎺ュ惉
+        function answer() {
+            try {
+                cti.answerCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍛煎嚭
+        function callOut() {
+            try {
+
+                var number = txtNumber.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.callOut("", number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍐呯嚎鍛煎彨
+        function callInner() {
+            try {
+
+                var number = txtNumber.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.callInner(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎸傛満
+        function hangup() {
+            try {
+                cti.releaseCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 浜屾鎷ㄥ彿
+        function sendDTMF() {
+            try {
+
+                var number = txtDTMF.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.sendDTMF(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 璁剧疆闈欓煶
+        function setmuteon() {
+            try {
+                cti.setMuteOn();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍙栨秷闈欓煶
+        function setmuteoff() {
+            try {
+                cti.setMuteOff();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 璇婚殢璺暟鎹�
+        function getCallData() {
+            try {
+                txtCallData.value = cti.queryCallData();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍐欓殢璺暟鎹�
+        function setCallData() {
+            try {
+                cti.setCallData(txtCallData.value);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 淇濇寔
+        function hold() {
+            try {
+                cti.holdCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍙栦繚鎸�
+        function unhold() {
+            try {
+                cti.retrieveCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 缁撴潫閫氳瘽锛堝皬缁撴椂璋冪敤锛�
+        function finish() {
+            try {
+                cti.finishCall(0);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞绾�
+        function transOut() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferOut("", number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞唴绾�
+        function transInner() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferInner(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞槦鍒�
+        function transQueue() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferQueue(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞琁VR
+        function transIVR() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferIVR(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎸傝捣杞琁VR
+        function consultIVR() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.consultIVR(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗忓晢澶栫嚎
+        function consultOut() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.consultOut("", number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗忓晢搴у腑
+        function consultInner() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.consultInner(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍙栨秷鍗忓晢
+        function cancelConsult() {
+            try {
+                cti.cancelConsult();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗忓晢杞帴
+        function consultTransfer() {
+            try {
+                cti.consultTransfer();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 涓夋柟閫氳瘽
+        function consultConference() {
+            try {
+                cti.consultConference();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 寮哄埗绀哄繖
+        function forceBusy() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.forceAgentBusy(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 寮哄埗绀洪棽
+        function forceReady() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.forceAgentReady(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 寮哄埗绛惧嚭
+        function forceOut() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.forceAgentLogout(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鐩戝惉
+        function listen() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.listen(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍋滄鎻掑叆
+        function stopListen() {
+            try {
+                cti.stopListen();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎻掑叆
+        function insert() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.insert(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍋滄鎻掑叆
+        function stopInsert() {
+            try {
+                cti.stopInsert();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        function showCallInfo() {
+            try {
+                var call = cti.getActiveCallInfo();
+
+                if (call != null) {
+                    alert("娲诲姩鍛煎彨锛� CallId = " + call.CallId + ", 涓诲彨 = " + call.CallerNum + ", 琚彨 = " + call.CalledNum);
+                }
+
+                call = cti.getHeldCallInfo();
+
+                if (call != null) {
+                    alert("淇濇寔鍛煎彨锛� CallId = " + call.CallId + ", 涓诲彨 = " + call.CallerNum + ", 琚彨 = " + call.CalledNum);
+                }
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        function queryAllAgentStatus() {
+            try {
+                var result = cti.queryAllAgentStatus();
+
+                if (result != null) {
+
+                    var str = "";
+
+                    for (var i = 0; i < result.length; i++) {
+
+                        str += "宸ュ彿: " + result[i].AgentId;
+                        str += ", 鐘舵�侊細 " + getStateDescr(result[i].AgentState);
+                        str += "\r\n";
+                    }
+
+                    alert(str);
+                }
+                else {
+                    alert("娌℃湁搴у腑.");
+                }
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        Date.prototype.Format = function (fmt) { //author: meizz
+            var o = {
+                "M+": this.getMonth() + 1, //鏈堜唤
+                "d+": this.getDate(), //鏃�
+                "h+": this.getHours(), //灏忔椂
+                "m+": this.getMinutes(), //鍒�
+                "s+": this.getSeconds(), //绉�
+                "q+": Math.floor((this.getMonth() + 3) / 3), //瀛e害
+                "S": this.getMilliseconds() //姣
+            };
+
+            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
+            for (var k in o)
+                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
+            return fmt;
+        }
+
+        // 杈撳嚭鏃ュ織
+        function AppendLog(message) {
+            var now = new Date();
+            txtLog.value += now.Format("yyyy-MM-dd hh:mm:ss") + "  " + message + "\r\n";
+        }
+    </script>
+
+    <p>
+        <textarea id="txtLog" name="S1"></textarea>
+    </p>
+
+</body>
+</html>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CTITest.page-meta.xml b/scr/pages/CTITest.page-meta.xml
new file mode 100644
index 0000000..d07e982
--- /dev/null
+++ b/scr/pages/CTITest.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>CTITest</label>
+</ApexPage>
diff --git a/scr/pages/CampaignRelationship.page b/scr/pages/CampaignRelationship.page
new file mode 100644
index 0000000..cf0464b
--- /dev/null
+++ b/scr/pages/CampaignRelationship.page
@@ -0,0 +1,238 @@
+<apex:page standardController="Campaign" extensions="CampaignRelationshipController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="瀹㈡埛-甯傚満娲诲姩鍏崇郴">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+
+    var openQuoteExcelImportWindow = null;
+    var baseUrl = '{!baseUrl}';
+    
+    var campaignId = '{!campaignId}';
+    function openQuoteExcelImport() {
+        if ( openQuoteExcelImportWindow == null || openQuoteExcelImportWindow.closed) {
+            openQuoteExcelImportWindow = window.open(baseUrl + '/apex/DataLoadAccount?campaignId=' +campaignId, 'xlsdoc', 'width=1800,height=700');
+        }
+        else {
+            openQuoteExcelImportWindow.focus();
+        }
+    }
+
+    function refreshPage(){
+            var baseUrlre = j$(escapeVfId("baseUrl")).value();
+            window.parent.location.href = baseUrl + '/{!URLENCODE(campaignId)}';
+    }
+</script>
+
+<apex:form id="allForm">
+    
+    <apex:commandButton onclick="openQuoteExcelImport();return false;" reRender="dummy" value="瀵煎叆瀹㈡埛" style="width: 70px;right: auto;" oncomplete="unblockUI();"></apex:commandButton>
+    
+    <apex:outputPanel id="allPanel">
+    <input type="hidden" value="{!baseUrl}" id="baseUrl" />
+    </apex:outputPanel>
+
+    <apex:outputPanel id="Activities">
+        
+            <table class="formtable" width="100%" border="0" style ="text-align: center;">
+                 <colgroup>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="12%"/>
+                </colgroup>
+                <tr>
+                    <th style ="text-align: center" >RVI瀹㈡埛</th>
+                </tr>
+                <tr>
+                    <th style ="text-align: center">瀹㈡埛-甯傚満娲诲姩鍏崇郴鍚嶇О</th>
+                    <th style ="text-align: center">瀹㈡埛</th>
+                    <th style ="text-align: center">鍒嗛噹</th>
+                    <th style ="text-align: center">瀹㈡埛缂栫爜</th>
+                    <th style ="text-align: center">瀹㈡埛鐘舵��</th>
+                </tr>
+               
+              <apex:repeat id="RVI_CRList" value="{!RVICRList}" var="CR">
+
+                <tr>
+                    <apex:outputPanel layout="none" rendered="{!IF(CR.RelationshipProductSegment__c == 'RVI', true, false)}">
+                        <td style ="text-align: center" > 
+                            <apex:outputLink value="/{!CR.Id}" target="LINK_{!CR.Id}">{!CR.name}</apex:outputLink>
+                        </td>
+                        <td style ="text-align: center" > 
+                            <apex:outputLink value="/{!CR.RelationshipAccount__c}" target="LINK_{!CR.RelationshipAccount__c}">{!CR.RelationshipAccount__r.Name}</apex:outputLink>
+                        </td>
+                        <td style ="text-align: center" > 
+                            <apex:outputText id="RVI_ProductSegment" value="{!CR.RelationshipProductSegment__c}" ></apex:outputText>
+                        </td>
+                        <td style ="text-align: center" > 
+                            <apex:outputText id="RVI_ManagementCode" value="{!CR.ManagementCode__c}" ></apex:outputText>
+                        </td>
+                        <td style ="text-align: center" > 
+                            <apex:outputText id="RVI_Status" value="{!IF(OR(CR.RelationshipAccountStatus__c == 'Active',CR.RelationshipAccountStatus__c == ''),'鏈夋晥','鍙栨秷')}" ></apex:outputText>
+                            
+                        </td>
+                    </apex:outputPanel>
+                </tr>
+                 </apex:repeat>
+            </table>
+       
+        <td colspan="9"> <hr/></td>
+        
+            <table class="formtable" width="100%" border="0" >
+                <colgroup>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="12%"/>
+                </colgroup>
+                <tr>
+                    <th style ="text-align: center">NDT瀹㈡埛</th>
+                </tr>
+                <tr>
+                    <th style ="text-align: center">瀹㈡埛-甯傚満娲诲姩鍏崇郴鍚嶇О</th>
+                    <th style ="text-align: center">瀹㈡埛</th>
+                    <th style ="text-align: center">鍒嗛噹</th>
+                    <th style ="text-align: center">瀹㈡埛缂栫爜</th>
+                    <th style ="text-align: center">瀹㈡埛鐘舵��</th>
+                </tr>
+                
+                <apex:repeat id="NDT_CRList" value="{!NDTCRList}" var="CR">
+                    <tr>
+                        <apex:outputPanel layout="none" rendered="{!IF(CR.RelationshipProductSegment__c == 'NDT', true, false)}">
+                            <td style ="text-align: center"> 
+                                <apex:outputLink value="/{!CR.Id}" target="LINK_{!CR.Id}">{!CR.name}</apex:outputLink>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputLink value="/{!CR.RelationshipAccount__c}" target="LINK_{!CR.RelationshipAccount__c}">{!CR.RelationshipAccount__r.Name}</apex:outputLink>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <!-- <apex:outputText id="NDT_ProductSegment" value="{!CR.RelationshipProductSegment__c}" ></apex:outputText> -->
+                                <c:PDFWbr targetStr="{!CR.RelationshipProductSegment__c}"/>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputText id="NDT_ManagementCode" value="{!CR.ManagementCode__c}" ></apex:outputText>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputText id="NDT_Status" value="{!IF(OR(CR.RelationshipAccountStatus__c == 'Active',CR.RelationshipAccountStatus__c == ''),'鏈夋晥','鍙栨秷')}" ></apex:outputText>
+                            </td>
+                        </apex:outputPanel>
+                    </tr>
+                </apex:repeat>
+            </table>
+        
+        <td colspan="9"> <hr/></td>
+
+            <table class="formtable" width="100%" border="0" >
+                <colgroup>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="12%"/>
+                </colgroup>
+                <tr>
+                    <th style ="text-align: center">ANI瀹㈡埛</th>
+                </tr>
+                <tr>
+                    <th style ="text-align: center">瀹㈡埛-甯傚満娲诲姩鍏崇郴鍚嶇О</th>
+                    <th style ="text-align: center">瀹㈡埛</th>
+                    <th style ="text-align: center">鍒嗛噹</th>
+                    <th style ="text-align: center">瀹㈡埛缂栫爜</th>
+                    <th style ="text-align: center">瀹㈡埛鐘舵��</th>
+                </tr>
+                
+                <apex:repeat id="ANI_CRList" value="{!ANICRList}" var="CR">
+                    <tr>
+                        <apex:outputPanel layout="none" rendered="{!IF(CR.RelationshipProductSegment__c == 'ANI', true, false)}">
+                            <td style ="text-align: center"> 
+                                <apex:outputLink value="/{!CR.Id}" target="LINK_{!CR.Id}">{!CR.name}</apex:outputLink>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputLink value="/{!CR.RelationshipAccount__c}" target="LINK_{!CR.RelationshipAccount__c}">{!CR.RelationshipAccount__r.Name}</apex:outputLink>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputText id="ANI_ProductSegment" value="{!CR.RelationshipProductSegment__c}" ></apex:outputText>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputText id="ANI_ManagementCode" value="{!CR.ManagementCode__c}" ></apex:outputText>
+                            </td>
+                            <td style ="text-align: center"> 
+                                <apex:outputText id="ANI_Status" value="{!IF(OR(CR.RelationshipAccountStatus__c == 'Active',CR.RelationshipAccountStatus__c == ''),'鏈夋晥','鍙栨秷')}" ></apex:outputText>
+                            </td>
+                        </apex:outputPanel>
+                    </tr>
+                </apex:repeat>
+            </table>
+        
+        <td colspan="9"> <hr/></td>
+ 
+            <table class="formtable" width="100%" border="0" >
+                <colgroup>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="11%"/>
+                    <col width="12%"/>
+                </colgroup>
+                <tr>
+                    <th style ="text-align: center">IE瀹㈡埛</th>
+                </tr>
+                <tr>
+                    <th style ="text-align: center">瀹㈡埛-甯傚満娲诲姩鍏崇郴鍚嶇О</th>
+                    <th style ="text-align: center">瀹㈡埛</th>
+                    <th style ="text-align: center">鍒嗛噹</th>
+                    <th style ="text-align: center">瀹㈡埛缂栫爜</th>
+                    <th style ="text-align: center">瀹㈡埛鐘舵��</th>
+                </tr>
+                
+            <apex:repeat id="IE_CRList" value="{!IECRList}" var="CR">    
+                <tr>
+                    <apex:outputPanel layout="none" rendered="{!IF(CR.RelationshipProductSegment__c == 'IE', true, false)}">
+                        <td style ="text-align: center"> 
+                            <!-- <apex:outputText id="IE_Name" value="{!CR.name}" ></apex:outputText> -->
+                            <apex:outputLink value="/{!CR.Id}" target="LINK_{!CR.Id}">{!CR.name}</apex:outputLink>
+                        </td>
+                        <td style ="text-align: center"> 
+                           <!--  <apex:outputText id="IE_Account" value="{!CR.RelationshipAccount__r.Name}" ></apex:outputText> -->
+                            <apex:outputLink value="/{!CR.RelationshipAccount__c}" target="LINK_{!CR.RelationshipAccount__c}">{!CR.RelationshipAccount__r.Name}</apex:outputLink>
+                        </td>
+                        <td style ="text-align: center"> 
+                            <!-- <apex:outputText id="IE_ProductSegment" value="{!CR.RelationshipProductSegment__c}" ></apex:outputText> -->
+                            <c:PDFWbr targetStr="{!CR.RelationshipProductSegment__c}"/>
+                        </td>
+                        <td style ="text-align: center"> 
+                            <apex:outputText id="IE_ManagementCode" value="{!CR.ManagementCode__c}" ></apex:outputText>
+                        </td>
+                        <td style ="text-align: center"> 
+                            <apex:outputText id="IE_Status" value="{!IF(OR(CR.RelationshipAccountStatus__c == 'Active',CR.RelationshipAccountStatus__c == ''),'鏈夋晥','鍙栨秷')}" ></apex:outputText>
+                        </td>
+                    </apex:outputPanel>
+                </tr>
+            </apex:repeat>
+            </table>
+        
+        <td colspan="9"> <hr/></td>
+    </apex:outputPanel>
+
+</apex:form>
+
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CampaignRelationship.page-meta.xml b/scr/pages/CampaignRelationship.page-meta.xml
new file mode 100644
index 0000000..dc30485
--- /dev/null
+++ b/scr/pages/CampaignRelationship.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>CampaignRelationship</label>
+</ApexPage>
diff --git a/scr/pages/CanNotDeleteCase.page b/scr/pages/CanNotDeleteCase.page
new file mode 100644
index 0000000..77f6cab
--- /dev/null
+++ b/scr/pages/CanNotDeleteCase.page
@@ -0,0 +1,6 @@
+<apex:page standardController="User_FaultInfo__c" showHeader="true" sidebar="true">
+    <apex:form >
+        <div style="font-size: 18px">涓嶈兘鍒犻櫎璇ユ暟鎹��</div>
+        <div style="font-size: 18px">鐐瑰嚮<apex:commandLink action="{!cancel}" value="杩欓噷" style="color: blue"/>杩斿洖銆�</div>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CanNotDeleteCase.page-meta.xml b/scr/pages/CanNotDeleteCase.page-meta.xml
new file mode 100644
index 0000000..bad0fe8
--- /dev/null
+++ b/scr/pages/CanNotDeleteCase.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>CanNotDeleteCase</label>
+</ApexPage>
diff --git a/scr/pages/CanNotEditOrDelete.page b/scr/pages/CanNotEditOrDelete.page
new file mode 100644
index 0000000..1c0d0ea
--- /dev/null
+++ b/scr/pages/CanNotEditOrDelete.page
@@ -0,0 +1,6 @@
+<apex:page standardController="OrderItem" showHeader="true" sidebar="true">
+    <apex:form >
+        <div style="font-size: 18px">涓嶈兘鐩存帴缂栬緫鎴栧垹闄よ鏁版嵁銆�</div>
+        <div style="font-size: 18px">鐐瑰嚮<apex:commandLink action="{!cancel}" value="杩欓噷" style="color: blue"/>杩斿洖銆�</div>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CanNotEditOrDelete.page-meta.xml b/scr/pages/CanNotEditOrDelete.page-meta.xml
new file mode 100644
index 0000000..32a8b40
--- /dev/null
+++ b/scr/pages/CanNotEditOrDelete.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>CanNotEditOrDelete</label>
+</ApexPage>
diff --git a/scr/pages/ChangePassword.page b/scr/pages/ChangePassword.page
new file mode 100644
index 0000000..ffb6b69
--- /dev/null
+++ b/scr/pages/ChangePassword.page
@@ -0,0 +1,41 @@
+<apex:page id="changePassword" showHeader="false" controller="ChangePasswordController" title="{!$Label.site.change_password}">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">  
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.change_your_password}"/>
+                  <br/>
+                  <apex:form id="theForm">
+                    <apex:pageMessages id="error"/>
+                    <apex:panelGrid columns="2" style="margin-top:1em;">
+                      <apex:outputLabel rendered="{! !$Site.IsPasswordExpired}" value="{!$Label.site.old_password}" for="oldpsw"/>
+                      <apex:inputSecret required="true" id="oldpsw" rendered="{! !$Site.IsPasswordExpired}" value="{!oldPassword}"/>
+                      <apex:outputLabel value="{!$Label.site.new_password}" for="psw"/>
+                      <apex:inputSecret required="true" id="psw" value="{!newPassword}"/>
+                      <apex:outputLabel value="{!$Label.site.verify_new_password}" for="vpsw"/>
+                      <apex:inputSecret required="true" id="vpsw" value="{!verifyNewPassword}"/>
+                      <apex:outputText value=""/>
+                      <apex:commandButton id="cpwbtn" action="{!changePassword}" value="{!$Label.site.change_password}"/>
+                    </apex:panelGrid> 
+                  </apex:form>                  
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+             </apex:outputPanel>
+            <c:SiteFooter />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChangePassword.page-meta.xml b/scr/pages/ChangePassword.page-meta.xml
new file mode 100644
index 0000000..509be64
--- /dev/null
+++ b/scr/pages/ChangePassword.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 鏇存敼瀵嗙爜椤甸潰</description>
+    <label>ChangePassword</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersAgentView.page b/scr/pages/ChatterAnswersAgentView.page
new file mode 100644
index 0000000..a39d3fe
--- /dev/null
+++ b/scr/pages/ChatterAnswersAgentView.page
@@ -0,0 +1,11 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page standardController="Case">
+    <apex:outputPanel rendered="{!case.origin == 'Chatter Answers'}">
+        <apex:detail /><br/>
+        <chatteranswers:singleitemfeed entityId="{!case.id}" />
+    </apex:outputPanel>
+
+    <apex:outputPanel rendered="{!case.origin != 'Chatter Answers'}">
+       <apex:detail />
+    </apex:outputPanel>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersAgentView.page-meta.xml b/scr/pages/ChatterAnswersAgentView.page-meta.xml
new file mode 100644
index 0000000..24f9707
--- /dev/null
+++ b/scr/pages/ChatterAnswersAgentView.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Agent View page</description>
+    <label>ChatterAnswersAgentView</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersChangePassword.page b/scr/pages/ChatterAnswersChangePassword.page
new file mode 100644
index 0000000..b8580fa
--- /dev/null
+++ b/scr/pages/ChatterAnswersChangePassword.page
@@ -0,0 +1,6 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page showHeader="false" sidebar="false">
+    <body>
+        <chatteranswers:changepassword />
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersChangePassword.page-meta.xml b/scr/pages/ChatterAnswersChangePassword.page-meta.xml
new file mode 100644
index 0000000..60192eb
--- /dev/null
+++ b/scr/pages/ChatterAnswersChangePassword.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Change Password page</description>
+    <label>ChatterAnswersChangePassword</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersForgotPassword.page b/scr/pages/ChatterAnswersForgotPassword.page
new file mode 100644
index 0000000..545a937
--- /dev/null
+++ b/scr/pages/ChatterAnswersForgotPassword.page
@@ -0,0 +1,6 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page showHeader="false" sidebar="false">
+    <body>
+        <chatteranswers:forgotpassword />
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersForgotPassword.page-meta.xml b/scr/pages/ChatterAnswersForgotPassword.page-meta.xml
new file mode 100644
index 0000000..fd6723e
--- /dev/null
+++ b/scr/pages/ChatterAnswersForgotPassword.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Forgot Password page</description>
+    <label>ChatterAnswersForgotPassword</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersForgotPasswordConfirm.page b/scr/pages/ChatterAnswersForgotPasswordConfirm.page
new file mode 100644
index 0000000..bfae337
--- /dev/null
+++ b/scr/pages/ChatterAnswersForgotPasswordConfirm.page
@@ -0,0 +1,6 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page showHeader="false" sidebar="false">
+    <body>
+        <chatteranswers:forgotpasswordconfirm />
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersForgotPasswordConfirm.page-meta.xml b/scr/pages/ChatterAnswersForgotPasswordConfirm.page-meta.xml
new file mode 100644
index 0000000..999db58
--- /dev/null
+++ b/scr/pages/ChatterAnswersForgotPasswordConfirm.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Forgot Password Confirmation page</description>
+    <label>ChatterAnswersForgotPasswordConfirm</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersHelp.page b/scr/pages/ChatterAnswersHelp.page
new file mode 100644
index 0000000..51394a2
--- /dev/null
+++ b/scr/pages/ChatterAnswersHelp.page
@@ -0,0 +1,6 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page showHeader="false" sidebar="false">
+    <body>
+        <chatteranswers:help />
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersHelp.page-meta.xml b/scr/pages/ChatterAnswersHelp.page-meta.xml
new file mode 100644
index 0000000..a5ab41f
--- /dev/null
+++ b/scr/pages/ChatterAnswersHelp.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Help page</description>
+    <label>ChatterAnswersHelp</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersLogin.page b/scr/pages/ChatterAnswersLogin.page
new file mode 100644
index 0000000..48587ca
--- /dev/null
+++ b/scr/pages/ChatterAnswersLogin.page
@@ -0,0 +1,6 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page showHeader="false" sidebar="false">
+    <body>
+        <chatteranswers:login />
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersLogin.page-meta.xml b/scr/pages/ChatterAnswersLogin.page-meta.xml
new file mode 100644
index 0000000..893df81
--- /dev/null
+++ b/scr/pages/ChatterAnswersLogin.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Login page</description>
+    <label>ChatterAnswersLogin</label>
+</ApexPage>
diff --git a/scr/pages/ChatterAnswersRegistration.page b/scr/pages/ChatterAnswersRegistration.page
new file mode 100644
index 0000000..7fee222
--- /dev/null
+++ b/scr/pages/ChatterAnswersRegistration.page
@@ -0,0 +1,6 @@
+<!--PLEASE READ: If you override the automatically generated CSS, your Chatter Answers community might not function correctly.-->
+<apex:page showHeader="false" sidebar="false">
+    <body>
+        <chatteranswers:registration />
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ChatterAnswersRegistration.page-meta.xml b/scr/pages/ChatterAnswersRegistration.page-meta.xml
new file mode 100644
index 0000000..2c0414f
--- /dev/null
+++ b/scr/pages/ChatterAnswersRegistration.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Default Chatter Answers Registration page</description>
+    <label>ChatterAnswersRegistration</label>
+</ApexPage>
diff --git a/scr/pages/CommunitiesLanding.page b/scr/pages/CommunitiesLanding.page
new file mode 100644
index 0000000..247a950
--- /dev/null
+++ b/scr/pages/CommunitiesLanding.page
@@ -0,0 +1,2 @@
+<apex:page id="communitiesLandingPage" controller="CommunitiesLandingController" action="{!forwardToStartPage}" title="{!$Label.site.site_login}">
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CommunitiesLanding.page-meta.xml b/scr/pages/CommunitiesLanding.page-meta.xml
new file mode 100644
index 0000000..027d927
--- /dev/null
+++ b/scr/pages/CommunitiesLanding.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿绀惧尯鐧诲綍椤甸潰</description>
+    <label>CommunitiesLanding</label>
+</ApexPage>
diff --git a/scr/pages/CommunitiesLogin.page b/scr/pages/CommunitiesLogin.page
new file mode 100644
index 0000000..ba837c9
--- /dev/null
+++ b/scr/pages/CommunitiesLogin.page
@@ -0,0 +1,2 @@
+<apex:page id="loginPage" controller="CommunitiesLoginController" action="{!forwardToAuthPage}" title="{!$Label.site.site_login}">
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CommunitiesLogin.page-meta.xml b/scr/pages/CommunitiesLogin.page-meta.xml
new file mode 100644
index 0000000..1c48644
--- /dev/null
+++ b/scr/pages/CommunitiesLogin.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿绀惧尯鐧诲綍椤甸潰</description>
+    <label>CommunitiesLogin</label>
+</ApexPage>
diff --git a/scr/pages/CommunitiesSelfReg.page b/scr/pages/CommunitiesSelfReg.page
new file mode 100644
index 0000000..ba08f09
--- /dev/null
+++ b/scr/pages/CommunitiesSelfReg.page
@@ -0,0 +1,28 @@
+<apex:page id="communitiesSelfRegPage" showHeader="true" controller="CommunitiesSelfRegController" title="{!$Label.site.user_registration}">
+     <apex:define name="body">  
+      <center>
+<apex:form id="theForm" forceSSL="true">
+                    <apex:pageMessages id="error"/>
+                    <apex:panelGrid columns="2" style="margin-top:1em;">
+                      <apex:outputLabel value="First Name" for="firstName"/>
+                      <apex:inputText required="true" id="firstName" value="{!firstName}" label="First Name"/>
+                      <apex:outputLabel value="Last Name" for="lastName"/>
+                      <apex:inputText required="true" id="lastName" value="{!lastName}" label="Last Name"/>
+                      <apex:outputLabel value="{!$Label.site.community_nickname}" for="communityNickname"/>
+                      <apex:inputText required="true" id="communityNickname" value="{!communityNickname}" label="{!$Label.site.community_nickname}"/>
+                      <apex:outputLabel value="{!$Label.site.email}" for="email"/>
+                      <apex:inputText required="true" id="email" value="{!email}" label="{!$Label.site.email}"/>
+                      <apex:outputLabel value="{!$Label.site.password}" for="password"/>
+                      <apex:inputSecret id="password" value="{!password}"/>
+                      <apex:outputLabel value="{!$Label.site.confirm_password}" for="confirmPassword"/>
+                      <apex:inputSecret id="confirmPassword" value="{!confirmPassword}"/>
+                      <apex:outputText value=""/>
+                      <apex:commandButton action="{!registerUser}" value="{!$Label.site.submit}" id="submit"/>
+                    </apex:panelGrid> 
+                  <br/>
+</apex:form>
+     </center>
+      <br/>
+    </apex:define>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CommunitiesSelfReg.page-meta.xml b/scr/pages/CommunitiesSelfReg.page-meta.xml
new file mode 100644
index 0000000..f75d171
--- /dev/null
+++ b/scr/pages/CommunitiesSelfReg.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿绀惧尯鑷姪娉ㄥ唽椤甸潰</description>
+    <label>CommunitiesSelfReg</label>
+</ApexPage>
diff --git a/scr/pages/CommunitiesSelfRegConfirm.page b/scr/pages/CommunitiesSelfRegConfirm.page
new file mode 100644
index 0000000..33f9830
--- /dev/null
+++ b/scr/pages/CommunitiesSelfRegConfirm.page
@@ -0,0 +1,28 @@
+<apex:page id="communitiesSelfRegConfirmPage" controller="CommunitiesSelfRegConfirmController" showHeader="true" cache="false" title="{!$Label.site.registration_confirmation}" >
+    <apex:define name="body">  
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1" style="align: center;"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" style="topPanel"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanelContainer">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.thank_you_for_registering}"/>
+                  <br/>
+                  <br/>
+                  <apex:outputLink value="{!$Page.CommunitiesLogin}" rendered="{!$Site.LoginEnabled}">{!$Label.site.go_to_login_page}</apex:outputLink>
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+            </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CommunitiesSelfRegConfirm.page-meta.xml b/scr/pages/CommunitiesSelfRegConfirm.page-meta.xml
new file mode 100644
index 0000000..503bbb5
--- /dev/null
+++ b/scr/pages/CommunitiesSelfRegConfirm.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿绀惧尯鑷姪娉ㄥ唽纭椤甸潰</description>
+    <label>CommunitiesSelfRegConfirm</label>
+</ApexPage>
diff --git a/scr/pages/CommunitiesTemplate.page b/scr/pages/CommunitiesTemplate.page
new file mode 100644
index 0000000..345cb1d
--- /dev/null
+++ b/scr/pages/CommunitiesTemplate.page
@@ -0,0 +1,6 @@
+<apex:page showHeader="false" sidebar="false" id="CommunitiesTemplate">
+  <apex:stylesheet value="{!$Site.Prefix}/communities/CommunitiesStyles.css"/>
+  <apex:insert name="header"/>
+  <apex:insert name="body"/>
+  <apex:insert name="footer"/>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CommunitiesTemplate.page-meta.xml b/scr/pages/CommunitiesTemplate.page-meta.xml
new file mode 100644
index 0000000..c50321e
--- /dev/null
+++ b/scr/pages/CommunitiesTemplate.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿绀惧尯椤甸潰妯℃澘</description>
+    <label>CommunitiesTemplate</label>
+</ApexPage>
diff --git a/scr/pages/ContactOpenAlert.page b/scr/pages/ContactOpenAlert.page
new file mode 100644
index 0000000..a4719b4
--- /dev/null
+++ b/scr/pages/ContactOpenAlert.page
@@ -0,0 +1,21 @@
+<apex:page standardController="Contact" showHeader="false" sidebar="false">
+    <script type="text/javascript">
+    	var is_new = '{!Contact.IsNew__c}' == 'true';
+    	var approval_status = '{!Contact.StatusD__c}';
+        var now_status = '{!Contact.Address1_IsChanged__c}' == 'true' || 
+            '{!Contact.Address2_IsChanged__c}' == 'true' || 
+            '{!Contact.Address3_IsChanged__c}' == 'true' || 
+            '{!Contact.CancelReason_IsChanged__c}' == 'true' || 
+            '{!Contact.Contact_Status_IsChanged__c}' == 'true' || 
+            '{!Contact.Email_IsChanged__c}' == 'true' || 
+            '{!Contact.Fax_IsChanged__c}' == 'true' || 
+            '{!Contact.MobilePhone_IsChanged__c}' == 'true' || 
+            '{!Contact.OtherPhone_IsChanged__c}' == 'true' || 
+            '{!Contact.Phone_IsChanged__c}' == 'true' || 
+            '{!Contact.Postcode_IsChanged__c}' == 'true' || 
+            '{!Contact.Title_IsChanged__c}' == 'true';
+        if ((is_new || now_status) && approval_status != 'Submit') {
+            alert("鏂板缓鎴栦慨鏀硅仈绯讳汉淇℃伅鍚庯紝璇峰強鏃舵彁浜ゅ鎵广��");
+        }
+	</script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ContactOpenAlert.page-meta.xml b/scr/pages/ContactOpenAlert.page-meta.xml
new file mode 100644
index 0000000..b2405e8
--- /dev/null
+++ b/scr/pages/ContactOpenAlert.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>ContactOpenAlert</label>
+</ApexPage>
diff --git a/scr/pages/CustContPage.page b/scr/pages/CustContPage.page
new file mode 100644
index 0000000..2b7baa3
--- /dev/null
+++ b/scr/pages/CustContPage.page
@@ -0,0 +1,40 @@
+<apex:page controller="CustContController" showHeader="true" sidebar="false" action="{!init}" id="allPage" >
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<style type="text/css"> td>div{display: inline-block;}</style>
+<script>
+function judgement(){
+	blockme();
+	getisOk();
+}
+function back(){
+	var isOk1 = j$(escapeVfId('isOk')).value();
+	if (isOk1!= '') {alert(isOk1);}
+	else{alert('瀹㈡埛涓庤仈绯讳汉閮戒笉濉�,鍋氫笉鍒板晩');}
+}
+</script>
+
+
+	<apex:form id="allForm">
+	<apex:actionFunction name="getisOk" action="{!getisOk}" rerender="ok" oncomplete="back();unblockUI();"></apex:actionFunction>
+		<apex:outputPanel id="ok">
+		 <input type="hidden" id='isOk' value="{!isOk}"/>
+		 </apex:outputPanel>
+		 <table border="0" style="width: 260px;">
+	        <tr>
+	            <td><apex:outputLabel value="瀹㈡埛" style="float: right;"/></td>
+	            <td><apex:inputField value="{!lou.Customer__c}" id="acc"></apex:inputField></td>
+	        </tr>
+	        <tr>
+	            <td><apex:outputLabel value="鑱旂郴浜�" style="float: right;"/></td>    
+	            <td><apex:inputField value="{!lou.Contact__c}" id="con"></apex:inputField></td>
+	        </tr>
+	        <tr>
+	        	<td style="text-align: center;" colspan="2">
+	        		<apex:commandButton onclick="judgement();return false;" value="鍒ゆ柇" style="width: 60px;"/>
+	        	</td>
+	        </tr>
+	     </table>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/CustContPage.page-meta.xml b/scr/pages/CustContPage.page-meta.xml
new file mode 100644
index 0000000..ab4728f
--- /dev/null
+++ b/scr/pages/CustContPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>CustContPage</label>
+</ApexPage>
diff --git a/scr/pages/DataLoadAccount.page b/scr/pages/DataLoadAccount.page
new file mode 100644
index 0000000..6684935
--- /dev/null
+++ b/scr/pages/DataLoadAccount.page
@@ -0,0 +1,197 @@
+<apex:page controller="DataLoadAccountController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="/soap/ajax/29.0/connection.js"/>
+    <apex:includeScript value="/soap/ajax/29.0/apex.js"/>
+
+    <style type="text/css">
+
+    </style>
+
+    <script type="text/javascript">
+
+        function saveJs() {
+            blockme();
+            save();
+        }
+        // 鍏抽棴瀵煎叆椤甸潰
+        function closeJs(){
+            window.parent.opener=null;
+            window.parent.open('', '_self', ''); 
+            setTimeout('window.parent.close()', 10000);
+        }
+        // 璋冪敤鐖堕〉闈㈢殑鏂规硶鍒锋柊鐖堕〉闈�
+        function refreshPage(){
+            window.opener.refreshPage(); 
+            window.close();
+        }
+	</script>
+	<apex:form id="allForm">
+        <apex:actionFunction name="save" action="{!save}" rerender="allForm" onComplete="unblockUI();refreshPage();closeJs();"></apex:actionFunction>
+        <input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+		<apex:pageBlock title="瀹㈡埛-甯傚満娲诲姩鍏崇郴" id="allBlock">
+			<apex:pageblocksection columns="1" title="瀹㈡埛" id="CampaignRelationship">
+				<apex:outputPanel >
+					<DIV style="OVERFLOW-Y: hidden; OVERFLOW-X:auto;width:1260px">
+						 
+        	    		<div id="CampaignRelationship:tablediv" style="OVERFLOW-X: hidden; OVERFLOW-Y:auto;width:1800px; height:400px">
+
+	    					<table id="theTable_header" border="0" style ="width:1800px;text-align: center;"   styleClass="list">
+                            <thead>
+                                <tr>
+
+                                    <td style ="width: 1%;text-align: center" scope="col">No</td>
+                                    <!-- 鍒嗛噹 -->
+                                    <td style ="width: 2%;text-align: center" scope="col">鍒嗛噹</td>
+                                    <!-- 瀹㈡埛 -->
+                                    <td style ="width: 10%;text-align: center" scope="col">瀹㈡埛</td>
+                                    <!-- 閮ㄩ棬鍚嶇О -->
+                                    <td style ="width: 5%;text-align: center" scope="col">閮ㄩ棬鍚嶇О.</td>
+                                    <!-- 瀹℃壒浜� -->
+                                    <td style ="width: 3%;;text-align: center" scope="col">瀹℃壒浜�</td>
+                                    <!-- 鐪� -->
+                                    <td style ="width: 3%;text-align: center" scope="col">鐪�</td>
+                                    <!-- 鍩庡競 -->
+                                    <td style ="width: 3%;text-align: center" scope="col">鍩庡競</td>
+                                    <!-- 瀹㈡埛鍦板潃1 -->
+                                    <td style ="width: 10%;text-align: center" scope="col">瀹㈡埛鍦板潃1 </td>
+                                    <!-- 閭紪 -->
+                                    <td style ="width: 5%;text-align: center" scope="col">閭紪</td>
+                                    <!-- Sub Use -->
+                                    <td style ="width: 5%;text-align: center" scope="col">Sub Use</td>
+
+                                    
+                                    <!-- 甯︽暀鏃堕暱 -->
+                                    <!-- 甯︽暀鑰呮剰瑙佸缓璁� -->
+                                    <td style ="width: 8%;text-align: center" scope="col">鑻辨枃鍚嶇О.</td>
+                                    <!-- 琚甫鏁欒�呭弽棣� -->
+                                    <td style ="width: 4%;text-align: center" scope="col">瀹㈡埛鏉ユ簮. </td>
+                                    <!-- 澶囨敞 -->
+                                    <td style ="width: 5%;text-align: center" scope="col">鐢ㄦ埛灞炴��</td>
+                                    <td style ="width: 5%;text-align: center" scope="col">瀹㈡埛绫诲瀷</td>
+                                    <td style ="width: 5%;text-align: center" scope="col">澶囨敞</td>
+                                    <td style ="width: 3%;text-align: center" scope="col">濮撴皬</td>
+                                    <td style ="width: 10%;text-align: center" scope="col">鑱旂郴浜哄湴鍧�1.</td>
+                                    <td style ="width: 5%;text-align: center" scope="col">鎵嬫満.</td>
+                                    <td style ="width: 3%;text-align: center" scope="col">閭斂缂栫爜.</td>
+                                    <td style ="width: 5%;text-align: center" scope="col">澶囨敞</td>
+
+                                </tr>
+                            </thead>
+                        </table>
+                            <apex:dataTable value="{!ACInfoList}"  var="acInfo" id="theTable_content" border="0" 
+    	        			style="width:1800px;border-bottom-width: 0px; font-size:11px; border-spacing:0;text-align: center;" styleClass="list"> 
+    	        				 <apex:column style="width: 1%">
+                        			<apex:outputText value="{!acInfo.lineNo}" style="resize:vertical;width: 95%"/>
+                        		</apex:column>
+    	        				 <apex:column style="width: 2%">
+                        			<apex:outputField value="{!acInfo.accountpage.ProductSegment__c}" style="resize:vertical;width: 95%"/>
+                        		</apex:column>
+                        		<apex:column style="width: 10%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.FacilityNameD__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.FacilityNameD__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 5%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.DivisionName_D__c}" style="resize:vertical;width: 95%"/> -->
+                        		    <c:PDFWbr targetStr="{!acInfo.accountpage.DivisionName_D__c}"/>
+                                </apex:column>
+                        		<apex:column style="width: 3%">
+                        			<apex:outputField value="{!acInfo.accountpage.DealerSelectOwner__c}" style="resize:vertical;width: 95%"/>
+                                    <!-- <c:PDFWbr targetStr="{!acInfo.accountpage.DealerSelectOwner__r.Name}"/> -->
+                        		</apex:column>
+                        		<apex:column style="width: 3%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.Province__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.Province__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 3%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.CityD__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.CityD__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 10%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.Address1D__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.Address1D__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 5%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.PostCodeD__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.PostCodeD__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 5%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.Sub_UseD__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.Sub_UseD__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 8%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.EnglishNameD__c}"  style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.EnglishNameD__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 4%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.CustomerSource__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.CustomerSource__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 5%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.UserType__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.UserType__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 5%">
+                        			<!-- <apex:outputField value="{!acInfo.accountpage.TargetCustomer__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.TargetCustomer__c}"/>
+                        		</apex:column>
+                                <apex:column style="width: 5%">
+                                    <!-- <apex:outputField value="{!acInfo.accountpage.Remark__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.accountpage.Remark__c}"/>
+                                </apex:column>
+                        		<apex:column style="width: 3%">
+                        			<!-- <apex:outputField value="{!acInfo.contactpage.LastName}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.contactpage.LastName}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 10%">
+                        			<!-- <apex:outputField value="{!acInfo.contactpage.Address1D__c}" style="resize:vertical;width: 95%"/> -->
+                        		    <c:PDFWbr targetStr="{!acInfo.contactpage.Address1D__c}"/>
+                                </apex:column>
+                        		<apex:column style="width: 5%">
+                        			<!-- <apex:outputField value="{!acInfo.contactpage.MobilePhoneD__c}"  style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.contactpage.MobilePhoneD__c}"/>
+                        		</apex:column>
+                        		<apex:column style="width: 4%">
+                        			<!-- <apex:outputField value="{!acInfo.contactpage.PostcodeD__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.contactpage.PostcodeD__c}"/>
+                        		</apex:column>
+                                <apex:column style="width: 5%">
+                                    <!-- <td style ="width: 5%" scope="col">鑱旂郴浜哄娉�</td> -->
+                                    <!-- <apex:outputField value="{!acInfo.contactpage.Remark__c}" style="resize:vertical;width: 95%"/> -->
+                                    <c:PDFWbr targetStr="{!acInfo.contactpage.Remark__c}"/>
+                                </apex:column>
+    	        			</apex:dataTable>
+
+	    				 </div>
+					</DIV>
+				</apex:outputPanel>
+				
+			</apex:pageblocksection>
+		</apex:pageBlock>
+        <!-- <apex:commandButton action="{!save}"  value="淇濆瓨" style="width: 70px;" oncomplete="unblockUI();"></apex:commandButton> -->
+        <apex:commandButton onclick="saveJs();return false;"   value="淇濆瓨" style="width: 70px;" oncomplete="unblockUI();"></apex:commandButton>
+	</apex:form>
+	<apex:form id="fileForm">
+		<apex:outputPanel rendered="{!errorflag}" layout="none">
+            <table width="100%">
+                <tr>
+                    <!-- <apex:messages styleClass="editListError" /> -->
+                    <apex:messages />
+                </tr>
+            </table>
+        </apex:outputPanel>
+        <table border="0">
+	        <tr>
+	            <th>瀹㈡埛瀵煎叆锛�</th>
+	            <th>1.<apex:inputFile value="{!contentFile}" filename="{!nameFile}"/></th>
+	        </tr>
+	        <tr>
+	            <th>&nbsp;</th>
+	            <th>2.&nbsp;<apex:commandButton action="{!csvRead}" value="璇诲彇CSV" /></th>
+	        </tr>
+            
+	    </table>
+	</apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/DataLoadAccount.page-meta.xml b/scr/pages/DataLoadAccount.page-meta.xml
new file mode 100644
index 0000000..7dd98b6
--- /dev/null
+++ b/scr/pages/DataLoadAccount.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>DataLoadAccount</label>
+</ApexPage>
diff --git a/scr/pages/DeliveryConfirmPDF.page b/scr/pages/DeliveryConfirmPDF.page
new file mode 100644
index 0000000..b237c18
--- /dev/null
+++ b/scr/pages/DeliveryConfirmPDF.page
@@ -0,0 +1,269 @@
+<apex:page controller="DeliveryConfirmPDFController" showHeader="false" sidebar="false"  id="allPage" action="{!init}" renderAs="pdf">  <!-- renderAs="pdf" -->
+<html>
+<head>
+    <style>
+         @page {
+            margin: 1mm 1mm 1mm 1mm;   
+        }
+
+    </style>
+</head>
+<body style="font-family: Arial Unicode MS; page-break-inside: auto;font-size: 10px;">
+    <apex:image value="{!URLFOR($Resource.pdfSign)}" width="80"  style="position:absolute; left:300px; top:100px;"/>
+    <p style="text-align: center; display: block;font-size: 25px;">浠櫙閫氭牱鏈哄�熺敤鍗�</p>
+    <table style="border: 2px solid black; width: 100%;border-collapse:collapse;" border="solid">
+        <tr>
+            <td align="right" width="100px"><apex:outputText value="鐢宠鏃ユ湡锛�" /></td>
+            <td width="600"><apex:outputField value="{!la.Approval_Date__c}"/></td>
+            <td align="right" width="100"><apex:outputText value="鍊熺敤缂栧彿锛�"/></td>
+            <td width="300"><apex:outputText value="{!la.loaner_request_number__c}"/></td>
+        </tr>
+        <tr>
+        
+            <td align="right">鍊熺敤鏂癸細</td>
+
+            <apex:outputPanel rendered="{!IF(la.CreatorUserType__c == 'PowerPartner', 'true', 'false')}" layout="none">
+                <td><apex:outputText value="{!agentName}"/></td>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!IF(la.CreatorUserType__c != 'PowerPartner', 'true', 'false')}" layout="none">
+                <td><apex:outputText value="{!la.Applicant_department__c}"/></td>
+            </apex:outputPanel>
+            
+            <td align="right">鍊熺敤鎷呭綋锛�</td>
+            <td><apex:outputText value="{!la.Loaner_Ser__c}"/></td>
+        </tr>
+        <tr>
+            <td align="right">鍊熺敤鏃ユ湡锛�</td>
+            <td><apex:outputText value="{!lab.ladate}"/></td>
+            <td align="right">鍊熺敤鏈熼檺锛�</td>
+            <td><apex:outputText value="{!lab.ladateNumS}"/></td>
+        </tr>
+        <tr>
+            <td align="right">鍊熺敤鐩殑锛�</td>
+            <td ><apex:outputText value="{!la.Demo_purpose__c}"/></td>
+            <td align="right">鏍锋満搴撳瓨鍦帮細</td>
+            <td><apex:outputText value="{!la.loaner_place__c}"/></td>
+            
+        </tr>
+        <tr>
+             
+            
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', false , true)}" layout="none">
+                <td align="right">澶囨敞锛�</td>
+                <td colspan="3"><apex:outputText value="{!la.loaner_Remark__c}"/></td>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                <td align="right">澶囨敞锛�</td>
+                <td ><apex:outputText value="{!la.loaner_Remark__c}"/></td>
+                <td align="right">CRM缂栧彿:</td>
+                <td ><apex:outputText value="{!OCM_Number}"/></td>
+            </apex:outputPanel>
+        </tr>
+    </table>
+    <br style="height: 0.5em;" />
+
+
+    <table style="border: 2px solid black; width: 100%;border-collapse:collapse;" border="solid">
+        <tr>
+            <td align="right" width="90">瀵勯�佹柟寮忥細</td>
+            <td colspan="3">
+                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+                <apex:outputPanel rendered="{!isSelf}" layout="none"> <img src="/img/checkbox_checked.gif"/></apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(isSelf,'false','true')}" layout="none"> <img src="/img/checkbox_unchecked.gif"/></apex:outputPanel>
+                鑷彁 
+                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+                <apex:outputPanel rendered="{!isExpress}" layout="none"> <img src="/img/checkbox_checked.gif"/></apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(isExpress,'false','true')}" layout="none"> <img src="/img/checkbox_unchecked.gif"/></apex:outputPanel> 
+                蹇��
+                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+                <apex:outputPanel rendered="{!isRenew}" layout="none"> <img src="/img/checkbox_checked.gif"/></apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(isRenew,'false','true')}" layout="none"> <img src="/img/checkbox_unchecked.gif"/></apex:outputPanel>
+                缁��
+            </td>
+        </tr>
+
+        <tr>
+            
+            <td width="90">&nbsp;&nbsp;</td>
+            <td colspan="3">&nbsp;&nbsp;</td>
+
+        </tr>
+
+        <tr>
+            
+            <td align="right" width="90">瀵勯�佸湴鍧�锛�</td>
+            <td colspan="3"><apex:outputField value="{!la.direct_shippment_address__c}"/></td>
+        </tr>
+
+        <tr>
+            
+            <td align="right" width="90">鑱旂郴浜猴細</td>
+            <td><apex:outputField value="{!la.Loaner_receive_staff__c}"/></td>
+            <td align="right" width="90">鑱旂郴鐢佃瘽锛�</td>
+            <td width="200"><apex:outputField value="{!la.Loaner_receive_staff_phone__c}"/></td>
+
+        </tr>
+
+    </table>
+    <br/>
+    <table style="border: 2px solid black; width: 100%;border-collapse:collapse;" border="solid">
+        
+        <caption style="text-align: left;font-size: 15px;">鐢ㄦ埛淇℃伅锛�</caption>
+
+        <colgroup>
+            <col width="50%" />
+            <col width="20%" />
+            <col width="10%" />
+            <col width="20%" />
+        </colgroup>
+        <tr>
+            <th style="text-align: center; border-bottom-style: ridge;">瀹㈡埛鍚嶇О</th>
+            <th style="text-align: center; border-bottom-style: ridge;">瀹㈡埛閮ㄩ棬</th>
+            <th style="text-align: center; border-bottom-style: ridge;">鑱旂郴浜�</th>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">鑱旂郴鐢佃瘽</th>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', false , true)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">鍊熺敤鏃堕棿</th>
+            </apex:outputPanel>
+        </tr>
+        <apex:repeat value="{!luData}" var="luLine" id="lus">
+        <tr>
+            <td class="dataCell" style="text-align: center;">
+                <apex:outputText value="{!luLine.lu.Customer__r.Name}"/>
+            </td>
+            <td class="dataCell" style="text-align: center;">
+                <apex:outputText value="{!luLine.lu.Customer__r.DivisionName__c}"/>
+            </td>
+            <td class="dataCell" style="text-align: center;">
+                <apex:outputText value="{!luLine.lu.Contact__r.Name}"/>
+            </td>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                <td class="dataCell" style="text-align: center;">
+                    <apex:outputText value="{!luLine.lu.Contact__r.Phone}"/>
+                </td>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', false , true)}" layout="none">
+                <td class="dataCell" style="text-align: center;">
+                    <apex:outputText value="{!luLine.borrowDate}"/>
+                </td>
+            </apex:outputPanel>
+            
+        </tr>
+        </apex:repeat>
+
+    </table>
+    <br/>
+    <table style="border:2px solid black; width: 100%;border-collapse: collapse; " border="solid">
+        <caption style="text-align: left;font-size: 15px;" >閰嶇疆娓呭崟:</caption>
+
+        <tr>
+            
+            <th style="text-align: center; border-bottom-style: ridge;">搴忓彿</th>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI', true , false)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+            </apex:outputPanel>
+            <th style="text-align: center; border-bottom-style: ridge;">EC Code</th>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">鎻忚堪</th>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', false , true)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">搴忓垪鍙�</th>
+            </apex:outputPanel>
+            <th style="text-align: center; border-bottom-style: ridge;">鏁伴噺</th>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">鏈鸿韩鍙�</th>
+                <th style="text-align: center; border-bottom-style: ridge;">鏈鸿韩鍙�1</th>
+                <th style="text-align: center; border-bottom-style: ridge;">璧勪骇缂栧彿</th>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'IE' || la.Equipment_Type__c == 'RVI', true , false)}" layout="none">
+                <th style="text-align: center; border-bottom-style: ridge;">鏍锋満搴撲綅</th>
+            </apex:outputPanel>
+   
+            
+            <th style="text-align: center; border-bottom-style: ridge;">澶囨敞</th>
+        </tr>
+        <apex:variable value="{!1}" var="cnt" />
+        <apex:repeat value="{!dataLines}" var="line" id="lines">
+       
+            <tr>
+                <td class="dataCell" style="text-align: center;">
+                    <apex:outputText value="{!cnt}"/>
+                </td>
+                <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI', true , false)}" layout="none">
+                    <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                    </td>
+                </apex:outputPanel> 
+                <td class="dataCell" style="text-align: center;">
+                    <apex:outputText value="{!line.lad.ECCode__c}"/>
+                </td>
+                <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                    <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.LOANER__r.Description}"/>
+                    </td>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', false , true)}" layout="none">
+                    <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                    </td>
+                </apex:outputPanel>
+                <td class="dataCell" style="text-align: center;">
+                    <apex:outputText value="{!line.num}"/>
+                </td>
+                <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none">
+                     <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.LOANER__r.SerialNumber}"/>
+                    </td>
+                     <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.LOANER__r.SerialNumber1__c}"/>
+                    </td>
+                     <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.LOANER__r.Internal_Asset_number__c}"/>
+                    </td>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'IE' || la.Equipment_Type__c == 'RVI', true , false)}" layout="none">
+                    <td class="dataCell" style="text-align: center;">
+                        <apex:outputText value="{!line.lad.LOANER__r.Description}"/>
+                    </td>
+                </apex:outputPanel>
+                <td class="dataCell" style="text-align: center;">
+                    <apex:outputText value="{!line.lad.Remark__c}"/>
+                </td>
+                
+            </tr>
+
+            <!-- <apex:outputPanel rendered="{!cnt == 32}" layout="none">
+                <div style="page-break-after: always;"/> 
+                
+            </apex:outputPanel>  -->
+        <apex:variable value="{!cnt + 1}" var="cnt" />
+        
+        </apex:repeat>
+
+
+    </table>
+    <br/>
+
+     <apex:outputPanel rendered="{!IF((rowNum > 26 && rowNum <34) || (rowNum > 80 && rowNum < 87),'true','false')}" layout="none">
+         <div style="page-break-after: always;"/>
+     </apex:outputPanel>
+
+    <table style="border: 2px solid black;width: 100%;">
+        <caption style="text-align: left;font-size: 15px;" >鏍锋満锛堝鍝侊級鍊熺敤椤荤煡锛�</caption>
+        <tr><td>1.璇锋竻鐐瑰強楠屾敹鏍锋満锛堝鍝侊級鍚庡湪姝ゅ崗璁功涓婄瀛楁垨鐩栫珷銆�</td></tr>
+        <tr><td>2.璇峰皢鏍锋満锛堝鍝侊級浜庤吹鏂圭‘璁や箣鏈熼檺鍐呭綊杩樸��</td></tr>
+        <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', true , false)}" layout="none"> 
+            <tr><td>3.濡傚�熺敤涔嬫牱鏈猴紙澶囧搧锛夊湪鍊熺敤鏈熼棿鎹熷潖(鍚鎷嗛浂閮ㄤ欢)锛屾垜鏂规湁鏉冭姹傝吹鏂规寜鐩稿簲閲戦璧斿伩鎴栨壙鎷呯淮淇垂鐢ㄣ��</td></tr>
+        </apex:outputPanel>
+        <apex:outputPanel rendered="{!IF(la.Equipment_Type__c == 'BS', false, true)}" layout="none"> 
+            <tr><td>3.濡傚�熺敤涔嬫牱鏈猴紙澶囧搧锛夊湪鍊熺敤鏈熼棿鎹熷潖锛屾垜鏂规湁鏉冭姹傝吹鏂规寜鐩稿簲閲戦璧斿伩鎴栨壙鎷呯淮淇垂鐢ㄣ��</td></tr>
+        </apex:outputPanel>
+        <tr><td>4.鍊熷嚭鏍锋満鍦ㄦ湭寰佸緱鎴戞柟鐨勮鍙紝璐垫柟涓嶅緱杞�熺涓夋柟浣跨敤锛屽惁鍒欏皢涓鍊熺敤骞惰拷绌惰矗浠汇��</td></tr>
+        <tr><td>5.浠櫙閫氭湁鏉冩牴鎹渶瑕侀殢鏃舵敹鍥炲�熷嚭鐨勬牱鏈恒��</td></tr>
+    </table>
+
+</body>
+</html>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/DeliveryConfirmPDF.page-meta.xml b/scr/pages/DeliveryConfirmPDF.page-meta.xml
new file mode 100644
index 0000000..1537f2c
--- /dev/null
+++ b/scr/pages/DeliveryConfirmPDF.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>DeliveryConfirmPDF</label>
+</ApexPage>
diff --git a/scr/pages/EquipmentLoanerApply.page b/scr/pages/EquipmentLoanerApply.page
new file mode 100644
index 0000000..8f5573f
--- /dev/null
+++ b/scr/pages/EquipmentLoanerApply.page
@@ -0,0 +1,563 @@
+<apex:page Controller="EquipmentLoanerApplyController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="鏍锋満鍒嗛厤">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <script>
+function searchProductJs() {
+    blockme(); 
+    searchLoanerApp();
+}
+function notArrDetJs(setid,deatilNo){
+
+    blockme();
+    getLoanerSetdet(setid);
+    var productCount = j$(escapeVfId('loanerSetNo')).value();
+    for (var i = 0; i < productCount; i++) {
+        j$(escapeVfId('allPage:allForm:allBlock:dataBlock0:loanerSetTable:' + i +':loanerSetNamelinK')).css('color', 'black');
+    }
+    j$(escapeVfId('allPage:allForm:allBlock:dataBlock0:loanerSetTable:' + deatilNo +':loanerSetNamelinK')).css('color', 'red');
+}
+
+function overwriteRedJs(){
+    var productCount = j$(escapeVfId('loanerSetNo')).value();
+    for (var i = 0; i < productCount; i++) {
+        j$(escapeVfId('allPage:allForm:allBlock:dataBlock0:loanerSetTable:' + i +':loanerSetNamelinK')).css('color', 'black');
+    }
+}
+function sortTableJs(key) {
+    blockme();
+    sortTable(key);
+}
+function saveJs() {
+    blockme();
+    save();
+}
+function checkAllJs() {
+    var productCount = j$(escapeVfId('pageRecordNo')).value();
+    if (j$(escapeVfId('checker')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            if (document.getElementById('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i +':equipmentSetRowCheckbox').disabled == false) {
+                j$(escapeVfId('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i + ':equipmentSetRowCheckbox')).attr('checked',true);
+            }
+        }
+    }else{
+        for (var i = 0; i < productCount; i++   ) {
+            if (document.getElementById('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i +':equipmentSetRowCheckbox').disabled == false) {
+                j$(escapeVfId('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i + ':equipmentSetRowCheckbox')).attr('checked',false);
+            }
+        }
+    }
+
+}
+
+function ComputePriceJs(j) {
+    var z;
+    var a = j.id;
+    var i=a.substring(0,a.lastIndexOf(':'));
+    i = i.substring(0,i.lastIndexOf(':'));
+    z  =  parseFloat(j$(escapeVfId(a)).value());
+    if(isNaN(z)){z=0.00;}
+    if(z!=null&&z!=0&&z!=''){
+    j$(escapeVfId(i+':equipmentSetRowCheckbox')).attr('checked',true);
+    }else{
+    j$(escapeVfId(i+':equipmentSetRowCheckbox')).attr('checked',false);
+    }
+}
+
+// 璁$畻鑷劧鏃�
+function getDays(date1,date2){
+    var dayCount = 0;
+    if(date1 && date2){
+        //灏嗘椂闂村瓧绗︿覆杞寲涓鸿窛绂�1970骞�1鏈�1鏃ュ崍澶滈浂鏃剁殑鏃堕棿闂撮殧鐨勬绉掓暟
+        var time1 = Date.parse(date1);
+        var time2 = Date.parse(date2);
+
+        //灏嗕袱涓椂闂寸浉鍑�,姹傚嚭鐩搁殧鐨勫ぉ鏁�
+        var dayCount = (Math.ceil(time2 - time1))/1000/60/60/24;
+    }
+    return dayCount;
+}
+
+//椤甸潰鍔犺浇 鏍锋満鏃ユ湡鍒濆鍖�
+/*function onLoadDirction(){
+    var SDay = j$(escapeVfId('allPage:allForm:allBlock:Rental_SDate')).value();
+    var EDay = j$(escapeVfId('allPage:allForm:allBlock:Rental_EDate')).value();
+    var dayCount = 0;
+    var productCount = j$(escapeVfId('pageRecordNo')).value();
+    dayCount = getDays(SDay,EDay);
+    for (var i = 0; i < productCount; i++) {
+        //j$(escapeVfId('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i + ':Rental_Start_Date')).attr('checked',true);
+        document.getElementById('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i + ':Rental_Start_Date').innerHTML = SDay;
+        document.getElementById('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i + ':Rental_End_Date').innerHTML = EDay;
+        document.getElementById('allPage:allForm:allBlock:dataBlock:equipmentSetTable:' + i + ':SEdayCount').innerHTML = dayCount;
+    }
+
+}*/
+//window.sfdcPage.appendToOnloadQueue(function() { onLoadDirction(); });
+    </script>
+    <style>
+div#out_Div {
+  position:relative;
+  overflow: hidden;
+  width: 820px;
+}
+div#out_Div_L {
+  position:relative;
+  overflow: hidden;
+  float:left;
+  width: 413px;
+}
+div#in_Div {
+  position:relative;
+  overflow: auto;
+  width: 837px;
+  height: 314px;
+}
+div#in_Div_L {
+  position:relative;
+  overflow: hidden;
+  float:left;
+  width: 413px;
+  height: 297px;
+}
+div#all {
+  overflow: hidden;
+  width: 1250px;
+}
+    </style>
+    <apex:form id="allForm">
+    <apex:actionFunction name="sortTable" action="{!sortTable}" rerender="dataBlock, message" onComplete="unblockUI();overwriteRedJs();">
+        <apex:param name="firstParam" assignTo="{!sortKey}" value="" />
+    </apex:actionFunction>
+    <apex:actionFunction name="searchLoanerApp" action="{!searchLoanerApp}" rerender="dataBlock, message" onComplete="unblockUI();overwriteRedJs();">
+        </apex:actionFunction>
+    <apex:actionFunction name="getLoanerSetdet" action="{!getLoanerSetdet}" rerender="dataBlock, message" onComplete="unblockUI();">
+        <apex:param name="firstParam" assignTo="{!setId}" value="" />
+    </apex:actionFunction>
+    <apex:actionFunction name="save" action="{!save}" rerender="message" onComplete="unblockUI();overwriteRedJs();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="鏍锋満鍊熷嚭鐢宠" id="allBlock">
+                <apex:pageBlockButtons location="top" id="pageBlockButton1">
+                    <table>
+                        <tr>
+                            <td width="80%" align="right">
+                                <apex:commandButton value="淇濆瓨" style="width: 120px;" onclick="saveJs();return false;" rerender="dummy"  disabled="{!canSave}"/>
+                            </td>
+                            <td  width="20%" align="right"><apex:commandButton action="{!cancel}" value="杩斿洖鏍锋満鍊熷嚭鐢宠" rerender="dummy"/></td>
+                        </tr>
+                    </table>
+                </apex:pageBlockButtons>
+               
+                <table id="headTable" style="width:1300px">
+                    <colgroup>
+                        <col width="10%"/>
+                        <col width="15%"/>
+                        <col width="10%"/>
+                        <col width="15%"/>
+                        <col width="10%"/>
+                        <col width="15%"/>
+                        <col width="10%"/>
+                        <col width="15%"/>
+                    </colgroup>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.Name.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.Name}"/></td>
+                        <td align="right"></td>
+                        <td align="left"></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.Demo_purpose__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.Demo_purpose__c}"/></td>
+                        <td align="right"></td>
+                        <td align="left"></td>
+                    </tr>
+                     <apex:outputPanel layout="none" rendered="{!IF(OR(loanerApply.Equipment_Type__c == 'IE',loanerApply.Equipment_Type__c == 'RVI'), true , false)}">
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_1__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_1__c}"/></td>
+                         <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount1__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount1__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_11__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_11__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount11__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount11__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_2__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_2__c}"/></td>
+                       <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount2__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount2__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_12__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_12__c}"/></td>
+                         <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount12__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount12__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_3__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_3__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount3__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount3__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_13__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_13__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount13__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount13__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_4__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_4__c}"/></td>
+                         <td align="right">
+                        {!$ObjectType.loaner_application__c.fields.ProductCount4__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount4__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_14__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_14__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount14__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount14__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_5__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_5__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount5__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount5__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_15__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_15__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount15__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount15__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_6__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_6__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount6__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount6__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_16__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_16__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount16__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount16__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_7__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_7__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount7__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount7__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_17__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_17__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount17__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount17__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_8__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_8__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount8__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount8__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_18__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_18__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount18__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount18__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_9__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_9__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount9__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount9__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_19__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_19__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount19__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount19__c}"/></td>
+                    </tr>
+                    <tr>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_10__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_10__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount10__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount10__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.EC_Code_20__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.EC_Code_20__c}"/></td>
+                        <td align="right">{!$ObjectType.loaner_application__c.fields.ProductCount20__c.label} 锛� </td>
+                        <td align="left"><apex:outputField value="{!loanerApply.ProductCount20__c}"/></td>
+                    </tr>
+                     </apex:outputPanel>
+                </table>
+               
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+                <apex:pageBlock id="searchBlock">
+                    <table style="border-collapse: collapse;table-layout:fixed; width:1200px" >
+                        <colgroup>
+                            <col width="8%"/>
+                            <col width="25%"/>
+                            <col width="9%"/>
+                            <col width="25%"/>
+                            <col width="8%"/>
+                            <col width="25%"/>
+                        </colgroup>
+                        <tr>
+                            <td align="right">鏈鸿韩鍙�</td>
+                            <td><apex:inputField value="{!rec.SerialNumber}" style="width:150px"/></td>
+                            <!--<td align="right">{!$ObjectType.Asset.fields.Internal_Asset_number__c.label}</td>
+                            <td><apex:inputField value="{!rec.Internal_Asset_number__c}" style="width:150px"/></td>-->
+                            <td align="right">{!$ObjectType.Asset.fields.EC_Code__c.label}</td>
+                            <td><apex:inputText value="{!assECcode}" style="width:150px"/></td>
+                    <td align="right">{!$ObjectType.Asset.fields.OT_Code__c.label}</td>
+                    <td><apex:inputText value="{!rec.OT_Code__c}" style="width:150px"/></td>
+                </tr>
+                <tr>
+                    <td align="right">{!$ObjectType.Asset.fields.Equipment_Type__c.label}</td>
+                    <td><apex:inputField value="{!rec.Equipment_Type__c}" style="width:150px"/></td>
+                    <td align="right">{!$ObjectType.Asset.fields.loaner_place__c.label}</td>
+                    <td><apex:inputField value="{!rec.loaner_place__c}" style="width:150px"/></td>
+                    <td align="right">{!$ObjectType.Asset.fields.Status.label}</td>
+                    <td><apex:inputField value="{!rec.Status}" style="width:150px"/></td>
+                </tr>
+                <tr>
+                    <!-- IE RVI -->
+                    <apex:outputPanel rendered="{!IF(rec.Equipment_Type__c == 'IE' || rec.Equipment_Type__c == 'RVI', true , false)}">
+                        <td align="right" >{!$ObjectType.Asset.fields.ProductName__c.label}</td>
+                        <td><apex:inputText value="{!assName}" style="width:150px"/></td>
+                        <td></td>
+                        <td></td>
+                        <!--<td align="right">{!$ObjectType.Asset.fields.EC_Code__c.label}</td>
+                        <td><apex:inputText value="{!assECcode}" style="width:150px"/></td>-->
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(rec.Equipment_Type__c == 'NDT' || rec.Equipment_Type__c == 'ANI', true , false)}">
+                        <td align="right" >鏍锋満鍚嶇О</td>
+                        <td><apex:inputText value="{!assName}" style="width:150px"/></td>
+                        <td align="right">{!$ObjectType.Asset.fields.Remarks2__c.label}</td>
+                        <td><apex:inputText value="{!rec.Remarks2__c}" style="width:150px"/></td>
+                    </apex:outputPanel>
+                    
+                    <apex:outputPanel rendered="{!IF(rec.Equipment_Type__c == 'BS' , true , false)}">
+                        <td align="right" >鏍锋満鍚嶇О</td>
+                        <td><apex:inputText value="{!assName}" style="width:150px"/></td>
+                        <td align="right">{!$ObjectType.Asset.fields.Internal_Asset_number__c.label}</td>
+                        <td><apex:inputText value="{!rec.Internal_Asset_number__c}" style="width:150px"/></td>
+                    </apex:outputPanel>
+
+                    
+
+                    <td align="center"  ></td>
+                    <td   ><apex:commandButton value="鎼滅储" style="width: 120px;" onclick="searchProductJs(); return false;" disabled="{!canSearch}"/></td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+                <div style="position: relative;top:0;height:100%;overflow:hidden;overflow-y:auto;-webkit-overflow-scrolling: touch;">
+                <input type="hidden" id="loanerSetNo" value="{!loanerSetNo}" />
+                <apex:pageBlock id="dataBlock0" title="鏍锋満濂楄涓�瑙�" rendered="{!AND(!loanerApply.Loaner_LendOrder__c,loanerApply.Equipment_Type__c != 'NDT',loanerApply.Equipment_Type__c != 'ANI')}">
+                <div style="position: relative;top:0;height:150px;overflow:hidden;overflow-y:auto;-webkit-overflow-scrolling: touch;">
+                    <table class="list" border="0" cellpadding="0" cellspacing="0" id="example0">
+                        <tr class="headerRow">
+                            <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Name.label}</th>
+                           
+
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.set_type__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.SerialNumber__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Internal_Asset_number__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.status__c.label}</th>
+                            </apex:outputPanel>
+
+                            <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Equipment_Type__c.label}</th>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', false , true)}">
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Remarks__c.label}</th>
+                            </apex:outputPanel>
+                             <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.loaner_place__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Loaner_Set__c.fields.Reservation_information__c.label}</th>
+                            </apex:outputPanel>
+
+                        </tr>
+                        <apex:repeat value="{!loanerSetRecords}" var="records" id="loanerSetTable">
+                        <tr class="dataRow">
+                            <td class="dataCell" align="center">
+                                <apex:outputLink onclick="notArrDetJs('{!records.lSet.Id}','{!records.deatilNo}'); return false;" id="loanerSetNamelinK" ><apex:outputField value="{!records.lSet.Name}" id="loanerSetName"/></apex:outputLink>
+                            </td>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                                <td class="dataCell" align="center">{!records.lSet.set_type__c}</td>
+                                <td class="dataCell" align="center">{!records.lSet.SerialNumber__c}</td>
+                                <td class="dataCell" align="center">{!records.lSet.Internal_Asset_number__c}</td>
+                                <td class="dataCell" align="center">{!records.lSet.status__c}</td>
+                            </apex:outputPanel>
+                            <td class="dataCell" align="center">
+                                {!records.lSet.Equipment_Type__c}
+                            </td>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', false , true)}">
+                                <td class="dataCell" align="center">
+                                    {!records.lSet.Remarks__c}
+                                </td>
+                            </apex:outputPanel>
+                             <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                                <td class="dataCell" align="center">{!records.lSet.loaner_place__c}</td>
+                                <td class="dataCell" align="center">{!records.lSet.Reservation_information__c}</td>
+                            </apex:outputPanel>
+                        </tr>
+                        </apex:repeat>
+                    </table>
+                    </div>
+                </apex:pageBlock>
+                </div>
+                <div style="position: relative;top:0;height:700px;overflow:hidden;overflow-y:auto;-webkit-overflow-scrolling: touch;">
+                <apex:pageBlock id="dataBlock">
+                <input type="hidden" id="pageRecordNo" value="{!pageRecordNo}" />
+                    <table class="list" border="0" cellpadding="0" cellspacing="0" id="example">
+                        <tr class="headerRow">
+                            <th><input type='checkbox' onClick="checkAllJs()" id='checker' /></th>
+
+                            <apex:outputPanel layout="none" rendered="{!IF(AND((loanerApply.Equipment_Type__c == 'NDT' || loanerApply.Equipment_Type__c == 'ANI'),userType == 'PowerPartner'), false , true)}">
+                            <th style="text-align: center;">{!$ObjectType.loaner_application_detail__c.fields.Name.label}</th>
+
+                            </apex:outputPanel>
+                             <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'NDT' || loanerApply.Equipment_Type__c == 'ANI', true , false)}">
+                                <th style="text-align: center;">浜у搧鍚嶇О</th>
+                                <th style="text-align: center;">鏍锋満鍚嶇О</th>
+                            </apex:outputPanel>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                            <th style="text-align: center;">鏍锋満鍚嶇О</th> 
+                            <th style="text-align: center;">绫诲瀷</th>
+
+                          <!--   <th style="text-align: center;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th> -->
+
+                            </apex:outputPanel> 
+                            <th style="text-align: center;"><a href="#" onclick="sortTableJs('0');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</a>{!sortOrder[0]}</th>
+                            <!--<th style="text-align: center;"><a href="#" onclick="sortTableJs('1');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</a>{!sortOrder[1]}</th>-->
+
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , false , true)}">
+                                <th style="text-align: center;"><a href="#" onclick="sortTableJs('1');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</a>{!sortOrder[2]}</th>
+                            </apex:outputPanel>
+                            <th style="text-align: center;"><a href="#" onclick="sortTableJs('2');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</a>{!sortOrder[3]}</th>
+                            <th style="text-align: center;"><a href="#" onclick="sortTableJs('3');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.loaner_place__c.label}</a>{!sortOrder[3]}</th>
+                            <!-- <th style="text-align: center;">鏍锋満鍚嶇О</th> -->
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , false , true)}">
+                                <th style="text-align: center;width: 50Px;"><a href="#" onclick="sortTableJs('4');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.loaner_Status__c.label}/{!$ObjectType.Asset.fields.Count_can_allocate_F__c.label}</a>{!sortOrder[4]}</th>
+                            </apex:outputPanel>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , true , false)}">
+                                <th style="text-align: center;width: 50Px;"><a href="#" onclick="sortTableJs('4');return false;" style="text-decoration: underline;">{!$ObjectType.loaner_application_detail__c.fields.loaner_Status__c.label}</a>{!sortOrder[4]}</th>
+                            </apex:outputPanel>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'NDT' || loanerApply.Equipment_Type__c == 'ANI', true , false)}">
+                                <th style="text-align: center;">{!$ObjectType.Asset.fields.Rental_Customer__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Asset.fields.Rental_end_Date__c.label}</th>
+                            </apex:outputPanel>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                                <th style="text-align: center;">{!$ObjectType.Asset.fields.Rental_Customer__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Asset.fields.Rental_Start_Date__c.label}</th>
+                                <th style="text-align: center;">{!$ObjectType.Asset.fields.Rental_end_Date__c.label}</th>
+                            </apex:outputPanel>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , false , true)}">
+                                <th style="text-align: center;">鍊熷嚭鏁伴噺</th>
+                            </apex:outputPanel>
+
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                                <th style="text-align: center;">鏁伴噺</th>
+                                <th style="text-align: center;">鎻忚堪</th> 
+                            </apex:outputPanel> 
+
+                            <th style="text-align: center;">{!$ObjectType.loaner_application_detail__c.fields.Remark__c.label}</th>
+                        </tr>
+                        <apex:repeat value="{!equipmentSetRecords}" var="records" id="equipmentSetTable">
+                        <tr class="dataRow">
+                            <td>
+                                <apex:inputCheckbox value="{!records.check}" onclick="#" id="equipmentSetRowCheckbox"/>
+                            </td>
+                            
+                            <apex:outputPanel layout="none" rendered="{!IF(AND((loanerApply.Equipment_Type__c == 'NDT' || loanerApply.Equipment_Type__c == 'ANI'),userType == 'PowerPartner'), false , true)}">
+                            <td class="dataCell" align="center">
+                                {!records.lad.Name}
+                            </td>
+                            </apex:outputPanel>
+                             <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'NDT' || loanerApply.Equipment_Type__c == 'ANI', true , false)}">
+                            <td class="dataCell" align="center">
+                                 {!records.aset.ProductName__c}
+                            </td>
+                            <td class="dataCell" align="center">
+                                 {!records.aset.Name}
+                            </td>
+                            </apex:outputPanel>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , true , false)}">
+                            <td class="dataCell" align="center">
+                                 {!records.aset.Name}
+                            </td>
+                            <td class="dataCell" align="center">
+                                 {!records.aset.AssetType__c}
+                            </td>
+                            <!-- <td class="dataCell" align="center">
+                                 {!records.aset.Internal_Asset_number__c}
+                            </td> -->
+                            </apex:outputPanel>
+                            <td class="dataCell" align="center">
+                                {!records.aset.SerialNumber}
+                            </td>
+                            <!--<td class="dataCell" align="center">
+                                {!records.aset.Internal_Asset_number__c}
+                            </td>-->
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , false , true)}">
+                                <td class="dataCell" align="center">
+                                    {!records.aset.OT_Code__c}
+                                </td>
+                            </apex:outputPanel>
+                            <td class="dataCell" align="center">
+                                {!records.aset.EC_Code__c}
+                            </td>
+                            <!-- <td class="dataCell" align="center">
+                                {!records.aset.Equipment_Type__c}
+                            </td> -->
+                            <td class="dataCell" align="center">
+                                {!records.aset.loaner_place__c}
+                            </td>
+                            
+                            <td class="dataCell" align="center">
+                                <apex:variable var="v" value="" rendered="{!!records.showNo}" > {!records.aset.Status}</apex:variable>
+                                <apex:variable var="v" value="" rendered="{!records.showNo}"> {!records.aset.Count_can_allocate_F__c} </apex:variable>
+                            </td>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'NDT' || loanerApply.Equipment_Type__c == 'ANI', true , false)}">
+                            <td class="dataCell" align="center">
+                                <apex:outputField value="{!records.aset.Rental_Customer__r.Name}"></apex:outputField>
+                            </td>
+                            <td class="dataCell" align="center">
+                               <apex:outputField value="{!records.aset.Rental_end_Date__c}"></apex:outputField>
+                            </td>
+                            </apex:outputPanel>
+
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS', true , false)}">
+                            <td class="dataCell" align="center">
+                                <apex:outputField value="{!records.aset.Rental_Customer__r.Name}"></apex:outputField>
+                            </td>
+                            <td class="dataCell" align="center">
+                                <apex:outputField value="{!records.aset.Rental_Start_Date__c}"></apex:outputField>
+                            </td>
+                            <td class="dataCell" align="center">
+                               <apex:outputField value="{!records.aset.Rental_end_Date__c}"></apex:outputField>
+                            </td>
+                            </apex:outputPanel>
+
+                            <td class="dataCell" align="center">
+                            <apex:variable var="v" value="" rendered="{!!records.canInput}" ><apex:outputText id="ProductIdOut" value="{!records.deatilNo}"/> </apex:variable>
+                            <apex:variable var="v" id="ProductCountIn" value="" rendered="{!records.canInput}" ><apex:inputText id="ProductCount" value="{!records.deatilNo}" onblur="ComputePriceJs(this)" style="width: 50Px;text-align: right;"/>
+                            </apex:variable>
+                            </td>
+                            <apex:outputPanel layout="none" rendered="{!IF(loanerApply.Equipment_Type__c == 'BS' , true , false)}">
+                            <td class="dataCell" align="center">
+                                 {!records.aset.Description}
+                            </td>
+                            </apex:outputPanel>
+
+                            <td class="dataCell" align="center">
+                            <apex:inputText id="ProductCount" value="{!records.remark}" style="text-align: right;"/>
+                            </td>
+                            <!--<td class="dataCell" align="center">
+                                <apex:outputText value="{0, date, yyyy/MM/dd}" id="Rental_Start_Date">
+                                    <apex:param value="{!records.Rental_Start_Date}" />
+                                </apex:outputText>
+                            </td>
+                            <td class="dataCell" align="center">
+                                <apex:outputText value="{0, date, yyyy/MM/dd}" id="Rental_End_Date">
+                                    <apex:param value="{!records.Rental_End_Date}" />
+                                </apex:outputText>
+                            </td>
+                            <td class="dataCell" align="center">
+                                <apex:outputText id="SEdayCount" value="{!records.SEdayCount}"/>
+                            </td>-->
+                        </tr>
+                        </apex:repeat>
+                    </table>
+                </apex:pageBlock>
+                </div>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/EquipmentLoanerApply.page-meta.xml b/scr/pages/EquipmentLoanerApply.page-meta.xml
new file mode 100644
index 0000000..333d8b2
--- /dev/null
+++ b/scr/pages/EquipmentLoanerApply.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>EquipmentLoanerApply</label>
+</ApexPage>
diff --git a/scr/pages/Exception.page b/scr/pages/Exception.page
new file mode 100644
index 0000000..61dda59
--- /dev/null
+++ b/scr/pages/Exception.page
@@ -0,0 +1,37 @@
+<apex:page showHeader="false" title="{!$Label.site.error2}" cache="false">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1" style="align: center;">
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer">
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="3">
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/warning.png')}"/>
+                <apex:panelGroup >
+                  <apex:outputText styleClass="title" value="{!$Label.site.error}">
+                   <apex:param value="{!$Site.ErrorMessage}"/>
+                   <!-- this parameter needs to be italic in the site.error label -->
+                  </apex:outputText>
+                  <br/>
+                  <br/>
+                  <apex:outputText escape="false" value=" {!$Label.site.get_in_touch}">
+                   <apex:param value="mailto:{!$Site.AdminEmailAddress}"/>
+                   <apex:param value="{!$Label.site.email_us}"/>
+                  </apex:outputText>
+                </apex:panelGroup>
+              </apex:panelGrid>
+             </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid>
+          <br/>
+          <apex:messages />
+          <br/>
+        </apex:panelGrid>
+      </center>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/Exception.page-meta.xml b/scr/pages/Exception.page-meta.xml
new file mode 100644
index 0000000..d78a2a5
--- /dev/null
+++ b/scr/pages/Exception.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>楠岃瘉鍚庨敊璇殑榛樿 Force.com 椤甸潰</description>
+    <label>Exception</label>
+</ApexPage>
diff --git a/scr/pages/FileNotFound.page b/scr/pages/FileNotFound.page
new file mode 100644
index 0000000..4d5ba9b
--- /dev/null
+++ b/scr/pages/FileNotFound.page
@@ -0,0 +1,35 @@
+<apex:page showHeader="false" title="{!$Label.site.file_not_found}" cache="false">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1">
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer">
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="3">
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/warning.png')}"/>
+                <apex:panelGroup >
+                  <apex:outputText styleClass="title" value="{!$Label.site.page_not_found_detail}">
+                   <apex:param value="{!$Site.OriginalUrl}"/>
+                  </apex:outputText>
+                  <br/>
+                  <br/>
+                  <apex:outputText value="{!$Label.site.stay_tuned}"/>
+                  <apex:outputText escape="false" value=" {!$Label.site.get_in_touch}">
+                   <apex:param value="mailto:{!$Site.AdminEmailAddress}"/>
+                   <apex:param value="{!$Label.site.email_us}"/>
+                  </apex:outputText>
+                </apex:panelGroup>
+              </apex:panelGrid>
+             </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid>
+        </apex:panelGrid>
+      </center>
+    </apex:define>
+  </apex:composition>
+  <site:previewAsAdmin />
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/FileNotFound.page-meta.xml b/scr/pages/FileNotFound.page-meta.xml
new file mode 100644
index 0000000..e491112
--- /dev/null
+++ b/scr/pages/FileNotFound.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 椤甸潰/鏁版嵁鏈壘鍒伴〉闈�</description>
+    <label>FileNotFound</label>
+</ApexPage>
diff --git a/scr/pages/ForgotPassword.page b/scr/pages/ForgotPassword.page
new file mode 100644
index 0000000..9877886
--- /dev/null
+++ b/scr/pages/ForgotPassword.page
@@ -0,0 +1,36 @@
+<apex:page id="forgotPassword" showHeader="false" controller="ForgotPasswordController" title="{!$Label.site.forgot_password}">
+ <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.enter_password}"/>
+                  <br/>
+                  <apex:form id="theForm">
+                    <apex:pageMessages id="error"/>
+                    <apex:panelGrid columns="3" style="margin-top:1em;">
+                      <apex:outputLabel value="{!$Label.site.username}" for="username"/>
+                      <apex:inputText required="true" id="username" value="{!username}"/>
+                      <apex:commandButton id="submit" value="{!$Label.site.submit}" action="{!forgotPassword}"/>
+                    </apex:panelGrid> 
+                    </apex:form>                  
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+             </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ForgotPassword.page-meta.xml b/scr/pages/ForgotPassword.page-meta.xml
new file mode 100644
index 0000000..7b465a6
--- /dev/null
+++ b/scr/pages/ForgotPassword.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 蹇樿瀵嗙爜纭椤甸潰</description>
+    <label>ForgotPassword</label>
+</ApexPage>
diff --git a/scr/pages/ForgotPasswordConfirm.page b/scr/pages/ForgotPasswordConfirm.page
new file mode 100644
index 0000000..77f2654
--- /dev/null
+++ b/scr/pages/ForgotPasswordConfirm.page
@@ -0,0 +1,30 @@
+<apex:page showHeader="false" title="{!$Label.site.forgot_password_confirmation}">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">  
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.temp_password_sent}"/>
+                  <br/>
+                  <br/>
+                  <apex:outputLink value="{!$Page.SiteLogin}" rendered="{!$Site.LoginEnabled}">{!$Label.site.go_to_login_page}</apex:outputLink>
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+             </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ForgotPasswordConfirm.page-meta.xml b/scr/pages/ForgotPasswordConfirm.page-meta.xml
new file mode 100644
index 0000000..bb434e4
--- /dev/null
+++ b/scr/pages/ForgotPasswordConfirm.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 蹇樿瀵嗙爜纭椤甸潰</description>
+    <label>ForgotPasswordConfirm</label>
+</ApexPage>
diff --git a/scr/pages/IENewOpportunity.page b/scr/pages/IENewOpportunity.page
new file mode 100644
index 0000000..0763c37
--- /dev/null
+++ b/scr/pages/IENewOpportunity.page
@@ -0,0 +1,211 @@
+<apex:page id="Page" Controller="IENewOpportunityController" sidebar="true" showHeader="true" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+    function saveJs() {
+        blockme();
+        saveBtn();
+    }
+
+    function saveYesJs() {
+        blockme();
+        saveBtnYes();
+    }
+
+    function saveNoJs() {
+        blockme();
+        saveBtnNo();
+    }
+
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+        var rtUrl = '{!rtUrl}';
+        if (rtUrl == 'null' || rtUrl == '') {
+            rtUrl = '{!conId}';
+        }
+        window.location.href = baseUrl + "/" + rtUrl;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnYes}" name="saveBtnYes" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnNo}" name="saveBtnNo" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+
+        <input type="hidden" id="hasError" value="{!hasError}"/>
+
+        <apex:pageBlock id="idSearchSetProduct" title="鏂板缓璇环" tabStyle="Opportunity">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="saveYesJs();" value="鏄�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+                <apex:commandButton style="width:50px" onclick="saveNoJs();" value="鍚�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+            </apex:pageBlockButtons>
+
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦" for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.BudgetAmount__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢" for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦" for="opp_Amount"/>
+                    <apex:inputField value="{!opp.Amount}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="COMPO璇环" for="compo_opp"/>
+                    <apex:inputField value="{!opp.compo_opp__c}" id="compo_opp"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡" for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.ExpectedOrderDate__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡" for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.ExpectedDeliveryDate__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮" for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.CustomerSourceIE__c}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤" for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.TradeType__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�" for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.SalesChannel__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1" for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1" for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2" for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2" for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode2__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3" for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3" for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode3__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4" for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4" for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode4__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5" for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5" for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode5__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6" for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6" for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode6__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7" for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7" for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode7__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8" for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8" for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode8__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳?" for="Have_Computer"/>
+                    <apex:inputField value="{!opp.Have_Computer__c}" id="Have_Computer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏宠仈璇环" for="Association_Opportunity"/>
+                    <apex:inputField value="{!opp.Association_Opportunity__c}" id="Association_Opportunity"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+        </apex:pageBlock>
+    </apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/IENewOpportunity.page-meta.xml b/scr/pages/IENewOpportunity.page-meta.xml
new file mode 100644
index 0000000..36db6c8
--- /dev/null
+++ b/scr/pages/IENewOpportunity.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>IENewOpportunity</label>
+</ApexPage>
diff --git a/scr/pages/IdeasHome.page b/scr/pages/IdeasHome.page
new file mode 100644
index 0000000..165405b
--- /dev/null
+++ b/scr/pages/IdeasHome.page
@@ -0,0 +1 @@
+<apex:page action="{!URLFOR('/ideas/ideaList.apexp')}"/>
\ No newline at end of file
diff --git a/scr/pages/IdeasHome.page-meta.xml b/scr/pages/IdeasHome.page-meta.xml
new file mode 100644
index 0000000..c0a54a9
--- /dev/null
+++ b/scr/pages/IdeasHome.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>鎰忚绔欑偣鐨勯粯璁� Force.com 涓婚〉</description>
+    <label>IdeasHome</label>
+</ApexPage>
diff --git a/scr/pages/InMaintenance.page b/scr/pages/InMaintenance.page
new file mode 100644
index 0000000..ebea2ec
--- /dev/null
+++ b/scr/pages/InMaintenance.page
@@ -0,0 +1,19 @@
+<apex:page showHeader="false" title="{!$Label.site.in_maintenance}" cache="false">
+  <apex:composition template="StdExceptionTemplate">
+    <apex:define name="icon">
+      <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/warning.png')}"/>
+    </apex:define>
+    <apex:define name="error">
+      <apex:outputText escape="false" styleClass="title" value="{!$Label.site.down_for_maintenance}">
+        <apex:param value="{!$Site.BaseUrl}"/>
+      </apex:outputText>
+      <br/>
+      <br/>
+      <apex:outputText value="{!$Label.site.sorry_for_inconvenience_back_shortly}"/>
+      <apex:outputText escape="false" value=" {!$Label.site.get_in_touch}">
+      <apex:param value="mailto:{!$Site.AdminEmailAddress}"/>
+      <apex:param value="{!$Label.site.email_us}"/>
+    </apex:outputText>
+   </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/InMaintenance.page-meta.xml b/scr/pages/InMaintenance.page-meta.xml
new file mode 100644
index 0000000..80e31c6
--- /dev/null
+++ b/scr/pages/InMaintenance.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 缁存姢涓〉闈�</description>
+    <label>InMaintenance</label>
+</ApexPage>
diff --git a/scr/pages/LoanerApplicationPortionDeliver.page b/scr/pages/LoanerApplicationPortionDeliver.page
new file mode 100644
index 0000000..27be77c
--- /dev/null
+++ b/scr/pages/LoanerApplicationPortionDeliver.page
@@ -0,0 +1,119 @@
+<apex:page controller="LoanerPortionDeliverController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="閮ㄥ垎鍙戣揣">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<style type="text/css"> td>div{display: inline-block;}</style>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+               
+                <table border="0" style="width: 800px;">
+                    <tr>
+                        <td>
+                        <label for="company">{!$ObjectType.loaner_application_detail__c.fields.delivery_company__c.label}: </label><apex:inputField value="{!lac.delivery_company__c}" id="company"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>
+                         <label for="number">{!$ObjectType.loaner_application_detail__c.fields.Tracking_Number__c.label}: </label><apex:inputField value="{!lac.Tracking_Number__c}" id="number"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>
+                             <label for="user" >{!$ObjectType.loaner_application_detail__c.fields.Return_to_wh_staff__c.label}: </label>
+                            <apex:inputField value="{!lac.Return_to_wh_staff__c}" id="user"></apex:inputField>
+                        </td>
+                        <td>
+                            <apex:commandButton onclick="saveJs();" value="鍙戣揣" rerender="dummy" style="width: 70px;float: right;"/>  
+                            <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;float: right;"/>
+                        </td>
+                    </tr>
+                </table>
+                <br/>
+                <br/>
+                <table border="0" style="border-collapse: collapse;width:800px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Remarks2__c}"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerApplicationPortionDeliver.page-meta.xml b/scr/pages/LoanerApplicationPortionDeliver.page-meta.xml
new file mode 100644
index 0000000..69f5512
--- /dev/null
+++ b/scr/pages/LoanerApplicationPortionDeliver.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerApplicationPortionDeliver</label>
+</ApexPage>
diff --git a/scr/pages/LoanerApplicationStockDown.page b/scr/pages/LoanerApplicationStockDown.page
new file mode 100644
index 0000000..9448835
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockDown.page
@@ -0,0 +1,87 @@
+<apex:page controller="LoanerApplicationFlowController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="涓嬫灦">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="saveJs();" value="涓嬫灦" rerender="dummy" style="width: 70px;"/>
+                </apex:pageBlockButtons>
+                <table border="0" style="border-collapse: collapse;width:650px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerApplicationStockDown.page-meta.xml b/scr/pages/LoanerApplicationStockDown.page-meta.xml
new file mode 100644
index 0000000..0573327
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockDown.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerApplicationStockDown</label>
+</ApexPage>
diff --git a/scr/pages/LoanerApplicationStockDownCheck.page b/scr/pages/LoanerApplicationStockDownCheck.page
new file mode 100644
index 0000000..60098cf
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockDownCheck.page
@@ -0,0 +1,130 @@
+<apex:page controller="LoanerStockDownCheckController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="涓嬫灦妫�鏌�">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+
+}
+
+function fillAll(){
+    var count = {!datalineSize};
+    var value = j$(escapeVfId('allPage:allForm:allBlock:lines:0:downStotus'));
+    var valueNone = document.getElementById('allPage:allForm:allBlock:lines:0:downStotus');
+    for (var i = 1; i < count; i++) {
+        var select =document.getElementById('allPage:allForm:allBlock:lines:'+i+':downStotus');
+        var len = select.options.length;
+        for (var j = 0; j < len; j++) {
+            if(select.options[j].value == valueNone.value){
+                select.options[j].selected = true;
+            }
+        }
+    }
+}
+        
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+
+                    <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="saveJs();" value="纭" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="fillAll();" value="閫傜敤" reRender="dummy" style="width: 70px;"/>
+                    
+                </apex:pageBlockButtons>
+                
+                <table border="0" style="border-collapse: collapse;width:1000px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th> 
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.Inspection_result__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.StockDownRemark__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>  
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                        	<apex:inputField value="{!line.lad.Inspection_result__c }" id="downStotus"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputField value="{!line.lad.StockDownRemark__c }"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputField value="{!line.lad.LOANER__r.Remarks2__c }"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerApplicationStockDownCheck.page-meta.xml b/scr/pages/LoanerApplicationStockDownCheck.page-meta.xml
new file mode 100644
index 0000000..b4e8915
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockDownCheck.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerApplicationStockDownCheck</label>
+</ApexPage>
diff --git a/scr/pages/LoanerApplicationStockUp.page b/scr/pages/LoanerApplicationStockUp.page
new file mode 100644
index 0000000..247416e
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockUp.page
@@ -0,0 +1,94 @@
+<apex:page controller="LoanerApplicationStockUpController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="涓婃灦">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="saveJs();" value="涓婃灦" rerender="dummy" style="width: 70px;"/>
+                   
+                </apex:pageBlockButtons>
+                <table border="0" style="border-collapse: collapse;width:650px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.RAESD_Status__c.label}</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.RAESD_Status__c}" />
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerApplicationStockUp.page-meta.xml b/scr/pages/LoanerApplicationStockUp.page-meta.xml
new file mode 100644
index 0000000..6dd9ac9
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockUp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerApplicationStockUp</label>
+</ApexPage>
diff --git a/scr/pages/LoanerApplicationStockUpCheck.page b/scr/pages/LoanerApplicationStockUpCheck.page
new file mode 100644
index 0000000..9a9cb0a
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockUpCheck.page
@@ -0,0 +1,134 @@
+<apex:page controller="LoanerApplicationStockUpCheckController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="涓婃灦妫�鏌�">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+
+
+function fillAll(){
+    var count = {!datalineSize};
+    var value = j$(escapeVfId('allPage:allForm:allBlock:lines:0:upStotus'));
+    var valueNone = document.getElementById('allPage:allForm:allBlock:lines:0:upStotus');
+    for (var i = 1; i < count; i++) {
+        var select =document.getElementById('allPage:allForm:allBlock:lines:'+i+':upStotus');
+        var len = select.options.length;
+        for (var j = 0; j < len; j++) {
+            if(select.options[j].value == valueNone.value){
+                select.options[j].selected = true;
+            }
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+
+                    <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="saveJs();" value="纭" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="fillAll();" value="閫傜敤" reRender="dummy" style="width: 70px;"/> 
+                </apex:pageBlockButtons>
+                
+                <table border="0" style="border-collapse: collapse;width:1150px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="125"/>
+                        <col width="125"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.RAESD_Status__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.Inspection_result_after__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.StockUpRemark__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                        	<apex:outputField value="{!line.lad.RAESD_Status__c }"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                        	<apex:inputField value="{!line.lad.Inspection_result_after__c }" id="upStotus"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputField value="{!line.lad.StockUpRemark__c }"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Remarks2__c}"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerApplicationStockUpCheck.page-meta.xml b/scr/pages/LoanerApplicationStockUpCheck.page-meta.xml
new file mode 100644
index 0000000..44caa42
--- /dev/null
+++ b/scr/pages/LoanerApplicationStockUpCheck.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerApplicationStockUpCheck</label>
+</ApexPage>
diff --git a/scr/pages/LoanerLendDeliver.page b/scr/pages/LoanerLendDeliver.page
new file mode 100644
index 0000000..d893af4
--- /dev/null
+++ b/scr/pages/LoanerLendDeliver.page
@@ -0,0 +1,134 @@
+<apex:page controller="LoanerLendDeliverController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="杞�熷彂璐�">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<style type="text/css"> td>div{display: inline-block;}</style>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+               
+                <table border="0" style="width: 800px;">
+                    <tr>
+                        <td>
+                        <label for="company">杞�熷彂璐х墿娴佸叕鍙�: </label><apex:inputField value="{!lac.Return_Track_Company__c}" id="company"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>
+                         <label for="number">杞�熷彂璐х墿娴佸崟鍙�: </label><apex:inputField value="{!lac.Return_Track_Number__c}" id="number"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>
+                             <label for="user" >杞�熷彂璐х墿浜�: </label>
+                            <apex:inputField value="{!lac.Return_Trake_Staff__c}" id="user"></apex:inputField>
+                        </td>
+                        <td>
+                            <apex:commandButton onclick="saveJs();" value="鍙戣揣" rerender="dummy" style="width: 70px;float: right;"/>  
+                            <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;float: right;"/>
+                        </td>
+                    </tr>
+                </table>
+                <br/>
+                <br/>
+                <table border="0" style="border-collapse: collapse; width:1000px; table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="100"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">杞�熷崟鍙�</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">杞�熶唬鐞嗗晢</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏄惁涓婁紶鍊熺敤鍗忚</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.num}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.ltc}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!IF(line.PDFflag == true,'宸蹭笂浼�','鏈笂浼�')}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Remarks2__c}"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerLendDeliver.page-meta.xml b/scr/pages/LoanerLendDeliver.page-meta.xml
new file mode 100644
index 0000000..c881318
--- /dev/null
+++ b/scr/pages/LoanerLendDeliver.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerLendDeliver</label>
+</ApexPage>
diff --git a/scr/pages/LoanerPortionReturn.page b/scr/pages/LoanerPortionReturn.page
new file mode 100644
index 0000000..38b205b
--- /dev/null
+++ b/scr/pages/LoanerPortionReturn.page
@@ -0,0 +1,169 @@
+<apex:page controller="LoanerPortionReturnController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="閮ㄥ垎鍥炲瘎">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<style type="text/css"> td>div{display: inline-block;}</style>
+<script>
+function test1(){
+      getIsOk();
+}
+function saveJs() {
+  
+
+    var okDate = j$(escapeVfId('isOk')).value();
+    var loanerType = '{!loanerType}';
+   
+     if(loanerType == 'BS' && okDate == 'true'){
+        alert('鏈鏈虹‘璁わ紝涓嶈兘鍥炲瘎鏍锋満銆�');
+        return;
+    }
+   
+    if(loanerType != 'BS' && okDate == 'true'){ 
+        if(confirm('鏈鏈虹‘璁�,鏄惁鍥炲瘎?') == false){
+            return;
+         }
+    }
+    
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();"> </apex:actionFunction>
+       <apex:actionFunction name="getIsOk" action="{!getIsOk}"  rerender="allForm,message,allPanel" onComplete="unblockUI();saveJs();"></apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+ 
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+             <input type="hidden" id='isOk' value="{!isOk}"/>
+            <apex:pageBlock id="allBlock">
+               
+                <table border="0" style="width: 800px;">
+                    <tr>
+                        <td colspan="3">
+                            <label for="company">{!$ObjectType.loaner_application_detail__c.fields.Return_Track_Company__c.label}: </label><apex:inputField value="{!lac.Return_Track_Company__c}" id="company"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>    
+                             <label for="number">{!$ObjectType.loaner_application_detail__c.fields.Return_Track_Number__c.label}: </label><apex:inputField value="{!lac.Return_Track_Number__c}" id="number"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>
+                             <label for="user">{!$ObjectType.loaner_application_detail__c.fields.Return_Trake_Staff__c.label}: </label>
+                            <apex:inputField value="{!lac.Return_Trake_Staff__c}" id="user"></apex:inputField>
+                        </td>
+                        <td>
+                             <apex:commandButton onclick="test1();" value="鍥炲瘎" rerender="dummy" style="width: 70px;float: right;"/>  
+                             <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;float: right;"/>
+                            
+                        </td>
+                    </tr>
+                    <apex:outputPanel layout="none" rendered="{!IF(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI', true , false)}">
+                    <tr>
+                        <td>    
+                             <label for="return_Number__c">{!$ObjectType.loaner_application_detail__c.fields.return_Number__c.label}: </label><apex:inputField value="{!lac.return_Number__c}" id="return_Number__c"></apex:inputField>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>    
+                             <label for="place">{!$ObjectType.loaner_application_detail__c.fields.loaner_manage_place__c.label}: </label><apex:inputField value="{!lac.loaner_manage_place__c}" id="place"></apex:inputField>
+                        </td>
+                    </tr>
+                     </apex:outputPanel>
+                </table>
+                <br/>
+                <br/>
+                <table border="0" style="border-collapse: collapse;width:900px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="170"/>
+                        <col width="170"/>
+                        <col width="150"/>
+                        <apex:outputPanel layout="none" rendered="{!IF(loanerType == 'BS', true , false)}">
+                            <col width="150" />
+                        </apex:outputPanel>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.RAESD_Status__c.label}</th>
+                        <apex:outputPanel layout="none" rendered="{!IF(loanerType == 'BS', true , false)}">
+                            <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鎻忚堪</th>
+                        </apex:outputPanel>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                        	<apex:outputField value="{!line.lad.RAESD_Status__c}"/>
+                        </td>
+                         <apex:outputPanel layout="none" rendered="{!IF(loanerType == 'BS', true , false)}">
+                            <td class="dataCell" style="text-align: center;">
+                                <apex:outputField value="{!line.lad.LOANER__r.Description}"/>
+                            </td>
+                        </apex:outputPanel>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Remarks2__c}"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerPortionReturn.page-meta.xml b/scr/pages/LoanerPortionReturn.page-meta.xml
new file mode 100644
index 0000000..6d307b1
--- /dev/null
+++ b/scr/pages/LoanerPortionReturn.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerPortionReturn</label>
+</ApexPage>
diff --git a/scr/pages/LoanerReceiveGoods.page b/scr/pages/LoanerReceiveGoods.page
new file mode 100644
index 0000000..c71fe01
--- /dev/null
+++ b/scr/pages/LoanerReceiveGoods.page
@@ -0,0 +1,128 @@
+<apex:page controller="LoanerReceiveGoodsController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="鏀惰揣">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+
+function fillAll(){
+    var count = {!DatalineSize};
+    var value = j$(escapeVfId('allPage:allForm:allBlock:lines:0:receiveStatus'));
+    var valueNone = document.getElementById('allPage:allForm:allBlock:lines:0:receiveStatus');
+    for (var i = 1; i < count; i++) {
+        var select =document.getElementById('allPage:allForm:allBlock:lines:'+i+':receiveStatus');
+        var len = select.options.length;
+        for (var j = 0; j < len; j++) {
+            if(select.options[j].value == valueNone.value){
+                select.options[j].selected = true;
+            }
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+
+                    <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="saveJs();" value="纭" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="fillAll();" value="閫傜敤" reRender="dummy" style="width: 70px;"/>
+                
+                </apex:pageBlockButtons>
+                
+                <table border="0" style=" border-collapse: collapse; width:1000px; table-layout:fixed; ">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                        <col width="150"/>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.Receipt_Status__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.ReceiptRemark__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                        	<apex:inputField value="{!line.lad.Receipt_Status__c }" id="receiveStatus"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputField value="{!line.lad.ReceiptRemark__c }"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Remarks2__c}"/>
+                        </td>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerReceiveGoods.page-meta.xml b/scr/pages/LoanerReceiveGoods.page-meta.xml
new file mode 100644
index 0000000..417be5e
--- /dev/null
+++ b/scr/pages/LoanerReceiveGoods.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerReceiveGoods</label>
+</ApexPage>
diff --git a/scr/pages/LoanerTakeBack.page b/scr/pages/LoanerTakeBack.page
new file mode 100644
index 0000000..5d46b9b
--- /dev/null
+++ b/scr/pages/LoanerTakeBack.page
@@ -0,0 +1,136 @@
+<apex:page controller="LoanerTakeBackController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="鍥炴敹">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function saveJs() {
+    if(confirm('鏄惁淇濆瓨淇敼?')==true){
+        blockme();
+        saveBtn();
+
+    }
+}
+function checkAll() {
+    var productCount = j$(escapeVfId('linesize')).value();
+    if (j$(escapeVfId('checkall')).attr('checked') == 'checked') {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',true);
+        }
+    } else {
+        for (var i = 0; i < productCount; i++) {
+            j$(escapeVfId('allPage:allForm:allBlock:lines:' + i + ':check')).attr('checked',false);
+        }
+    }
+}
+function fillAll(){
+    var count = {!datalineSize};
+    var value = j$(escapeVfId('allPage:allForm:allBlock:lines:0:backStotus'));
+    var valueNone = document.getElementById('allPage:allForm:allBlock:lines:0:backStotus');
+    for (var i = 1; i < count; i++) {
+        var select =document.getElementById('allPage:allForm:allBlock:lines:'+i+':backStotus');
+        var len = select.options.length;
+        for (var j = 0; j < len; j++) {
+            if(select.options[j].value == valueNone.value){
+                select.options[j].selected = true;
+            }
+        }
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allForm,message,allPanel" onComplete="unblockUI();">
+        </apex:actionFunction>
+
+        <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+
+                    <apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="saveJs();" value="纭" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton onclick="fillAll();" value="閫傜敤" reRender="dummy" style="width: 70px;"/>
+                
+                </apex:pageBlockButtons>
+                
+                <table border="0" style="border-collapse: collapse;width:900px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="25"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="125"/>
+                        <col width="125"/>
+                        <col width="125"/>
+                        <col width="125"/>
+                        <col width="125"/>
+                        <apex:outputPanel layout="none" rendered="{!IF(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI', true , false)}">
+                            <col width="125"/>
+                        </apex:outputPanel>
+                    </colgroup>
+                    <tr>
+                        <th style="text-align: center; border-bottom-style: ridge;"><input type="checkbox" id="checkall" onclick="checkAll();" /></th>
+                        <th style="text-align: center; border-bottom-style: ridge;">No.</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満鍚嶇О</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.SerialNumber__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.Internal_Asset_number__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.OTCODE__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">{!$ObjectType.loaner_application_detail__c.fields.ECCode__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">
+                        {!$ObjectType.loaner_application_detail__c.fields.Check_lost_Item__c.label}</th>
+                        <th style="text-align: center; border-bottom-style: ridge;">鏍锋満澶囨敞</th>
+                         <apex:outputPanel layout="none" rendered="{!IF(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI', true , false)}">
+                            <th style="text-align: center; border-bottom-style: ridge;">    
+                                鏍锋満鍥炲瘎鍦板潃
+                            </th>
+                        </apex:outputPanel>
+                    </tr>
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:inputCheckbox id="check" value="{!line.checkFlag}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lineNo}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Name}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.SerialNumber__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.Internal_Asset_number__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.OTCODE__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.ECCode__c}"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                        	<apex:inputField value="{!line.lad.Check_lost_Item__c }" id="backStotus"/>
+                        </td>
+                        <td class="dataCell" style="text-align: center;">
+                            <apex:outputText value="{!line.lad.LOANER__r.Remarks2__c}"/>
+                        </td>
+                        <apex:outputPanel layout="none" rendered="{!IF(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI', true , false)}">
+                            <td style="text-align: center; border-bottom-style: ridge;">    
+                                <apex:outputText value="{!line.lad.loaner_manage_place__c }"/>
+                            </td>
+                        </apex:outputPanel>
+
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/LoanerTakeBack.page-meta.xml b/scr/pages/LoanerTakeBack.page-meta.xml
new file mode 100644
index 0000000..28bb5f4
--- /dev/null
+++ b/scr/pages/LoanerTakeBack.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>LoanerTakeBack</label>
+</ApexPage>
diff --git a/scr/pages/MessageBoard.page b/scr/pages/MessageBoard.page
new file mode 100644
index 0000000..1e53559
--- /dev/null
+++ b/scr/pages/MessageBoard.page
@@ -0,0 +1,40 @@
+<apex:page standardController="User_FaultInfo__c" extensions="MessageBoardController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    
+    if ('{!usertype}' == 'PowerPartner'){
+    window.open('/production/apex/MessageBoardPoPup?caseId=' + '{!URLENCODE(User_FaultInfo__c.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    } else{
+    window.open('/apex/MessageBoardPoPup?caseId=' + '{!URLENCODE(User_FaultInfo__c.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    }
+}
+
+function reloadjs() {
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="璁板綍" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!userfaultInfo.MessageBoard__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/MessageBoard.page-meta.xml b/scr/pages/MessageBoard.page-meta.xml
new file mode 100644
index 0000000..7c17b29
--- /dev/null
+++ b/scr/pages/MessageBoard.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>MessageBoard</label>
+</ApexPage>
diff --git a/scr/pages/MessageBoardPoPuP.page b/scr/pages/MessageBoardPoPuP.page
new file mode 100644
index 0000000..32d2f86
--- /dev/null
+++ b/scr/pages/MessageBoardPoPuP.page
@@ -0,0 +1,51 @@
+<apex:page Controller="MessageBoardController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.User_FaultInfo__c.fields.MessageBoard__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="Save" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="Cancel" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="caseId" value="{!caseId}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!userfaultInfoPoPuP.MessageBoard__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/MessageBoardPoPuP.page-meta.xml b/scr/pages/MessageBoardPoPuP.page-meta.xml
new file mode 100644
index 0000000..dace40c
--- /dev/null
+++ b/scr/pages/MessageBoardPoPuP.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>MessageBoardPoPuP</label>
+</ApexPage>
diff --git a/scr/pages/MicrobatchSelfReg.page b/scr/pages/MicrobatchSelfReg.page
new file mode 100644
index 0000000..96b3069
--- /dev/null
+++ b/scr/pages/MicrobatchSelfReg.page
@@ -0,0 +1,24 @@
+<apex:page id="microbatchSelfRegPage" showHeader="true" controller="MicrobatchSelfRegController" title="{!$Label.site.user_registration}">
+     <apex:define name="body">
+      <center>
+<apex:form id="theForm" forceSSL="true">
+                    <apex:pageMessages id="error"/>
+                    <apex:panelGrid columns="2" style="margin-top:1em;">
+                      <apex:outputLabel value="First Name" for="firstName"/>
+                      <apex:inputText required="true" id="firstName" value="{!firstName}" label="First Name"/>
+                      <apex:outputLabel value="Last Name" for="lastName"/>
+                      <apex:inputText required="true" id="lastName" value="{!lastName}" label="Last Name"/>
+                      <apex:outputLabel value="{!$Label.site.community_nickname}" for="communityNickname"/>
+                      <apex:inputText required="true" id="communityNickname" value="{!communityNickname}" label="{!$Label.site.community_nickname}"/>
+                      <apex:outputLabel value="{!$Label.site.email}" for="email"/>
+                      <apex:inputText required="true" id="email" value="{!email}" label="{!$Label.site.email}"/>
+                      <apex:outputText value=""/>
+                      <apex:commandButton action="{!registerUser}" value="{!$Label.site.submit}" id="submit"/>
+                    </apex:panelGrid>
+                  <br/>
+</apex:form>
+     </center>
+      <br/>
+    </apex:define>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/MicrobatchSelfReg.page-meta.xml b/scr/pages/MicrobatchSelfReg.page-meta.xml
new file mode 100644
index 0000000..7085375
--- /dev/null
+++ b/scr/pages/MicrobatchSelfReg.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>54.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>Process self-registration requests in batches instead of individually</description>
+    <label>MicrobatchSelfReg</label>
+</ApexPage>
diff --git a/scr/pages/MyProfilePage.page b/scr/pages/MyProfilePage.page
new file mode 100644
index 0000000..bf72930
--- /dev/null
+++ b/scr/pages/MyProfilePage.page
@@ -0,0 +1,72 @@
+<apex:page id="portalUserProfilePage" controller="MyProfilePageController" showHeader="false" title="{!$Label.site.my_profile_page}">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">
+        <apex:form id="theForm">
+          <apex:outputPanel style="padding:50px 50px 50px 50px" id="userDetail">
+           <apex:pageBlock title="{!$Label.site.my_profile}" id="editUserDetail" rendered="{!isEdit}">
+             <apex:pageMessages />
+             <apex:pageBlockButtons id="editButtons" location="top">
+               <apex:commandButton id="save" value="{!$Label.site.save}" action="{!save}" rerender="userDetail"/>
+               <apex:commandButton id="cancel" value="{!$Label.site.cancel}" action="{!cancel}" rerender="userDetail" immediate="true"/>
+             </apex:pageBlockButtons>
+             <apex:pageBlockSection id="editUserSection" columns="1" title="{!$Label.site.user_information}">
+                 <apex:inputField id="editusername" value="{!user.username}"/>
+                 <apex:inputField id="edittimezone" value="{!user.timezonesidkey}"/> 
+                 <apex:inputField id="editlocale" value="{!user.localesidkey}"/> 
+                 <apex:inputField id="editlanguage" value="{!user.languagelocalekey}"/> 
+                 <apex:inputField id="editcommunityNickname" value="{!user.communityNickname}"/> 
+             </apex:pageBlockSection>
+             <apex:pageBlockSection id="editContactSection" columns="2" title="{!$Label.site.contact_information}">
+                 <apex:inputField id="editfirstName" value="{!user.firstName}"/> 
+                 <apex:inputField id="editemail" value="{!user.email}"/> 
+                 <apex:inputField id="editlastName" value="{!user.lastName}"/> 
+                 <apex:inputField id="editphone" value="{!user.phone}"/> 
+                 <apex:inputField id="edittitle" value="{!user.title}"/> 
+                 <apex:inputField id="editextension" value="{!user.extension}"/> 
+                 <apex:pageBlockSectionItem />
+                 <apex:inputField id="editfax" value="{!user.fax}"/>
+                 <apex:pageBlockSectionItem />
+                 <apex:inputField id="editmobile" value="{!user.mobilephone}"/> 
+               </apex:pageBlockSection>
+               <apex:pageBlockSection id="editAddressInformation" columns="1" title="{!$Label.site.address_information}">
+                 <apex:inputField id="editstreet" value="{!user.street}"/> 
+                 <apex:inputField id="editcity" value="{!user.city}"/> 
+                 <apex:inputField id="editstate" value="{!user.state}"/> 
+                 <apex:inputField id="editpostalcode" value="{!user.postalcode}"/> 
+                 <apex:inputField id="editcountry" value="{!user.country}"/> 
+               </apex:pageBlockSection>
+           </apex:pageBlock>         
+        
+            <apex:pageBlock title="{!$Label.site.my_profile}" id="viewUserDetail" rendered="{!!isEdit}">
+                 <apex:pageBlockButtons id="detailButtons" location="top">
+                   <apex:commandButton id="edit" value="{!$Label.site.edit}" action="{!edit}" rerender="userDetail"/>
+                   <apex:commandButton id="changePassword" value="{!$Label.site.change_password}" action="{!changePassword}"/>
+                 </apex:pageBlockButtons>
+                 <apex:pageBlockSection id="viewUserSection" columns="2" title="{!$Label.site.user_information}">
+                     <apex:outputField id="detailusername" value="{!user.username}"/>
+                     <apex:outputField id="detailtimezone" value="{!user.timezonesidkey}"/> 
+                     <apex:outputField id="detaillocale" value="{!user.localesidkey}"/> 
+                     <apex:outputField id="detaillanguage" value="{!user.languagelocalekey}"/> 
+                     <apex:outputField id="detailcommunityNickname" value="{!user.communityNickname}"/> 
+                 </apex:pageBlockSection>
+                 <apex:pageBlockSection id="viewContactSection" columns="2" title="{!$Label.site.contact_information}">
+                     <apex:outputField id="detailemail" value="{!user.email}"/> 
+                     <apex:outputField id="detailfirstName" value="{!user.firstName}"/> 
+                     <apex:outputField id="detaillastName" value="{!user.lastName}"/> 
+                     <apex:outputField id="detailtitle" value="{!user.title}"/> 
+                     <apex:outputField id="detailphone" value="{!user.phone}"/> 
+                     <apex:outputField id="detailstreet" value="{!user.street}"/> 
+                     <apex:outputField id="detailcity" value="{!user.city}"/> 
+                     <apex:outputField id="detailstate" value="{!user.state}"/> 
+                     <apex:outputField id="detailpostalcode" value="{!user.postalcode}"/> 
+                     <apex:outputField id="detailcountry" value="{!user.country}"/> 
+                     <apex:outputField id="detailextension" value="{!user.extension}"/> 
+                     <apex:outputField id="detailfax" value="{!user.fax}"/> 
+                     <apex:outputField id="detailmobile" value="{!user.mobilephone}"/> 
+                  </apex:pageBlockSection>
+               </apex:pageBlock>
+            </apex:outputPanel>
+         </apex:form>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/MyProfilePage.page-meta.xml b/scr/pages/MyProfilePage.page-meta.xml
new file mode 100644
index 0000000..08d3678
--- /dev/null
+++ b/scr/pages/MyProfilePage.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 鎴戠殑绠�妗i〉</description>
+    <label>MyProfilePage</label>
+</ApexPage>
diff --git a/scr/pages/NEWCreateSWOQuote.page b/scr/pages/NEWCreateSWOQuote.page
new file mode 100644
index 0000000..7835391
--- /dev/null
+++ b/scr/pages/NEWCreateSWOQuote.page
@@ -0,0 +1,890 @@
+<apex:page standardController="Quotes__c" extensions="NEWCreateSWOQuoteController" showChat="false" showHeader="true" sidebar="false" action="{!init}" id="Page">
+
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<apex:includeScript value="{!URLFOR($Resource.NewQuoteEntryJS)}"/>
+<apex:includeScript value="{!URLFOR($Resource.SWOJS)}"/>
+<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+<script type="text/javascript">
+
+</script>
+<style type="text/css"> 
+        .Page{
+            margin-left: 20px;
+            margin-right: 20px;
+        }
+
+        .title{
+            height: 30px;
+            background-color: #DFE6F0;
+            font-size: 15px;
+            color:#607799;
+            font-weight: bold;
+            line-height:30px;
+        }
+        .title1{
+            height: 15px;
+            background-color: #607799;
+            /*background-color: #DFE6F0!important;*/
+            font-size: 15px;
+            color:#FFFFFF;
+            font-weight: bold;
+            line-height:15px;
+
+        }
+        .title2{
+            height: 15px;
+            /*background-color: #607799;*/
+            background-color: #DFE6F0!important;
+            font-size: 15px;
+            color:#FFFFFF;
+            font-weight: bold;
+            line-height:15px;
+
+        }
+        .pbSubheader {
+            background: #BFB19C!important;
+            /*background-color: #FFFFFF!important;*/
+            /*background: #BFB19C;*/
+            /*background-color: #44A3BB!important;
+            background-color: #E6E6FA!important;*/
+            /*background-color: #1797c0!important;*/
+            background-color: #DFE6F0!important;
+            /*color:#607799;*/
+            /*color:#FFFFFF!important;*/
+            /*background-color: #FFFFFF!important;*/
+            /*font-size:12pt;
+            font-family:verdana;*/
+            font-weight:bold;
+
+        }
+        .red {
+            background-color:#B22222;
+            text-align: right;
+        }
+
+        .centerLong {
+            /*line-height:30px;
+            height:30px;*/
+            text-align: center;
+            font-weight: bold;
+        }
+        .center {
+            line-height:30px;
+            height:30px;
+            text-align: center;
+            font-size: 10px;
+            color:#FFFFFF;
+            font-weight: bold;
+        }
+        .centerItem {
+            line-height:20px;
+            height:20px;
+            /*padding: 8px 0 ;*/
+            /*padding: 2px 5px 2px 0px;*/
+
+            /*border: 3px solid green;*/
+            text-align: left;
+        }
+        .textRed{
+            color: #B22222;
+            font-size: 16px;
+            font-weight: 700;
+        }
+    </style>
+<apex:form id="allForm">
+        <input type="hidden" id="Id" value="{!Id}"/>
+        <apex:actionFunction name="Save" action="{!Save}" rerender="allForm,allPanel,message" oncomplete="focusFunction();unblockUI();" ></apex:actionFunction>
+        
+        <apex:pageBlock title="Quotes" id="allBlock">
+            <apex:commandButton onclick="save2btn();return false;" value="Save" oncomplete="unblockUI();" style="width:5%;" rerender="dummy" />
+            <apex:outputPanel id="message">
+
+                <apex:pagemessages />
+            </apex:outputPanel>
+            <apex:pageblocksection columns="1" title="QuotesInfo"   id="Quotes" >
+
+                <apex:outputPanel id="allPanel" >
+                <apex:pageBlock title="" id="unEditable" rendered="true">
+
+                    <table class="formtable" width="100%" border="0">
+                         <colgroup>
+                            
+                            <col width="27%"/>   
+                            <col width="5%"/>
+                            <col width="27%"/>
+                            <col width="5%"/>
+                            <col width="2%"/>
+                            <col width="1%"/>
+                            <col width="10%"/>
+                            <col width="5%"/>
+                            <col width="20%"/>
+                        </colgroup>
+                        <tr>
+                            <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th  colspan="9" class="title">Estimate</th>
+                        <tr>
+                            <td  colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.CURRENCY__c.label}</td>
+                            <td  colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_NAME__c.label}</td>                            
+                        </tr>
+                        <tr>
+
+                            <td colspan="2" align="left" ><apex:inputField id="CURRENCY" value="{!QuotesPage.CURRENCY__c}" style="width: 56%"/></td>
+                            <td colspan="2" align="left" ><apex:outputField value="{!QuotesPage.CONTACT_NAME__c}" style="width: 63%"/></td>
+                            <td colspan="2"/>
+                            <td colspan="2" class="title1">Summary</td>
+                            <td/>
+                            <td/>
+
+                        </tr>
+                        <tr>
+                            <td align="left" >CUSTOMER:JOB</td>
+                            
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_PHONE__c.label}</td>
+                            <td colspan="3"/>
+                            <td class="title2">{!$ObjectType.Quotes__c.fields.SUBTOTAL__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.SUBTOTAL__c}" style="width: 62%"/></td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" ><apex:outputField id="COMPANY" value="{!QuotesPage.COMPANY__c}"/>
+                            <!-- <apex:outputLink value="/{!QuotesPage.COMPANYId__c}" target="LINK_{!QuotesPage.COMPANYId__c}" ><c:PDFWbr targetStr="{!QuotesPage.COMPANYName__c}"/></apex:outputLink> -->
+                            </td>
+                            <td align="left" ><apex:outputField id="CONTACT_PHONE" value="{!QuotesPage.CONTACT_PHONE__c}"/></td>
+                            <td colspan="3"/>
+                            <td class="title2">{!$ObjectType.Quotes__c.fields.DISCOUNT__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.DISCOUNT__c}" style="width: 62%"/></td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.DATE__c.label}<span class="textRed">*</span></td>
+                            <td ></td>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_FAX__c.label}</td>
+                            <td colspan="3"/>
+                            <td class="title2">{!$ObjectType.Quotes__c.fields.TAX__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.TAX__c}" style="width: 62%"/></td>
+                            <td/>
+
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="DATE" value="{!QuotesPage.DATE__c }" />
+                            </td>
+                            <td></td>
+                            <td align="left" ><apex:outputField id="CONTACT_FAX" value="{!QuotesPage.CONTACT_FAX__c}"/></td>
+                            <td colspan="3"/>
+                             <td class="title2">{!$ObjectType.Quotes__c.fields.TOTAL__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.TOTAL__c}" style="width: 62%"/></td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.ESTIMATE__c.label}</td>
+                            <td></td>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_EMAIL__c.label}</td>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="ESTIMATE" value="{!QuotesPage.ESTIMATE__c }" /></td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="CONTACT_EMAIL" value="{!QuotesPage.CONTACT_EMAIL__c}"/></td>
+                        
+                        </tr>
+                        <tr>
+                             <td align="left" >{!$ObjectType.Quotes__c.fields.OPPORTUNITY__c.label}</td>
+                             <td></td>
+                            <td align="left" ><apex:inputField id="GSA_ORDER" value="{!QuotesPage.GSA_ORDER__c}"/>{!$ObjectType.Quotes__c.fields.GSA_ORDER__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="OPPORTUNITY" value="{!QuotesPage.OPPORTUNITY__c }"/></td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="GOVERNMENT_ORDER" value="{!QuotesPage.GOVERNMENT_ORDER__c}"/>{!$ObjectType.Quotes__c.fields.GOVERNMENT_ORDER__c.label}</td>
+                        </tr>
+                        <tr>
+                            
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.SUBSIDIARY__c.label}</td>
+                            <td colspan="3" align="left" ><apex:inputField id="SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE" value="{!QuotesPage.SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE__c}"/>{!$ObjectType.Quotes__c.fields.SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE__c.label}</td>
+                        </tr>
+
+                         <tr>
+                            <td colspan="2" align="left" ><apex:inputField id="SUBSIDIARY" value="{!QuotesPage.SUBSIDIARY__c}"/></td>
+                            <td colspan="2" align="left" ><apex:inputField id="SALES_TEAM_AUTO_ASSIGN_ON_SAVE" value="{!QuotesPage.SALES_TEAM_AUTO_ASSIGN_ON_SAVE__c}"/>{!$ObjectType.Quotes__c.fields.SALES_TEAM_AUTO_ASSIGN_ON_SAVE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.TAX_ID__c.label}</td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.LEAD_TIME__c.label}<span class="textRed">*</span></td>
+                            
+
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="TAX_ID" value="{!QuotesPage.TAX_ID__c }" /></td>
+                            <td></td>
+                            <td align="left" ><apex:inputField id="LEAD_TIME" value="{!QuotesPage.LEAD_TIME__c }" style="width: 95%"/>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.STATUS__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.BILLING_SCHEDULE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="STATUS" value="{!QuotesPage.STATUS__c }" onchange="StatusChangeFunction();" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="BILLING_SCHEDULE" value="{!QuotesPage.BILLING_SCHEDULE__c }" style="width: 95%"/>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_WORKFLOW_TYPE__c.label}</td>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.LEAD_SOURCE__c.label}</td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" ><apex:inputField id="DISCOUNT_WORKFLOW_TYPE" value="{!QuotesPage.DISCOUNT_WORKFLOW_TYPE__c}" style="width: 65%"/>
+                            </td>
+                            <td align="left" ><apex:inputField id="LEAD_SOURCE" value="{!QuotesPage.LEAD_SOURCE__c}"/>
+                            </td>
+                            
+                        </tr>
+                       
+                        <tr>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_STATUS__c.label}</td>
+
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                             <td align="left" ><apex:inputField id="DISCOUNT_STATUS" value="{!QuotesPage.DISCOUNT_STATUS__c}" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="ONLINE_BILLING" value="{!QuotesPage.ONLINE_BILLING__c }"/>{!$ObjectType.Quotes__c.fields.ONLINE_BILLING__c.label}
+                            </td>
+                            
+                        </tr>
+                        <tr>
+                            <!-- <td/> -->
+                           <td colspan="2" align="left" ><apex:inputField id="INITIATE_APPROVAL_ROUTING" value="{!QuotesPage.INITIATE_APPROVAL_ROUTING__c }"/>{!$ObjectType.Quotes__c.fields.INITIATE_APPROVAL_ROUTING__c.label}
+                            </td> 
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_STATUS_ROUTING__c.label} </td>
+
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.ONLINE_BILLING_ADDRESS__c.label}</td>
+
+                            
+
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="DISCOUNT_STATUS_ROUTING" value="{!QuotesPage.DISCOUNT_STATUS_ROUTING__c}" style="width: 100%"/></td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="ONLINE_BILLING_ADDRESS" value="{!QuotesPage.ONLINE_BILLING_ADDRESS__c}"/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.PROBABILITY__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.PRODUCT_SEGMENT__c.label}<span class="textRed">*</span></td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputText id="PROBABILITY" value="{!QuotesPage.PROBABILITY__c }"/>
+                                <apex:inputText id="DisplayPROBABILITY" value="{!QuotesPage.PROBABILITY__c}" style="display: none;"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="PRODUCT_SEGMENT" value="{!QuotesPage.PRODUCT_SEGMENT__c}" style="width: 95%"/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.LOCATION__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:inputField value="{!QuotesPage.FDA_REPORT_COMPLETE__c }"/>{!$ObjectType.Quotes__c.fields.FDA_REPORT_COMPLETE__c.label}</td>
+                        </tr>
+                        <tr>
+                        
+
+                            <td align="left" ><apex:inputField id="LOCATION" value="{!QuotesPage.LOCATION__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SWOName__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.TERMS__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td align="left" >
+                            <apex:outputLink value="/apex/SWOPageRead?id={!QuotesPage.SWO__c}&type=Quotes" target="LINK_{!QuotesPage.SWO__c}" ><c:PDFWbr targetStr="{!QuotesPage.SWOName__c}"/></apex:outputLink>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="TERMS" value="{!QuotesPage.TERMS__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.CONTRACT_NAME__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="TERMS_OVERRIDE" value="{!QuotesPage.TERMS_OVERRIDE__c }" />{!$ObjectType.Quotes__c.fields.TERMS_OVERRIDE__c.label}
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="CONTRACT_NAME" value="{!QuotesPage.CONTRACT_NAME__c}" style="width: 95%"/> </td>
+                        </tr>
+
+                        <tr>
+                            
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.PO__c.label}</td>
+                            
+                            <td/>
+                            
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.QUOTE_TITLE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="PO" value="{!QuotesPage.PO__c }"/></td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="QUOTE_TITLE" value="{!QuotesPage.QUOTE_TITLE__c}"/></td>
+                        </tr>
+                        
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.EXPIRES__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.PKMS_PO_FOR_RECEIPT__c.label}</td>
+                            
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="EXPIRES" value="{!QuotesPage.EXPIRES__c }" />
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="PKMS_PO_FOR_RECEIPT" value="{!QuotesPage.PKMS_PO_FOR_RECEIPT__c}"/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.EXP_CLOSE__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.REVISION_NEEDED__c.label}</td>
+
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="EXP_CLOSE" value="{!QuotesPage.EXP_CLOSE__c }"/></td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="REVISION_NEEDED" value="{!QuotesPage.REVISION_NEEDED__c}" style="width: 95%"/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.ORDER_TYPE__c.label}<span class="textRed">*</span></td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.COLLECTION_STATUS__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            
+                            <td align="left" ><apex:inputField id="ORDER_TYPE" value="{!QuotesPage.ORDER_TYPE__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="COLLECTION_STATUS" value="{!QuotesPage.COLLECTION_STATUS__c}" style="width: 95%"/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.NO_CHARGE_TYPE__c.label}</td>
+                            <td/>
+                            <td colspan="2" align="left" >CONSOLIDATED INVOICE NUMBER</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="NO_CHARGE_TYPE" value="{!QuotesPage.NO_CHARGE_TYPE__c }" style="width: 100%"/></td>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.SHIP_TO_ENTITY_USE_CODE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:inputField id="SHIP_TO_ENTITY_USE_CODE" value="{!QuotesPage.SHIP_TO_ENTITY_USE_CODE__c}" style="width: 56%"/></td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.BILL_TO_ENTITY_USE_CODE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:inputField id="BILL_TO_ENTITY_USE_CODE" value="{!QuotesPage.BILL_TO_ENTITY_USE_CODE__c}" style="width: 54%"/></td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="3" align="left" >{!$ObjectType.Quotes__c.fields.INVOICE_MESSAGING__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="3" align="left" ><apex:inputField id="INVOICE_MESSAGING" value="{!QuotesPage.INVOICE_MESSAGING__c}" style="width: 63%"/></td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:inputField id="IS_SELLER_IMPORTER_OF_RECORD" value="{!QuotesPage.IS_SELLER_IMPORTER_OF_RECORD__c }" />{!$ObjectType.Quotes__c.fields.IS_SELLER_IMPORTER_OF_RECORD__c.label}
+                            </td>
+                            
+                        </tr>
+                        
+                        
+                        
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Address</th>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.BILL_TO__c.label}</td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SHIP_TO__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" ><apex:inputField id="BILL_TO" value="{!QuotesPage.BILL_TO__c }" style="width: 90%;height: 80PX"/></td>
+                            <td colspan="2" align="left" ><apex:inputField id="SHIP_TO" value="{!QuotesPage.SHIP_TO__c}" style="width: 90%;height: 80PX"/></td> 
+                        </tr>
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Shipping</th>
+
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_COST__c.label}</td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_TAX_RATE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="SHIPPING_COST" value="{!QuotesPage.SHIPPING_COST__c }" />
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="SHIPPING_TAX_RATE" value="{!QuotesPage.SHIPPING_TAX_RATE__c}" style="width: 90%"/></td>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.TOTAL_TRANSACTION_ITEM_WEIGHT_KGS__c.label}</td>
+                            <td/>
+                            <td/>                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="TOTAL_TRANSACTION_ITEM_WEIGHT_KGS" value="{!QuotesPage.TOTAL_TRANSACTION_ITEM_WEIGHT_KGS__c }"/></td>
+                            <td/>
+                            <td/>                            
+                        
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_CARRIER__c.label}</td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_TAX_CODE__c.label}</td>
+                        </tr>
+                         <tr>
+                            <td align="left" ><apex:inputField id="SHIPPING_CARRIER" value="{!QuotesPage.SHIPPING_CARRIER__c }" style="width: 100%"/></td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="SHIPPING_TAX_CODE" value="{!QuotesPage.SHIPPING_TAX_CODE__c}" style="width: 95%"/></td>
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SHIP_VIA__c.label}</td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.INCOTERM__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="SHIP_VIA" value="{!QuotesPage.SHIP_VIA__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="INCOTERM" value="{!QuotesPage.INCOTERM__c}" style="width: 95%"/></td>  
+                        </tr>
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Items</th>
+                        
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_ITEM__c.label}</td>
+                            <td/>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.SWO_PART_NUMBERS__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="DISCOUNT_ITEM" value="{!QuotesPage.DISCOUNT_ITEM__c }" onchange="DISCOUNTITEMChangeFunction();" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:inputField id="SWO_PART_NUMBERS" value="{!QuotesPage.SWO_PART_NUMBERS__c}"/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.RATE__c.label}</td>
+                            <td/>
+                            <td align="left" ><apex:inputField id="TAX_OVERRIDE" value="{!QuotesPage.TAX_OVERRIDE__c}"/>{!$ObjectType.Quotes__c.fields.TAX_OVERRIDE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputText id="RATE" value="{!QuotesPage.RATE__c }"/>
+                                <apex:inputText id="RATEDisplay" value="{!QuotesPage.RATE__c}" style="display: none;"/>
+                            <td/>
+                            <td/>
+                        </td>
+                        </tr>
+                        <tr>
+                           <td align="left" >{!$ObjectType.Quotes__c.fields.SWO_SERIAL__c.label}</td>
+                            <td/>
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="SWO_SERIAL" value="{!QuotesPage.SWO_SERIAL__c }"/>
+                            </td>
+                            <td/>
+                        </tr>
+                        
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Messages</th>
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <tr>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.QuotesType__c.label}</td>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:inputField id="QuotesType" value="{!QuotesPage.QuotesType__c }" onchange="QuotesTypeChangeFunction();"  style="width: 70%"/>
+                                </td>
+                            <td>
+                               
+                            </td>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                        </tr>
+                        
+                                <tr>
+                                    <apex:outputPanel layout="none" rendered="{!IF(aftORbef == false && aftORbef1 == false, true, false)}">
+                                        <td colspan="9">
+                                        <apex:outputText id="message01" value="{!Messages01}" style="resize:vertical;width: 100%"/>
+                                        </td>
+                                    </apex:outputPanel> 
+                                </tr>
+                                <tr>
+                                    <apex:outputPanel layout="none" rendered="{!IF(aftORbef == true || aftORbef1 == true, true, false)}">
+                                        <td colspan="9">
+                                        <apex:outputText value="-缁翠慨璐ㄤ繚鍙兜鐩栦簬鏈缁翠慨鐨勯厤浠讹紝缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿��" style="resize:vertical;width: 100%"/>
+                                        </td>
+                                    </apex:outputPanel> 
+                                </tr>
+                                <tr>
+                                    <td colspan="9">
+                                     <apex:outputText id="message02" value="{!Messages02}" style="resize:vertical;width: 100%"/>
+                                </td> 
+                                </tr>
+                                <tr>
+                                    <td colspan="9">
+                                     <apex:outputText id="message03" value="{!Messages03}" style="resize:vertical;width: 100%"/>
+                                </td> 
+                                </tr>
+                                <tr>
+                                    <td colspan="9">
+                                     <apex:outputText id="message04" value="{!Messages04}" style="resize:vertical;width: 100%"/>
+                                </td> 
+                                </tr>
+                                <tr>
+                                    <td colspan="9">
+                                     <apex:outputText id="message05" value="{!Messages05}" style="resize:vertical;width: 100%"/>
+                                </td> 
+                                </tr>
+                                <tr>
+                                    <td colspan="9">
+                                     <apex:outputText id="message06" value="{!Messages06}" style="resize:vertical;width: 100%"/>
+                                </td> 
+                                </tr>
+                                <tr>
+                                    <td colspan="9">
+                                     <apex:outputText id="message07" value="{!Messages07}" style="resize:vertical;width: 100%"/>
+                                </td> 
+                                </tr>
+                                
+                    </table>
+                </apex:pageBlock>
+            </apex:outputPanel>
+
+            </apex:pageblocksection>
+            <apex:pageblocksection columns="1"  title="QuotesItem" id="ProductInfoList">
+                <apex:outputPanel >
+                    <!-- <table > -->
+                        <!-- <td style="width:130px;"> -->
+                            <apex:commandButton rerender="dummy" id="Btn_RowUp" onclick="radioChecker2('up');return false;" value="涓婅皟琛屽彿" style="width:60px;"/>
+                            <apex:commandButton rerender="dummy" id="Btn_RowDown" onclick="radioChecker2('down');return false;" value="涓嬭皟琛屽彿" style="width:60px;"/>
+                        <!-- </td> -->
+                    <!-- </table>         -->
+                    <DIV style="OVERFLOW-Y: hidden; OVERFLOW-X:auto;width:1260px">
+                         
+                        <div id="ProductInfoList:tablediv" style="OVERFLOW-X: hidden; OVERFLOW-Y:auto;width:4000px; height:200px">
+
+                            <table id="theTable_header" border="2" style="width:4000px;border-bottom-width: 0px; font-size:11px; border-spacing:0;text-align: left;" styleClass="list"> 
+                            <thead>
+                                
+                                <tr style="background-color: #ccc;">
+                                    <td class="center" style ="width: 1%;text-align: center" scope="col"></td>
+                                    <td class="center" style ="width: 1%;text-align: center" scope="col">No</td>
+
+                                    
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">ProductName</td>
+                                    <td class="center" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.QuotesItemName__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 3%;;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.PART_NUMBERNew__c.label}</td>
+                                
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.ON_HAND__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.QUANTITY__c.label}</td>
+                                    
+                                    
+                                    <td class="center" style ="width: 5%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.DESCRIPTION__c.label}</td>
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.PRICE_LEVEL__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.RATE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.AMOUNT__c.label}</td>
+                                    
+                                    <td class="centerLong" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.PRE_APPROVED_DISCOUNT__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.DISCOUNTED_RATE__c.label}</td>
+                                     
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.EST_COST__c.label}</td>
+                                    
+                                    <td class="centerLong" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.EST_GROSS_MARGIN__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.TAX_CODE__c.label}<span class="textRed">*</span></td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.TAX_RATE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.TAX_AMT__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.GROSS_AMT__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 4%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.LOCATION__c.label}<span class="textRed">*</span></td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.OPTIONS__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.EXPECTED_SHIP_DATE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 5%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.ITEM_NOTE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.SERIALIZED__c.label}</td>
+                                    
+                                    <td class="centerLong" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.SWOName__c.label}</td>
+                                    
+                                    
+                                </tr>
+                            </thead>
+                        </table>
+                        <apex:dataTable value="{!productInfoList}"  var="ProductInfo" id="theTable_content" border="2" 
+                            style="width:4000px;border-bottom-width: 0px; font-size:11px; border-spacing:0;text-align: left;" styleClass="list">
+                                <apex:column style="width: 1%">
+                                    <input type="checkbox" name="checklist" value="{!ProductInfo.lineNumber}" style="width:10px;"/>
+                                </apex:column>
+                                 <!--No  -->
+                                <apex:column style="width: 1%">
+                                    <apex:outputText id="lineNumber" value="{!ProductInfo.lineNumber}" style="resize:vertical;width: 100%"/>
+                                    <!-- <apex:inputText id="lineNumberDisplay" value="{!ProductInfo.quotesItemINFO.LineNumber__c}" style="display: none;"/> -->
+                                    <apex:inputText id="quotesItemIdDisplay" value="{!ProductInfo.quotesItemId}" style="display: none;"/>
+                                </apex:column>
+                                 
+                                <!-- ProductName -->
+                                <apex:column style="width: 2%">
+                                    <!-- <apex:inputText styleClass="centerItem"  id="ProductName"  value="{!ProductInfo.productName}" onclick="searchProduct('{!ProductInfo.lineNumber}',this.value)" onchange="doReroadJs('{!ProductInfo.lineNumber}');" style="resize:vertical;width: 95%">
+                                        
+                                    </apex:inputText> -->
+                                    <apex:inputText styleClass="centerItem"  id="ProductName"  value="{!ProductInfo.productName}" onclick="searchProduct('{!ProductInfo.lineNumber}',this.value)" style="resize:vertical;width: 95%">
+                                        
+                                    </apex:inputText>
+                                    <apex:inputText id="productId" value="{!ProductInfo.productId}" style="display: none;"/>
+                                </apex:column>
+                                <!-- ITEM -->
+                                <apex:column style="width: 3%">
+                                    
+                                    <apex:outputLink styleClass="centerItemLink" id="QuotesItemNameLink" value="/{!ProductInfo.quotesItemINFO.Id}" target="LINK_{!ProductInfo.quotesItemINFO.Id}" ><c:PDFWbr targetStr="{!ProductInfo.quotesItemINFO.QuotesItemName__c}"/></apex:outputLink>
+                                </apex:column>
+                                <!-- Part Number -->
+                                <!-- align -->
+                                <apex:column style="width: 3%" >
+                                    <apex:outputText id="PART_NUMBER" styleClass="centerItem" style="width:95%;text-align:left;" value="{!ProductInfo.quotesItemINFO.PART_NUMBERNew__c}"
+                                     />
+                                </apex:column>
+                                <!-- ON HAND -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="ON_HAND"  style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.ON_HAND__c}" />
+                                </apex:column>
+                                <!-- Quantity -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputText styleClass="centerItem"  id="quantity"  value="{!ProductInfo.quotesItemINFO.QUANTITY__c}" onchange="sum('{!ProductInfo.lineNumber}');"  style="width:95%;text-align:left;">
+                                        
+                                    </apex:inputText>
+                                </apex:column>
+                                <!-- Description -->
+                                <apex:column style="width: 5%">
+                                    <apex:inputField id="Description" style="width:95%;text-align:left;" value="{!ProductInfo.quotesItemINFO.DESCRIPTION__c}" />
+                                </apex:column>
+                                <!-- PRICE LEVEL -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="PRICE_LEVEL" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.PRICE_LEVEL__c}" />
+                                </apex:column>
+                                <!-- RATE -->
+                                <apex:column style="width:2%">
+                                    <apex:inputText styleClass="centerItem"  id="RATE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.RATE__c}" onchange="sum('{!ProductInfo.lineNumber}');"/>
+                                </apex:column>
+                                <!-- AMOUNT -->
+                                <apex:column style="width: 3%">
+                                    <!-- <apex:outputText styleClass="centerItem"  id="AMOUNT" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.AMOUNT__c}" /> -->
+                                    <apex:outputText styleClass="centerItem"  id="AMOUNT" style="width:95%;text-align:center;" value="{0,number,###,###,##0.00}" >
+                                        <apex:param value="{!ProductInfo.quotesItemINFO.AMOUNT__c}"/>
+                                    </apex:outputText>
+                                </apex:column>
+                                <!-- PRE-APPROVED_DISCOUNT -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="PRE-APPROVED_DISCOUNT" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.PRE_APPROVED_DISCOUNT__c}" />
+                                </apex:column>
+                                <!-- DISCOUNTED RATE -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="DISCOUNTED_RATE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.DISCOUNTED_RATE__c}" />
+                                </apex:column>
+                                <!-- EST. COST -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="EST_COST" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.EST_COST__c}" />
+                                </apex:column>
+                                <!-- EST. GROSS MARGIN -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="EST_GROSS_MARGIN" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.EST_GROSS_MARGIN__c}" />
+                                </apex:column>
+                                <!-- TAX CODE -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="TAX_CODE"  style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.TAX_CODE__c}" onchange="TAXCODEChangeFunction('{!ProductInfo.lineNumber}');">
+                                        
+                                    </apex:inputField>
+                                </apex:column>
+                                <!-- TAX RATE -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputText styleClass="centerItem"  id="TAX_RATE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.TAX_RATE__c}" />
+                                    <apex:inputText styleClass="centerItem"  id="TAX_RATEDisplay" value="{!ProductInfo.quotesItemINFO.TAX_RATE__c}" style="display: none;"/>
+                                </apex:column>
+                                <!-- TAX AMT -->
+                                <apex:column style="width: 2%">
+                                    <!-- <apex:outputText styleClass="centerItem"  id="TAX_AMT" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.TAX_AMT__c}" /> -->
+                                    <apex:outputText styleClass="centerItem"  id="TAX_AMT" style="width:95%;text-align:center;" value="{0,number,###,###,##0.00}" >
+                                        <apex:param value="{!ProductInfo.quotesItemINFO.TAX_AMT__c}"/>
+                                    </apex:outputText>
+                                     <apex:inputText id="TAX_AMTDisplay" value="{!ProductInfo.quotesItemINFO.TAX_AMT__c}" style="display: none;"/>
+                                </apex:column>
+                                <!-- GROSS AMT -->
+                                <apex:column style="width: 2%">
+                                    <!-- <apex:outputText styleClass="centerItem"  id="GROSS_AMT" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.GROSS_AMT__c}" /> -->
+                                    <apex:outputText styleClass="centerItem"  id="GROSS_AMT" style="width:95%;text-align:center;" value="{0,number,###,###,##0.00}" >
+                                        <apex:param value="{!ProductInfo.quotesItemINFO.GROSS_AMT__c}"/>
+                                    </apex:outputText>
+                                    <apex:inputText id="GROSS_AMTDisplay" value="{!ProductInfo.quotesItemINFO.GROSS_AMT__c}" style="display: none;"/>
+                                </apex:column>
+                                <!-- LOCATION -->
+                                <apex:column style="width: 4%">
+                                    <apex:inputField styleClass="centerItem"  id="LOCATION" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.LOCATION__c}" />
+                                </apex:column>
+                                <!-- OPTIONS -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="OPTIONS" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.OPTIONS__c}" />
+                                </apex:column>
+                                <!-- EXPECTED SHIP DATE -->
+                                <apex:column style="width: 3%">
+                                    <apex:inputField styleClass="centerItem"  id="EXPECTED_SHIP_DATE" style="width:50%;text-align:center;" value="{!ProductInfo.quotesItemINFO.EXPECTED_SHIP_DATE__c}" />
+                                </apex:column>
+                                <!-- ITEM NOTE -->
+                                <apex:column style="width: 5%">
+                                    <apex:inputField styleClass="centerItem"  id="ITEM_NOTE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.ITEM_NOTE__c}" />
+                                </apex:column>
+                                <!-- SERIALIZED -->
+                                <apex:column style="width: 2%">
+                                    <apex:inputField styleClass="centerItem"  id="SERIALIZED" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.SERIALIZED__c}" />
+                                </apex:column>
+                                <!-- SERVICE WORK ORDER -->
+                                <apex:column style="width: 3%">
+                                    
+                                    <apex:outputLink styleClass="centerItem"  value="/{!ProductInfo.quotesItemINFO.SERVICE_WORK_ORDER__c}" target="LINK_{!ProductInfo.quotesItemINFO.SERVICE_WORK_ORDER__c}" ><c:PDFWbr targetStr="{!ProductInfo.quotesItemINFO.SWOName__c}"/></apex:outputLink>
+                                </apex:column>
+                                
+                        </apex:dataTable>
+                    </div>
+                </DIV>
+            </apex:outputPanel>
+        </apex:pageblocksection>
+        
+        <apex:pageblocksection columns="1" title="Mail_Merge"   id="Mail_Merge" >
+        <apex:pageBlockSection >
+            <apex:outputPanel >
+                <br/>
+                <apex:commandButton id="openPDF" value="Mail" onclick="openPDF();return false;" style="width: 5%" />
+                
+                <br/>
+                <table id="mailTable"  border="0" style="width: 1100PX">
+                     <colgroup>
+                            <col width="1%"/>
+                            <col width="9%"/>
+                            <col width="4%"/>
+                            <col width="25%"/>
+                            <col width="1%"/>
+                            <col width="12%"/>
+                            <col width="12%"/>
+                            <col width="2%"/>
+                            <col width="5%"/>
+                            <col width="1%"/>
+                        </colgroup>
+                    <tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+                    
+                        <th>VIEW</th> 
+                        <th>DATE</th>
+                        <th>AUTHOR</th>
+                        <th>MESSAGE</th>
+                        <th>EMAIL SENT</th>
+                        <th>PRIMARY RECIPIENT</th>
+                        <th>CC</th>
+                        <th>FILES</th>
+                        <th>ATTACHMENTS</th>
+                        <th>INTERNAL ONLY</th>
+                    </tr>
+                    <apex:repeat value="{!mailList}" var="mail" id="lines">
+                        <tr>
+                            <td><apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=Quotes&typeid={!Id}&openType=View">View</apex:outputLink>&nbsp;&nbsp;<apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=Quotes&typeid={!Id}&openType=Reply">Reply</apex:outputLink></td> 
+                            <td><apex:outputField value="{!mail.mm.DATE__c}" /></td>
+                            <td><apex:outputField value="{!mail.mm.FROM__c}" /></td>
+                            <td><apex:outputField value="{!mail.mm.MESSAGE__c}" /></td>
+                            <td><apex:outputText value="{!mail.mm.EMAIL_SENT__c}"  /></td>
+                            <td><apex:outputField value="{!mail.mm.toName__c}" /></td>
+                            <td><apex:outputField value="{!mail.mm.ccName__c}" /></td>
+                            <td><apex:outputText value="{!mail.haveAtt}" /></td>
+                            <td>
+                                <apex:repeat value="{!mail.attList}" var="att" id="lines">
+                                    <apex:outputLink value="/{!att.Id}" target="LINK_{!att.Id}"><c:PDFWbr targetStr="{!att.Name}" /></apex:outputLink>
+                                    <br/>
+                                </apex:repeat>
+                            </td>
+                            <td><apex:outputText value="YES" /></td>
+                        </tr>
+
+                    </apex:repeat>
+
+                </table>
+            </apex:outputPanel>
+        </apex:pageBlockSection> 
+    </apex:pageblocksection>
+         <apex:commandButton onclick="save2btn();return false;" value="Save" oncomplete="unblockUI();" style="width:5%;" rerender="dummy" />
+    </apex:pageBlock>
+    
+    <table border="0">
+</table>
+</apex:form>
+<!-- <apex:relatedList list="ProcessSteps"/> -->
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NEWCreateSWOQuote.page-meta.xml b/scr/pages/NEWCreateSWOQuote.page-meta.xml
new file mode 100644
index 0000000..5163391
--- /dev/null
+++ b/scr/pages/NEWCreateSWOQuote.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>50.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NEWCreateSWOQuote</label>
+</ApexPage>
diff --git a/scr/pages/NEWCreateSWOQuoteReadOnly.page b/scr/pages/NEWCreateSWOQuoteReadOnly.page
new file mode 100644
index 0000000..b3cb2e6
--- /dev/null
+++ b/scr/pages/NEWCreateSWOQuoteReadOnly.page
@@ -0,0 +1,842 @@
+<apex:page standardController="Quotes__c" extensions="NEWCreateSWOQuoteController" showChat="false" showHeader="true" sidebar="false" action="{!init}" id="Page">
+
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<apex:includeScript value="{!URLFOR($Resource.NewQuoteEntryJS)}"/>
+<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+<script type="text/javascript">
+
+        
+        function openPDF(){
+            
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            var Id = j$(escapeVfId("Id")).value();
+            if (Id == '') {
+                alert('Please save first Quotes');
+                return;
+            }
+            window.open(baseUrl + '/apex/SendEmail?type=Quotes&typeid=' + Id);
+            window.close();
+
+        }
+        
+        function Editbtn() {
+
+            Editbtn.call();
+        }
+
+        function ReturnToSWO(){
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+
+            // "/apex/SWOPageRead?id={!QuotesPage.SWO__c}&type=Quotes"
+            window.open(baseUrl + '/apex/SWOPageRead?id={!QuotesPage.SWO__c}&type=Quotes');
+            window.close();
+        }
+</script>
+<style type="text/css"> 
+        .Page{
+            margin-left: 20px;
+            margin-right: 20px;
+        }
+
+        .title{
+            height: 30px;
+            background-color: #DFE6F0;
+            font-size: 15px;
+            color:#607799;
+            font-weight: bold;
+            line-height:30px;
+        }
+        .title1{
+            height: 15px;
+            background-color: #607799;
+            font-size: 15px;
+            color:#FFFFFF;
+            font-weight: bold;
+        }
+
+        .title2{
+            height: 15px;
+            background-color: #DFE6F0!important;
+            font-size: 15px;
+            color:#FFFFFF;
+            font-weight: bold;
+            line-height:15px;
+
+        }
+        .pbSubheader {
+            background: #BFB19C;
+            background-color: #607799!important;
+
+
+
+        }
+        .red {
+            background-color:#B22222;
+            text-align: right;
+        }
+
+        .hand{
+            font-weight:bold;
+        }
+        .centerLong {
+            text-align: center;
+            font-weight: bold;
+        }
+        .center {
+            line-height:30px;
+            height:30px;
+            text-align: center;
+            font-size: 10px;
+            color:#FFFFFF;
+            font-weight: bold;
+        }
+
+        .centerItem {
+            /*line-height:15px; */
+            height:15px;
+            text-align: left;
+        }
+    </style>
+<apex:form id="allForm">
+        <input type="hidden" id="Id" value="{!Id}"/>        
+        <apex:actionFunction name="Editbtn" action="{!Editbtn}"></apex:actionFunction>
+        <apex:actionFunction name="Save" action="{!Save}"></apex:actionFunction>
+        <apex:pageBlock title="Quotes" id="allBlock">
+            
+            <apex:commandButton onclick="Editbtn();return false;" value="Edit" style="width:5%;" rerender="dummy" />
+            <apex:commandButton onclick="ReturnToSWO();return false;" value="Return To SWO" style="width:8%;" rerender="dummy" />
+            
+            <apex:pageblocksection columns="1" title="QuotesInfo" id="Quotes" >
+
+                <apex:outputPanel id="allPanel">
+                <apex:pageBlock title="" id="unEditable" rendered="true">
+                    <table class="formtable" width="100%" border="0">
+                         <colgroup>
+                            <col width="27%"/>   
+                            <col width="5%"/>
+                            <col width="27%"/>
+                            <col width="5%"/>
+                            <col width="2%"/>
+                            <col width="1%"/>
+                            <col width="10%"/>
+                            <col width="5%"/>
+                            <col width="20%"/>
+                        </colgroup>
+                        <tr>
+                            <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th  colspan="9" class="title">Estimate</th>
+                        <tr>
+                            <td  class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.CURRENCY__c.label}</td>
+                            <td  class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_NAME__c.label}</td>                            
+                        </tr>
+                        <tr>
+
+                            <td colspan="2" align="left" ><apex:outputField id="CURRENCY" value="{!QuotesPage.CURRENCY__c}" style="width: 56%"/></td>
+                            <td colspan="2" align="left" ><apex:outputField value="{!QuotesPage.CONTACT_NAME__c}" style="width: 63%"/></td>
+                            <td colspan="2"/>
+                            <td colspan="2" class="title1">Summary</td>
+                            <td/>
+                            <td/>
+
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >CUSTOMER:JOB</td>
+                            
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_PHONE__c.label}</td>
+                            <td colspan="3"/>
+                            <td class="title2">{!$ObjectType.Quotes__c.fields.SUBTOTAL__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.SUBTOTAL__c}" style="width: 62%"/></td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" ><apex:outputField id="COMPANY" value="{!QuotesPage.COMPANY__c}"/>
+                            </td>
+                            <td align="left" ><apex:outputField id="CONTACT_PHONE" value="{!QuotesPage.CONTACT_PHONE__c}"/></td>
+                            <td colspan="3"/>
+                            <td class="title2">{!$ObjectType.Quotes__c.fields.DISCOUNT__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.DISCOUNT__c}" style="width: 62%"/></td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.DATE__c.label}</td>
+                            <td ></td>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_FAX__c.label}</td>
+                            <td colspan="3"/>
+                            <td  class="title2">{!$ObjectType.Quotes__c.fields.TAX__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.TAX__c}" style="width: 62%"/></td>
+                            <td/>
+
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="DATE" value="{!QuotesPage.DATE__c }" />
+                            </td>
+                            <td></td>
+                            <td align="left" ><apex:outputField id="CONTACT_FAX" value="{!QuotesPage.CONTACT_FAX__c}"/></td>
+                            <td colspan="3"/>
+                             <td class="title2">{!$ObjectType.Quotes__c.fields.TOTAL__c.label}</td>
+                            <td class="title2" align="left" ><apex:outputField value="{!QuotesPage.TOTAL__c}" style="width: 62%"/></td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.ESTIMATE__c.label}</td>
+                            <td></td>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.CONTACT_EMAIL__c.label}</td>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="ESTIMATE" value="{!QuotesPage.ESTIMATE__c }" /></td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="CONTACT_EMAIL" value="{!QuotesPage.CONTACT_EMAIL__c}"/></td>
+                        
+                        </tr>
+                        <tr>
+                             <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.OPPORTUNITY__c.label}</td>
+                             <td></td>
+                            <td class="hand" align="left" ><apex:outputField id="GSA_ORDER" value="{!QuotesPage.GSA_ORDER__c}"/>{!$ObjectType.Quotes__c.fields.GSA_ORDER__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="OPPORTUNITY" value="{!QuotesPage.OPPORTUNITY__c }"/></td>
+                            <td/>
+                            <td colspan="2" class="hand" align="left" ><apex:outputField id="GOVERNMENT_ORDER" value="{!QuotesPage.GOVERNMENT_ORDER__c}"/>{!$ObjectType.Quotes__c.fields.GOVERNMENT_ORDER__c.label}</td>
+                        </tr>
+                        <tr>
+                            
+                            <td colspan="2" class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SUBSIDIARY__c.label}</td>
+                            <td class="hand" colspan="3" align="left" ><apex:outputField id="SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE" value="{!QuotesPage.SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE__c}"/>{!$ObjectType.Quotes__c.fields.SALES_TEAM_AUTO_ASSIGNMENT_OVERRIDE__c.label}</td>
+                        </tr>
+
+                         <tr>
+                            <td colspan="2" align="left" ><apex:outputField id="SUBSIDIARY" value="{!QuotesPage.SUBSIDIARY__c}"/></td>
+                            <td colspan="2" class="hand" align="left" ><apex:outputField id="SALES_TEAM_AUTO_ASSIGN_ON_SAVE" value="{!QuotesPage.SALES_TEAM_AUTO_ASSIGN_ON_SAVE__c}"/>{!$ObjectType.Quotes__c.fields.SALES_TEAM_AUTO_ASSIGN_ON_SAVE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.TAX_ID__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.LEAD_TIME__c.label}</td>
+                            
+
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="TAX_ID" value="{!QuotesPage.TAX_ID__c }" /></td>
+                            <td></td>
+                            <td align="left" ><apex:outputField id="LEAD_TIME" value="{!QuotesPage.LEAD_TIME__c }" style="width: 95%"/>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.STATUS__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.BILLING_SCHEDULE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" colspan="2"><apex:outputField id="STATUS" value="{!QuotesPage.STATUS__c }" style="width: 100%"/>
+                            </td>
+                            <!-- <td/> -->
+                            <td align="left" ><apex:outputField id="BILLING_SCHEDULE" value="{!QuotesPage.BILLING_SCHEDULE__c }" style="width: 95%"/>
+                            </td>
+                        </tr>
+                        <!-- <tr>
+                            <td colspan="2" class="hand" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_WORKFLOW_TYPE__c.label}</td>
+                            <td/>
+                        </tr> -->
+                        <!-- <tr>
+                            <td colspan="2" align="left" ><apex:outputField id="DISCOUNT_WORKFLOW_TYPE" value="{!QuotesPage.DISCOUNT_WORKFLOW_TYPE__c}" style="width: 65%"/>
+                            </td>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.LEAD_SOURCE__c.label}</td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td align="left" ><apex:outputField id="LEAD_SOURCE" value="{!QuotesPage.LEAD_SOURCE__c}"/>
+                            </td>
+                        </tr> -->
+                        <tr>
+                            <td colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_WORKFLOW_TYPE__c.label}</td>
+                            <td align="left" >{!$ObjectType.Quotes__c.fields.LEAD_SOURCE__c.label}</td>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" ><apex:outputField id="DISCOUNT_WORKFLOW_TYPE" value="{!QuotesPage.DISCOUNT_WORKFLOW_TYPE__c}" style="width: 65%"/>
+                            </td>
+                            <td align="left" ><apex:outputField id="LEAD_SOURCE" value="{!QuotesPage.LEAD_SOURCE__c}"/>
+                            </td>
+                            
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_STATUS__c.label}</td>
+
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                             <td align="left" ><apex:outputField id="DISCOUNT_STATUS" value="{!QuotesPage.DISCOUNT_STATUS__c}" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td class="hand" align="left" ><apex:outputField id="ONLINE_BILLING" value="{!QuotesPage.ONLINE_BILLING__c }"/>{!$ObjectType.Quotes__c.fields.ONLINE_BILLING__c.label}
+                            </td>
+                            
+                        </tr>
+                        <tr>
+                            <!-- <td/> -->
+                           <td class="hand" colspan="2" align="left" ><apex:outputField id="INITIATE_APPROVAL_ROUTING" value="{!QuotesPage.INITIATE_APPROVAL_ROUTING__c }"/>{!$ObjectType.Quotes__c.fields.INITIATE_APPROVAL_ROUTING__c.label}
+                            </td> 
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_STATUS_ROUTING__c.label} </td>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.ONLINE_BILLING_ADDRESS__c.label}</td>
+
+                            
+
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="DISCOUNT_STATUS_ROUTING" value="{!QuotesPage.DISCOUNT_STATUS_ROUTING__c}" style="width: 100%"/></td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="ONLINE_BILLING_ADDRESS" value="{!QuotesPage.ONLINE_BILLING_ADDRESS__c}"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.PROBABILITY__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.PRODUCT_SEGMENT__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="PROBABILITY" value="{!QuotesPage.PROBABILITY__c }"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="PRODUCT_SEGMENT" value="{!QuotesPage.PRODUCT_SEGMENT__c}" style="width: 95%"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.LOCATION__c.label}</td>
+                            <td/>
+                            <td class="hand" colspan="2" align="left" ><apex:outputField value="{!QuotesPage.FDA_REPORT_COMPLETE__c }"/>{!$ObjectType.Quotes__c.fields.FDA_REPORT_COMPLETE__c.label}</td>
+                        </tr>
+                        <tr>
+                        
+
+                            <td align="left" ><apex:outputField id="LOCATION" value="{!QuotesPage.LOCATION__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SWOName__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.TERMS__c.label}</td>
+                            <td/>
+                            <td align="left" >
+                            <apex:outputLink value="/apex/SWOPageRead?id={!QuotesPage.SWO__c}&type=Quotes" target="LINK_{!QuotesPage.SWO__c}" ><c:PDFWbr targetStr="{!QuotesPage.SWOName__c}"/></apex:outputLink>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="TERMS" value="{!QuotesPage.TERMS__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.CONTRACT_NAME__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="2" align="left" ><apex:outputField id="TERMS_OVERRIDE" value="{!QuotesPage.TERMS_OVERRIDE__c }" />{!$ObjectType.Quotes__c.fields.TERMS_OVERRIDE__c.label}
+                            </td>
+                            <!-- <td/> -->
+                            <td align="left" ><apex:outputField id="CONTRACT_NAME" value="{!QuotesPage.CONTRACT_NAME__c}" style="width: 95%"/> </td>
+                        </tr>
+
+                        <tr>
+                            
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.PO__c.label}</td>
+                            
+                            <td/>
+                            
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.QUOTE_TITLE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="PO" value="{!QuotesPage.PO__c }"/></td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="QUOTE_TITLE" value="{!QuotesPage.QUOTE_TITLE__c}"/></td>
+                        </tr>
+                        
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.EXPIRES__c.label}</td>
+                            <td/>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.PKMS_PO_FOR_RECEIPT__c.label}</td>
+                            
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="EXPIRES" value="{!QuotesPage.EXPIRES__c }" />
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="PKMS_PO_FOR_RECEIPT" value="{!QuotesPage.PKMS_PO_FOR_RECEIPT__c}"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.EXP_CLOSE__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.REVISION_NEEDED__c.label}</td>
+
+                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="EXP_CLOSE" value="{!QuotesPage.EXP_CLOSE__c }"/></td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="REVISION_NEEDED" value="{!QuotesPage.REVISION_NEEDED__c}" style="width: 95%"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.ORDER_TYPE__c.label}</td>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.COLLECTION_STATUS__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            
+                            <td colspan="2" align="left" ><apex:outputField id="ORDER_TYPE" value="{!QuotesPage.ORDER_TYPE__c }" style="width: 100%"/>
+                            </td>
+                            <td align="left" ><apex:outputField id="COLLECTION_STATUS" value="{!QuotesPage.COLLECTION_STATUS__c}" style="width: 95%"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.NO_CHARGE_TYPE__c.label}</td>
+                            <!-- CONSOLIDATED INVOICE NUMBER -->
+                            <td class="hand" colspan="2" align="left" >CONSOLIDATED INVOICE NUMBER</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="NO_CHARGE_TYPE" value="{!QuotesPage.NO_CHARGE_TYPE__c }" style="width: 100%"/></td>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.SHIP_TO_ENTITY_USE_CODE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:outputField id="SHIP_TO_ENTITY_USE_CODE" value="{!QuotesPage.SHIP_TO_ENTITY_USE_CODE__c}" style="width: 56%"/></td>
+                        </tr>
+                        <tr>
+                            <!-- BILL-TO ENTITY/USE CODE -->
+                            <td/>
+                            <td/>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.BILL_TO_ENTITY_USE_CODE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="2" align="left" ><apex:outputField id="BILL_TO_ENTITY_USE_CODE" value="{!QuotesPage.BILL_TO_ENTITY_USE_CODE__c}" style="width: 54%"/></td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td class="hand" colspan="3" align="left" >{!$ObjectType.Quotes__c.fields.INVOICE_MESSAGING__c.label}</td>
+                            
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td colspan="3" align="left" ><apex:outputField id="INVOICE_MESSAGING" value="{!QuotesPage.INVOICE_MESSAGING__c}" style="width: 63%"/></td>
+                        </tr>
+                        <tr>
+                            <td/>
+                            <td/>
+                            <td class="hand" colspan="2" align="left" ><apex:outputField id="IS_SELLER_IMPORTER_OF_RECORD" value="{!QuotesPage.IS_SELLER_IMPORTER_OF_RECORD__c }" />{!$ObjectType.Quotes__c.fields.IS_SELLER_IMPORTER_OF_RECORD__c.label}
+                            </td>
+                            
+                        </tr>
+                        
+                        
+                        
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Address</th>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.BILL_TO__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SHIP_TO__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td colspan="2" align="left" ><apex:outputField id="BILL_TO" value="{!QuotesPage.BILL_TO__c }" style="width: 90%;height: 80PX"/></td>
+                            <td colspan="2" align="left" ><apex:outputField id="SHIP_TO" value="{!QuotesPage.SHIP_TO__c}" style="width: 90%;height: 80PX"/></td> 
+                        </tr>
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Shipping</th>
+
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_COST__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_TAX_RATE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="SHIPPING_COST" value="{!QuotesPage.SHIPPING_COST__c }" />
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="SHIPPING_TAX_RATE" value="{!QuotesPage.SHIPPING_TAX_RATE__c}" style="width: 90%"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="4" align="left" >{!$ObjectType.Quotes__c.fields.TOTAL_TRANSACTION_ITEM_WEIGHT_KGS__c.label}</td>
+                            <td/>
+                            <td/>                            
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="TOTAL_TRANSACTION_ITEM_WEIGHT_KGS" value="{!QuotesPage.TOTAL_TRANSACTION_ITEM_WEIGHT_KGS__c }"/></td>
+                            <td/>
+                            <td/>                            
+                        
+                        </tr>
+                        <tr>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_CARRIER__c.label}</td>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SHIPPING_TAX_CODE__c.label}</td>
+                        </tr>
+                         <tr>
+                            <td align="left" ><apex:outputField id="SHIPPING_CARRIER" value="{!QuotesPage.SHIPPING_CARRIER__c }" style="width: 100%"/></td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="SHIPPING_TAX_CODE" value="{!QuotesPage.SHIPPING_TAX_CODE__c}" style="width: 95%"/></td>
+                            
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SHIP_VIA__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.INCOTERM__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="SHIP_VIA" value="{!QuotesPage.SHIP_VIA__c }" style="width: 100%"/>
+                            </td>
+                            <td/>
+                            <td align="left" ><apex:outputField id="INCOTERM" value="{!QuotesPage.INCOTERM__c}" style="width: 95%"/></td>  
+                        </tr>
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Items</th>
+                        
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.DISCOUNT_ITEM__c.label}</td>
+                            <td/>
+                            <td class="hand" colspan="2" align="left" >{!$ObjectType.Quotes__c.fields.SWO_PART_NUMBERS__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" colspan="2"><apex:outputField id="DISCOUNT_ITEM" value="{!QuotesPage.DISCOUNT_ITEM__c }" style="width: 100%"/>
+                            </td>
+                            <td colspan="2" align="left" ><apex:outputField id="SWO_PART_NUMBERS" value="{!QuotesPage.SWO_PART_NUMBERS__c}"/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.RATE__c.label}</td>
+                            <td/>
+                            <td class="hand" align="left" ><apex:outputField id="TAX_OVERRIDE" value="{!QuotesPage.TAX_OVERRIDE__c}"/>{!$ObjectType.Quotes__c.fields.TAX_OVERRIDE__c.label}</td>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="RATE" value="{!QuotesPage.RATE__c }"/></td>
+                            <td/>
+                            <td/>
+                        
+                        </tr>
+                        <tr>
+                           <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.SWO_SERIAL__c.label}</td>
+                            <td/>
+                            <td/> 
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="SWO_SERIAL" value="{!QuotesPage.SWO_SERIAL__c }"/>
+                            </td>
+                            <td/>
+                            <td/>
+                        </tr>
+                        
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <th colspan="9" class="title">Messages</th>
+                         <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                        <tr>
+                            <td class="hand" align="left" >{!$ObjectType.Quotes__c.fields.QuotesType__c.label}</td>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td align="left" ><apex:outputField id="QuotesType" value="{!QuotesPage.QuotesType__c }" style="width: 70%"/>
+                                </td>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                            <td/>
+                        </tr>
+                        <tr>
+                            <td colspan="9">
+                                <apex:outputField value="{!QuotesPage.CUSTOMER_MESSAGE__c}" style="width: 70%"/><br/>
+                            </td>
+                        </tr>
+                        <tr>
+                             <td colspan="9"> <hr/></td>
+                        </tr>
+                    </table>
+                </apex:pageBlock>
+            </apex:outputPanel>
+
+            </apex:pageblocksection>
+            <apex:pageblocksection columns="1" title="QuotesItem"  id="ProductInfoList">
+                <apex:outputPanel >
+                    <DIV style="OVERFLOW-Y: hidden; OVERFLOW-X:auto;width:1260px">
+                         
+                        <div id="ProductInfoList:tablediv" style="OVERFLOW-X: hidden; OVERFLOW-Y:auto;width:4000px; height:200px">
+
+                            <table id="theTable_header" border="2" style="width:4000px;border-bottom-width: 0px; font-size:11px; border-spacing:0;text-align: center;" styleClass="list">
+                                
+                            <thead>
+                                <tr style="background-color: #ccc;">
+
+                                    <td class="center" style ="width: 1%;text-align: center" scope="col">No</td>
+
+                                    
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">ProductName</td>
+                                    <td class="center" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.QuotesItemName__c.label}</td>
+                                    <td class="center" style ="width: 3%;;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.PART_NUMBERNew__c.label}</td>
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.ON_HAND__c.label}</td>
+                                    <td class="center" style ="width: 2%;;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.QUANTITY__c.label}</td>
+                                    <td class="center" style ="width: 5%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.DESCRIPTION__c.label}</td>
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.PRICE_LEVEL__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.RATE__c.label}</td>
+                                   
+                                    <td class="center" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.AMOUNT__c.label}</td>
+                                    
+                                    <td  class="centerLong" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.PRE_APPROVED_DISCOUNT__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.DISCOUNTED_RATE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.EST_COST__c.label}</td>
+                                    
+                                    <td  class="centerLong" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.EST_GROSS_MARGIN__c.label}</td>
+                                   
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.TAX_CODE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.TAX_RATE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.TAX_AMT__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.GROSS_AMT__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 4%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.LOCATION__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.OPTIONS__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.EXPECTED_SHIP_DATE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 5%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.ITEM_NOTE__c.label}</td>
+                                    
+                                    <td class="center" style ="width: 2%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.SERIALIZED__c.label}</td>
+                                    
+                                    <td class="centerLong" style ="width: 3%;text-align: center" scope="col">{!$ObjectType.Quotes_item__c.fields.SWOName__c.label}</td>
+                                </tr>
+                            </thead>
+                        </table>
+
+                        <apex:dataTable value="{!productInfoList}"  var="ProductInfo" id="theTable_content" border="2" 
+                            style="width:4000px;border-bottom-width: 0px; font-size:11px; border-spacing:0;text-align: left;" styleClass="list">
+                                 <!--No  -->
+                                <apex:column style="width: 1%">
+                                    <apex:outputText styleClass="centerItem" value="{!ProductInfo.lineNumber}" style="width:95%;text-align:left;"/>
+                                </apex:column>
+                                 
+                                <apex:column style="width: 2%">
+                                    
+                                   <!--  <apex:outputText styleClass="centerItem" id="ProductName"  value="{!ProductInfo.productName}" style="width:100%;text-align:left;"/> -->
+                                    <apex:outputText styleClass="centerItem" id="ProductName" style="width:100%;text-align:left;"><c:PDFWbr targetStr="{!ProductInfo.productName}"/></apex:outputText>
+                                    
+                                </apex:column>
+                                <!-- ITEM -->
+                                <apex:column style="width: 3%">
+                                    
+                                    
+                                    <apex:outputLink styleClass="centerItem" value="/{!ProductInfo.quotesItemINFO.Id}" target="LINK_{!ProductInfo.quotesItemINFO.Id}" ><c:PDFWbr targetStr="{!ProductInfo.quotesItemINFO.QuotesItemName__c}"/></apex:outputLink>
+                            <!-- </td> -->
+                                </apex:column>
+                                <!-- Part Number -->
+                                <apex:column style="width: 3%">
+                                    <apex:outputText styleClass="centerItem" id="PART_NUMBER" style="width:95%;text-align:left;" value="{!ProductInfo.quotesItemINFO.PART_NUMBERNew__c}" />
+                                </apex:column>
+                                <!-- ON HAND -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField styleClass="center" id="ON_HAND" style="width:95%;text-align:left;" value="{!ProductInfo.quotesItemINFO.ON_HAND__c}" />
+                                </apex:column>
+                                <!-- Quantity -->
+                                <apex:column style="width: 2%">
+                                    
+                                    <apex:outputText styleClass="centerItem" id="quantity"  value="{!ProductInfo.quotesItemINFO.QUANTITY__c}" style="width:95%;text-align:left;"/>
+                                        
+                                    <!-- </apex:outputText> -->
+                                </apex:column>
+                                <!-- Description -->
+                                <apex:column style="width: 5%">
+                                    <apex:outputField styleClass="centerItem" id="Description" style="width:95%;text-align:left;" value="{!ProductInfo.quotesItemINFO.DESCRIPTION__c}" />
+                                </apex:column>
+                                <!-- PRICE LEVEL -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="PRICE_LEVEL" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.PRICE_LEVEL__c}" />
+                                </apex:column>
+                                <!-- RATE -->
+                                <apex:column style="width:2%">
+                                    
+                                    <apex:outputText value="{0,number,###,###,##0.00}">
+                                      <apex:param value="{!ProductInfo.quotesItemINFO.RATE__c}"/>
+                                  </apex:outputText>
+                                </apex:column>
+                                <!-- AMOUNT -->
+                                <apex:column style="width: 3%">
+                                    <apex:outputText value="{0,number,###,###,##0.00}">
+                                      <apex:param value="{!ProductInfo.quotesItemINFO.AMOUNT__c}"/>
+                                  </apex:outputText>
+                                </apex:column>
+                                <!-- PRE-APPROVED_DISCOUNT -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="PRE-APPROVED_DISCOUNT" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.PRE_APPROVED_DISCOUNT__c}" />
+                                </apex:column>
+                                <!-- DISCOUNTED RATE -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="DISCOUNTED_RATE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.DISCOUNTED_RATE__c}" />
+                                </apex:column>
+                                <!-- EST. COST -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="EST_COST" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.EST_COST__c}" />
+                                </apex:column>
+                                <!-- EST. GROSS MARGIN -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="EST_GROSS_MARGIN" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.EST_GROSS_MARGIN__c}" />
+                                </apex:column>
+                                <!-- TAX CODE -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="TAX_CODE"  style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.TAX_CODE__c}"/>
+                                        
+                                    <!-- </apex:outputField> -->
+                                </apex:column>
+                                <!-- TAX RATE -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="TAX_RATE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.TAX_RATE__c}" />
+                                </apex:column>
+                                <!-- TAX AMT -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputText value="{0,number,###,###,##0.00}">
+                                      <apex:param value="{!ProductInfo.quotesItemINFO.TAX_AMT__c}"/>
+                                  </apex:outputText>
+                                </apex:column>
+                                <!-- GROSS AMT -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputText value="{0,number,###,###,##0.00}">
+                                      <apex:param value="{!ProductInfo.quotesItemINFO.GROSS_AMT__c}"/>
+                                  </apex:outputText>
+                                </apex:column>
+                                <!-- LOCATION -->
+                                <apex:column style="width: 4%">
+                                    <apex:outputField id="LOCATION" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.LOCATION__c}" />
+                                </apex:column>
+                                <!-- OPTIONS -->
+                                <apex:column style="width: 2%">
+                                    <apex:outputField id="OPTIONS" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.OPTIONS__c}" />
+                                </apex:column>
+                                <!-- EXPECTED SHIP DATE -->
+                                <apex:column style="width: 3%">
+                                    <apex:outputField id="EXPECTED_SHIP_DATE" style="width:50%;text-align:center;" value="{!ProductInfo.quotesItemINFO.EXPECTED_SHIP_DATE__c}" />
+                                </apex:column>
+                                <!-- ITEM NOTE -->
+                                <apex:column style="width: 5%">
+                                    <apex:outputField id="ITEM_NOTE" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.ITEM_NOTE__c}" />
+                                </apex:column>
+                                <!-- SERIALIZED -->
+                                <apex:column style="width: 3%">
+                                    <apex:outputField id="SERIALIZED" style="width:95%;text-align:center;" value="{!ProductInfo.quotesItemINFO.SERIALIZED__c}" />
+                                </apex:column>
+                                <!-- SERVICE WORK ORDER -->
+                                <apex:column style="width: 2%">
+                                    
+                                    <apex:outputLink value="/{!ProductInfo.quotesItemINFO.SERVICE_WORK_ORDER__c}" target="LINK_{!ProductInfo.quotesItemINFO.SERVICE_WORK_ORDER__c}" ><c:PDFWbr targetStr="{!ProductInfo.quotesItemINFO.SWOName__c}"/></apex:outputLink>
+                            <!-- </td> -->
+                                </apex:column>
+                                
+                                
+                        </apex:dataTable>
+                    </div>
+                </DIV>
+            </apex:outputPanel>
+        </apex:pageblocksection>
+        <apex:commandButton onclick="Editbtn();return false;" value="Edit" style="width:5%;" rerender="dummy" />
+        <apex:commandButton onclick="ReturnToSWO();return false;" value="Return To SWO" style="width:8%;" rerender="dummy" />
+        <apex:pageBlockSection columns="1" title="Mail_Merge"   id="Mail_Merge">
+            <apex:outputPanel >
+                <br/>
+                <apex:commandButton id="openPDF" value="Mail" onclick="openPDF();return false;" style="width: 5%" />
+                
+                <br/>
+                <table id="mailTable"  border="0" style="width: 1300PX">
+                     <colgroup>
+                            <col width="1%"/>
+                            <col width="9%"/>
+                            <col width="4%"/>
+                            <col width="25%"/>
+                            <col width="1%"/>
+                            <col width="12%"/>
+                            <col width="12%"/>
+                            <col width="2%"/>
+                            <col width="5%"/>
+                            <col width="1%"/>
+                        </colgroup>
+                    <tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+                    
+                        <th>VIEW</th> 
+                        <th>DATE</th>
+                        <th>AUTHOR</th>
+                        <th>MESSAGE</th>
+                        <th>EMAIL SENT</th>
+                        <th>PRIMARY RECIPIENT</th>
+                        <th>CC</th>
+                        <th>FILES</th>
+                        <th>ATTACHMENTS</th>
+                        <th>INTERNAL ONLY</th>
+                    </tr>
+                    <apex:repeat value="{!mailList}" var="mail" id="lines">
+                        <tr>
+                            <td><apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=Quotes&typeid={!Id}&openType=View">View</apex:outputLink>&nbsp;&nbsp;<apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=Quotes&typeid={!Id}&openType=Reply">Reply</apex:outputLink></td> 
+                            <td><apex:outputField value="{!mail.mm.DATE__c}" /></td>
+                            <td><apex:outputField value="{!mail.mm.FROM__c}" /></td>
+                            <td><apex:outputField value="{!mail.mm.MESSAGE__c}" /></td>
+                            <td><apex:outputText value="{!mail.mm.EMAIL_SENT__c}"  /></td>
+                            <td><apex:outputField value="{!mail.mm.toName__c}" /></td>
+                            <td><apex:outputField value="{!mail.mm.ccName__c}" /></td>
+                            <td><apex:outputText value="{!mail.haveAtt}" /></td>
+                            <td>
+                                <apex:repeat value="{!mail.attList}" var="att" id="lines">
+                                    <apex:outputLink value="/{!att.Id}" target="LINK_{!att.Id}"><c:PDFWbr targetStr="{!att.Name}" /></apex:outputLink>
+                                    <br/>
+                                </apex:repeat>
+                            </td>
+                            <td><apex:outputText value="YES" /></td>
+                        </tr>
+
+                    </apex:repeat>
+
+                </table>
+            </apex:outputPanel>
+        </apex:pageBlockSection> 
+        <!-- <apex:commandButton onclick="Editbtn();return false;" value="Edit" style="width:5%;" rerender="dummy" />
+        <apex:commandButton onclick="ReturnToSWO();return false;" value="Return To SWO" style="width:8%;" rerender="dummy" /> -->
+    </apex:pageBlock>
+    
+    <table border="0">
+</table>
+</apex:form>
+<!-- <apex:relatedList list="ProcessSteps"/> -->
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NEWCreateSWOQuoteReadOnly.page-meta.xml b/scr/pages/NEWCreateSWOQuoteReadOnly.page-meta.xml
new file mode 100644
index 0000000..24296ed
--- /dev/null
+++ b/scr/pages/NEWCreateSWOQuoteReadOnly.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NEWCreateSWOQuoteReadOnly</label>
+</ApexPage>
diff --git a/scr/pages/NewCrossHighOpportunity.page b/scr/pages/NewCrossHighOpportunity.page
new file mode 100644
index 0000000..e26539a
--- /dev/null
+++ b/scr/pages/NewCrossHighOpportunity.page
@@ -0,0 +1,230 @@
+<apex:page id="Page" Controller="NewCrossHighOpportunityController" sidebar="true" showHeader="true" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+    function saveJs() {
+        blockme();
+        saveBtn();
+    }
+
+    function saveYesJs() {
+        blockme();
+        saveBtnYes();
+    }
+
+    function saveNoJs() {
+        blockme();
+        saveBtnNo();
+    }
+
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+        var rtUrl = '{!rtUrl}';
+        if (rtUrl == 'null' || rtUrl == '') {
+            rtUrl = '{!conId}';
+        }
+        window.location.href = baseUrl + "/" + rtUrl;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnYes}" name="saveBtnYes" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnNo}" name="saveBtnNo" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+
+        <input type="hidden" id="hasError" value="{!hasError}"/>
+        <input type="hidden" id="isDealerPage" value="{!isDealerPage}"/>
+
+        <apex:pageBlock id="idSearchSetProduct" title="鏂板缓璇环" tabStyle="Opportunity">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="saveYesJs();" value="鏄�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+                <apex:commandButton style="width:50px" onclick="saveNoJs();" value="鍚�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+            </apex:pageBlockButtons>
+
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦" for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.BudgetAmount__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢" for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦" for="opp_Amount"/>
+                    <apex:inputField value="{!opp.Amount}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡" for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.ExpectedOrderDate__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡" for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.ExpectedDeliveryDate__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮" for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.LeadSource}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤" for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.TradeType__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="System" for="OppSystem__c"/>
+                    <apex:inputField value="{!opp.SystemNew__c}" id="OppSystem__c" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�" for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.SalesChannel__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+                
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName"/>
+                    </apex:pageBlockSectionItem>
+                
+          
+              
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="涓棿鍟嗗悕" for="opp_SubDealer"/>
+                    <apex:inputField value="{!opp.SubDealer__c}" id="opp_SubDealer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗘湇鍔℃媴褰撹�呭悕" for="opp_DealerService"/>
+                    <apex:inputField value="{!opp.DealerService__c}" id="opp_DealerService"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+             <apex:pageBlockSection title="璺ㄥ尯鍩熼攢鍞�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍚堜綔鍖哄煙璐熻矗浜�" for="HeadOfCooperationArea__c"/>
+                    <apex:inputField value="{!opp.HeadOfCooperationArea__c}" id="HeadOfCooperationArea__c"/>
+                </apex:pageBlockSectionItem>
+
+            </apex:pageBlockSection>
+
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1" for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1" for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2" for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2" for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode2__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3" for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3" for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode3__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4" for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4" for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode4__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5" for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5" for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode5__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6" for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6" for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode6__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7" for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7" for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode7__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8" for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8" for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode8__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+        </apex:pageBlock>
+    </apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewCrossHighOpportunity.page-meta.xml b/scr/pages/NewCrossHighOpportunity.page-meta.xml
new file mode 100644
index 0000000..c541984
--- /dev/null
+++ b/scr/pages/NewCrossHighOpportunity.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewCrossHighOpportunity</label>
+</ApexPage>
diff --git a/scr/pages/NewCrossRegionalSalesOpportunity.page b/scr/pages/NewCrossRegionalSalesOpportunity.page
new file mode 100644
index 0000000..a879e0f
--- /dev/null
+++ b/scr/pages/NewCrossRegionalSalesOpportunity.page
@@ -0,0 +1,437 @@
+<apex:page id="Page" Controller="NewCrossRegionalSalesController" sidebar="true" showHeader="true" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+    function saveJs() {
+        blockme();
+        saveBtn();
+    }
+
+    function saveYesJs() {
+        blockme();
+        saveBtnYes();
+    }
+
+    function saveNoJs() {
+        blockme();
+        saveBtnNo();
+    }
+
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+        var rtUrl = '{!rtUrl}';
+        if (rtUrl == 'null' || rtUrl == '') {
+            rtUrl = '{!conId}';
+        }
+        window.location.href = baseUrl + "/" + rtUrl;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnYes}" name="saveBtnYes" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnNo}" name="saveBtnNo" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+
+        <input type="hidden" id="hasError" value="{!hasError}"/>
+        <input type="hidden" id="isDealerPage" value="{!isDealerPage}"/>
+
+        <apex:pageBlock id="idSearchSetProduct" title="鏂板缓璇环" tabStyle="Opportunity">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="saveYesJs();" value="鏄�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+                <apex:commandButton style="width:50px" onclick="saveNoJs();" value="鍚�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+            </apex:pageBlockButtons>
+<apex:outputPanel layout="none" rendered="{!IF(isDealerPage == true, false, true)}">
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦" for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.BudgetAmount__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢" for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦" for="opp_Amount"/>
+                    <apex:inputField value="{!opp.Amount}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+            <!--NO.6 gwy 2021-06-03-->
+                <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'IE', true, false)}">
+                    <apex:outputLabel value="COMPO璇环" for="compo_opp"/>
+                    <apex:inputField value="{!opp.compo_opp__c}" id="compo_opp"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'BS', true, false)}">
+                    <apex:outputLabel value="鐢ㄩ��" for="useing"/>
+                    <apex:inputField value="{!opp.useing__c}" id="useing"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡" for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.ExpectedOrderDate__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡" for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.ExpectedDeliveryDate__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem rendered="{!IF(isIEDealer == true, false, true)}">
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮" for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.LeadSource}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem rendered="{!IF(isIEDealer == true, true, false)}">
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮锛圛E鐢級" for="opp_LeadSourceIE"/>
+                    <apex:inputField value="{!opp.CustomerSourceIE__c}" id="opp_LeadSourceIE" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤" for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.TradeType__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�" for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.SalesChannel__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+                
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', false, true)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName"/>
+                    </apex:pageBlockSectionItem>
+                
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', true, false)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName" required="true"/>
+                    </apex:pageBlockSectionItem>
+              
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="涓棿鍟嗗悕" for="opp_SubDealer"/>
+                    <apex:inputField value="{!opp.SubDealer__c}" id="opp_SubDealer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗘湇鍔℃媴褰撹�呭悕" for="opp_DealerService"/>
+                    <apex:inputField value="{!opp.DealerService__c}" id="opp_DealerService"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+             <apex:pageBlockSection title="璺ㄥ尯鍩熼攢鍞�" columns="2">
+            
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍚堜綔鍖哄煙璐熻矗浜�" for="HeadOfCooperationArea__c"/>
+                    <apex:inputField value="{!opp.HeadOfCooperationArea__c}" id="HeadOfCooperationArea__c"/>
+                </apex:pageBlockSectionItem>
+
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1" for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1" for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2" for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2" for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode2__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3" for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3" for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode3__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4" for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4" for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode4__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5" for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5" for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode5__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6" for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6" for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode6__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7" for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7" for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode7__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8" for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8" for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode8__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+            <apex:outputPanel rendered="{!IF(ProductSegment == 'IE' || ProductSegment == 'BS', true, false)}">
+                 <apex:pageBlockSection title="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳" columns="2">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳?" for="Have_Computer"/>
+                        <apex:inputField value="{!opp.Have_Computer__c}" id="Have_Computer"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鍏宠仈璇环" for="Association_Opportunity"/>
+                        <apex:inputField value="{!opp.Association_Opportunity__c}" id="Association_Opportunity"/>
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+            </apex:outputPanel>
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+</apex:outputPanel>
+<apex:outputPanel layout="none" rendered="{!IF(isDealerPage == true, true, false)}">
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦." for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.Budget_Amount_D__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢." for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts_D__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦." for="opp_Amount"/>
+                    <apex:inputField value="{!opp.AmountD__c}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡." for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.Expected_Order_Date_D__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡." for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.Expected_delivery_date_D__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮." for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.LeadSource_D__c}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤." for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.Trade_Type_D__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�." for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.Sales_Channel_D__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+                <!-- <apex:outputPanel layout="none" rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', false, true)}"> -->
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', false, true)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕." for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.Dealer_Sales_Staff_Name_D__c}" id="opp_DealerSalesStaffName"/>
+                    </apex:pageBlockSectionItem>
+                <!-- </apex:outputPanel> -->
+                <!-- <apex:outputPanel rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', true, false)}" layout="inline"> -->
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', true, false)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕." for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.Dealer_Sales_Staff_Name_D__c}" id="opp_DealerSalesStaffName" required="true"/>
+                    </apex:pageBlockSectionItem>
+               <!--  </apex:outputPanel> -->
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="涓棿鍟嗗悕." for="opp_SubDealer"/>
+                    <apex:inputField value="{!opp.Sub_Dealer_D__c}" id="opp_SubDealer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗘湇鍔℃媴褰撹�呭悕." for="opp_DealerService"/>
+                    <apex:inputField value="{!opp.Dealer_Service_D__c}" id="opp_DealerService"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1." for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product_D__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1." for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code_D__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2." for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2_D__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2." for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code2_D__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3." for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3_D__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3." for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code3_D__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4." for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4_D__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4." for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code4_D__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5." for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5_D__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5." for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code5_D__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6." for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6_D__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6." for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code6_D__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7." for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7_D__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7." for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code7_D__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8." for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8_D__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8." for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code8_D__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+             <apex:outputPanel rendered="{!IF(ProductSegment == 'IE' || ProductSegment == 'BS', true, false)}">
+             <apex:pageBlockSection title="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳?" for="Have_Computer"/>
+                    <apex:inputField value="{!opp.Have_Computer__c}" id="Have_Computer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏宠仈璇环" for="Association_Opportunity"/>
+                    <apex:inputField value="{!opp.Association_Opportunity__c}" id="Association_Opportunity"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+            </apex:outputPanel>
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+</apex:outputPanel>
+        </apex:pageBlock>
+    </apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewCrossRegionalSalesOpportunity.page-meta.xml b/scr/pages/NewCrossRegionalSalesOpportunity.page-meta.xml
new file mode 100644
index 0000000..d712eb7
--- /dev/null
+++ b/scr/pages/NewCrossRegionalSalesOpportunity.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewCrossRegionalSalesOpportunity</label>
+</ApexPage>
diff --git a/scr/pages/NewDiagnosisPart.page b/scr/pages/NewDiagnosisPart.page
new file mode 100644
index 0000000..066a540
--- /dev/null
+++ b/scr/pages/NewDiagnosisPart.page
@@ -0,0 +1,145 @@
+<apex:page standardController="Diagnosis_Part__c" id="Page" extensions="NewDiagnosisPartController" action="{!init}" sidebar="false" showHeader="false">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.NewQuoteEntryJS)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script>
+        function returnSWOPage(){
+            var pageClose = j$(escapeVfId("pageClose")).value();
+            if (pageClose == 'true') {
+                var diagnosisPartId = j$(escapeVfId("diagnosisPartId")).value();
+                var swoId = j$(escapeVfId("swoId")).value();
+                window.opener.repairReturnJS(diagnosisPartId,swoId); 
+                window.close();   
+            }
+            
+        }
+
+        function saveJS(){
+            blockme();
+            save();
+        }
+
+        function closePage(){
+            window.close();
+        }
+
+        function deleteJS(){
+            if(confirm('鏄惁鍒犻櫎?')==true){
+                blockme();
+                deleteAction();
+            }
+        }
+
+    </script>
+    <style type="text/css">
+        .pbSubheader {
+            background: #BFB19C!important;
+            background-color: #DFE6F0!important;
+            font-weight:bold;
+
+        }
+    </style>
+    <apex:form id="formInfo">
+        <apex:actionFunction name="save" action="{!save}" oncomplete="returnSWOPage();unblockUI();" reRender="formInfo,message"/>
+        <apex:actionFunction name="deleteAction" action="{!deleteAction}"/>
+        <input type="hidden" id="diagnosisPartId" value="{!diagnosisPartId}" />
+        <input type="hidden" id="swoId" value="{!diagnosisPart.SWO__c}" />
+        <input type="hidden" id="pageClose" value="{!pageClose}" />
+        <apex:pageBlock id="RepairPartInfo" title="DiagnosisPart">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton onclick="saveJS()" value="Save" oncomplete="returnSWOPage();unblockUI();" reRender="formInfo" style="width: 80px;">
+                    
+                </apex:commandButton>
+
+                <apex:commandButton onclick="closePage()" value="Cancel" style="width: 80px;">
+                    
+                </apex:commandButton>
+                <apex:commandButton onclick="deleteJS();" oncomplete="returnSWOPage();" reRender="formInfo" value="Delete" style="width: 80px;">
+                    
+                </apex:commandButton>
+            </apex:pageBlockButtons>
+            <apex:outputPanel id="message">
+
+                <apex:pagemessages />
+            </apex:outputPanel>
+            <apex:pageBlockSection title="DiagnosisPart淇℃伅" columns="2">
+                    <apex:pageBlockSectionItem >
+                       
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.SWO__c.label}" for="SWO_ID"/>
+                        <apex:outputField value="{!diagnosisPart.SWO__c}" id="SWO_ID" />
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.Product__c.label}" for="ITEM"/>
+                        <apex:inputField value="{!diagnosisPart.Product__c}" id="ITEM" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                   <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.PRODUCT_CODE__c.label}" for="PRODUCT_CODE"/>
+                        <apex:inputField value="{!diagnosisPart.PRODUCT_CODE__c}" id="PRODUCT_CODE" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.PRODUCT_PART_NUMBER__c.label}" for="PRODUCT_PART_NUMBER"/>
+                        <apex:inputField value="{!diagnosisPart.PRODUCT_PART_NUMBER__c}" id="PRODUCT_PART_NUMBER" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.PRODUCT_DESCRIPTION__c.label}" for="PRODUCT_DESCRIPTION"/>
+                        <apex:inputField value="{!diagnosisPart.PRODUCT_DESCRIPTION__c}" id="PRODUCT_DESCRIPTION" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.QUANTITY__c.label}" for="QUANTITY"/>
+                    <apex:inputField value="{!diagnosisPart.QUANTITY__c}" id="QUANTITY" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.INST_SERIAL__c.label}" for="INST_SERIAL"/>
+                        <apex:inputField value="{!diagnosisPart.INST_SERIAL__c}" id="INST_SERIAL"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.STATUS__c.label}" for="STATUS"/>
+                        <apex:inputField value="{!diagnosisPart.STATUS__c}" id="STATUS"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.HOLD_REASON__c.label}" for="HOLD_REASON"/>
+                        <apex:inputField value="{!diagnosisPart.HOLD_REASON__c}" id="HOLD_REASON"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.REMARK__c.label}" for="REMARK"/>
+                        <apex:inputField value="{!diagnosisPart.REMARK__c}" id="REMARK"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.DELIVERED__c.label}" for="DELIVERED"/>
+                        <apex:inputField value="{!diagnosisPart.DELIVERED__c}" id="DELIVERED"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.RETURNED__c.label}" for="RETURNED"/>
+                        <apex:inputField value="{!diagnosisPart.RETURNED__c}" id="RETURNED"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.DeliveredDate__c.label}" for="RETURNED"/>
+                        <apex:inputField value="{!diagnosisPart.DeliveredDate__c}" id="DeliveredDate"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.Diagnosis_Part__c.fields.RETURN_DATE__c.label}" for="RETURN_DATE"/>
+                        <apex:inputField value="{!diagnosisPart.RETURN_DATE__c}" id="RETURN_DATE"/>
+                    </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+        </apex:pageBlock>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewDiagnosisPart.page-meta.xml b/scr/pages/NewDiagnosisPart.page-meta.xml
new file mode 100644
index 0000000..3a8c0a0
--- /dev/null
+++ b/scr/pages/NewDiagnosisPart.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewDiagnosisPart</label>
+</ApexPage>
diff --git a/scr/pages/NewHighProductsOpp.page b/scr/pages/NewHighProductsOpp.page
new file mode 100644
index 0000000..a275d18
--- /dev/null
+++ b/scr/pages/NewHighProductsOpp.page
@@ -0,0 +1,224 @@
+<apex:page id="Page" Controller="NewHighProductsOppController" sidebar="true" showHeader="true" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+    function saveJs() {
+        blockme();
+        saveBtn();
+    }
+
+    function saveYesJs() {
+        blockme();
+        saveBtnYes();
+    }
+
+    function saveNoJs() {
+        blockme();
+        saveBtnNo();
+    }
+
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+        var rtUrl = '{!rtUrl}';
+        if (rtUrl == 'null' || rtUrl == '') {
+            rtUrl = '{!conId}';
+        }
+        window.location.href = baseUrl + "/" + rtUrl;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnYes}" name="saveBtnYes" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnNo}" name="saveBtnNo" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+
+        <input type="hidden" id="hasError" value="{!hasError}"/>
+        <input type="hidden" id="isDealerPage" value="{!isDealerPage}"/>
+
+        <apex:pageBlock id="idSearchSetProduct" title="鏂板缓璇环" tabStyle="Opportunity">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="saveYesJs();" value="鏄�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+                <apex:commandButton style="width:50px" onclick="saveNoJs();" value="鍚�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+            </apex:pageBlockButtons>
+
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦" for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.BudgetAmount__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢" for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦" for="opp_Amount"/>
+                    <apex:inputField value="{!opp.Amount}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡" for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.ExpectedOrderDate__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡" for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.ExpectedDeliveryDate__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮" for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.LeadSource}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤" for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.TradeType__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="System" for="OppSystem__c"/>
+                    <apex:inputField value="{!opp.SystemNew__c}" id="OppSystem__c" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�" for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.SalesChannel__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+                
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName"/>
+                    </apex:pageBlockSectionItem>
+                
+          
+              
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="涓棿鍟嗗悕" for="opp_SubDealer"/>
+                    <apex:inputField value="{!opp.SubDealer__c}" id="opp_SubDealer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗘湇鍔℃媴褰撹�呭悕" for="opp_DealerService"/>
+                    <apex:inputField value="{!opp.DealerService__c}" id="opp_DealerService"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+     
+
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1" for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1" for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2" for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2" for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode2__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3" for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3" for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode3__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4" for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4" for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode4__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5" for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5" for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode5__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6" for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6" for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode6__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7" for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7" for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode7__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8" for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8" for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode8__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+        </apex:pageBlock>
+    </apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewHighProductsOpp.page-meta.xml b/scr/pages/NewHighProductsOpp.page-meta.xml
new file mode 100644
index 0000000..be8be68
--- /dev/null
+++ b/scr/pages/NewHighProductsOpp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>46.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewHighProductsOpp</label>
+</ApexPage>
diff --git a/scr/pages/NewLoanerApplication.page b/scr/pages/NewLoanerApplication.page
new file mode 100644
index 0000000..c8da600
--- /dev/null
+++ b/scr/pages/NewLoanerApplication.page
@@ -0,0 +1,386 @@
+<apex:page id="page" controller="NewLoanerApplicationController" showHeader="true" sidebar="true" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+    function saveJs() {
+        blockme();
+        saveBtn();
+    }
+
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+        var rtUrl = '{!contactID}';
+        if (rtUrl == 'null' || rtUrl == '') {
+            rtUrl = '{!accountID}';
+        }
+        window.location.href = baseUrl + "/" + rtUrl;
+    }
+    </script>
+
+    <apex:form id="mainfrom">
+        
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!cancelBtn}" name="cancelBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+        
+         <apex:pageBlock id="idSearchSetProduct" title="鏂板�熸牱鏈哄�熷嚭鐢宠" >
+            <apex:pageBlockButtons >
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy"/>
+            </apex:pageBlockButtons>
+           
+            <apex:outputPanel layout="none" >
+                <apex:pageBlockSection title="鏍锋満鍊熷嚭鐢宠璇︾粏淇℃伅" columns="2">
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏍锋満鍊熷嚭鐢宠鍚嶇О" for="la_Name"/>
+                        <apex:inputField value="{!la.Name}" id="la_Name" required="true"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏍锋満鍒嗙被" for="la_Type"/>
+                        <apex:inputField value="{!la.Equipment_Type__c}" id="la_Type" required="true"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鍊熺敤鎷呭綋" for="Loaner_Ser__c"/>
+                        <apex:inputField value="{!la.Loaner_Ser__c}" id="Loaner_Ser__c" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                        <apex:pageBlockSectionItem rendered="{!IF(userType == 'Standard', false , true)}">
+                            <apex:outputLabel value="瀹℃壒浜�" for="Approver__c"/>
+                            <apex:inputField value="{!la.Approver__c}" id="Approver__c" required="true"/>
+                        </apex:pageBlockSectionItem>
+                  
+                </apex:pageBlockSection>
+
+                <apex:pageBlockSection title="鍊熺敤鏍锋満鐩殑." columns="2" rendered="{!IF(typeName == 'NDT' || typeName == 'ANI', true , false)}">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浣跨敤鐩殑" for="Demo_purpose__c"/>
+                        <apex:inputField value="{!la.Demo_purpose__c}" id="Demo_purpose__c" required="true"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鐢宠鐞嗙敱" for="Demo_purpose_text__c"/>
+                        <apex:inputField value="{!la.Demo_purpose_text__c}" id="Demo_purpose_text__c" required="true" style="width: 350px"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+
+                <apex:pageBlockSection title="鍊熺敤鏍锋満鐩殑." columns="2" rendered="{!IF( typeName == 'BS', true , false)}">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浣跨敤鐩殑" for="Demo_purpose__c"/>
+                        <apex:inputField value="{!la.Demo_purpose__c}" id="Demo_purpose__c" required="true"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="璺熻繘璇环" for="Follow_Opp__c" rendered="{!IF(userType == 'Standard', false , true)}"/>
+                        <apex:inputField value="{!la.Follow_Opp__c}" id="Follow_Opp__c" rendered="{!IF(userType == 'Standard', false , true)}"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鐢宠鐞嗙敱" for="Demo_purpose_text__c"/>
+                        <apex:inputField value="{!la.Demo_purpose_text__c}" id="Demo_purpose_text__c" required="true" style="width: 350px"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+                
+                <apex:pageBlockSection title="鍊熺敤鏍锋満鐩殑." columns="2" rendered="{!IF(typeName == 'NDT' || typeName == 'ANI' || typeName == 'BS', false , true)}">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浣跨敤鐩殑" for="Demo_purpose__c"/>
+                        <apex:inputField value="{!la.Demo_purpose__c}" id="Demo_purpose__c" required="true"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鐢宠鐞嗙敱" for="Demo_purpose_text__c"/>
+                        <apex:inputField value="{!la.Demo_purpose_text__c}" id="Demo_purpose_text__c" required="true" style="width: 350px"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+
+               
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧1" for="ProductNameNum1__c"/>
+                        <apex:inputField value="{!la.ProductNameNum1__c}" id="ProductNameNum1__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount1__c"/>
+                        <apex:inputField value="{!la.ProductCount1__c}" id="ProductCount1__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧2" for="ProductNameNum2__c"/>
+                        <apex:inputField value="{!la.ProductNameNum2__c}" id="ProductNameNum2__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount2__c"/>
+                        <apex:inputField value="{!la.ProductCount2__c}" id="ProductCount2__c"/>
+                    </apex:pageBlockSectionItem>  
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧3" for="ProductNameNum3__c"/>
+                        <apex:inputField value="{!la.ProductNameNum3__c}" id="ProductNameNum3__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount3__c"/>
+                        <apex:inputField value="{!la.ProductCount3__c}" id="ProductCount3__c"/>
+                    </apex:pageBlockSectionItem>  
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧4" for="ProductNameNum4__c"/>
+                        <apex:inputField value="{!la.ProductNameNum4__c}" id="ProductNameNum4__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount4__c"/>
+                        <apex:inputField value="{!la.ProductCount4__c}" id="ProductCount4__c"/>
+                    </apex:pageBlockSectionItem>  
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧5" for="ProductNameNum5__c"/>
+                        <apex:inputField value="{!la.ProductNameNum5__c}" id="ProductNameNum5__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount5__c"/>
+                        <apex:inputField value="{!la.ProductCount5__c}" id="ProductCount5__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧6" for="ProductNameNum6__c"/>
+                        <apex:inputField value="{!la.ProductNameNum6__c}" id="ProductNameNum6__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount6__c"/>
+                        <apex:inputField value="{!la.ProductCount6__c}" id="ProductCount6__c"/>
+                    </apex:pageBlockSectionItem>  
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧7" for="ProductNameNum7__c"/>
+                        <apex:inputField value="{!la.ProductNameNum7__c}" id="ProductNameNum7__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount7__c"/>
+                        <apex:inputField value="{!la.ProductCount7__c}" id="ProductCount7__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧8" for="ProductNameNum8__c"/>
+                        <apex:inputField value="{!la.ProductNameNum8__c}" id="ProductNameNum8__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount8__c"/>
+                        <apex:inputField value="{!la.ProductCount8__c}" id="ProductCount8__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧9" for="ProductNameNum9__c"/>
+                        <apex:inputField value="{!la.ProductNameNum9__c}" id="ProductNameNum9__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount9__c"/>
+                        <apex:inputField value="{!la.ProductCount9__c}" id="ProductCount9__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧10" for="ProductNameNum10__c"/>
+                        <apex:inputField value="{!la.ProductNameNum10__c}" id="ProductNameNum10__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount10__c"/>
+                        <apex:inputField value="{!la.ProductCount10__c}" id="ProductCount10__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧11" for="ProductNameNum11__c"/>
+                        <apex:inputField value="{!la.ProductNameNum11__c}" id="ProductNameNum11__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount11__c"/>
+                        <apex:inputField value="{!la.ProductCount11__c}" id="ProductCount11__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧12" for="ProductNameNum12__c"/>
+                        <apex:inputField value="{!la.ProductNameNum12__c}" id="ProductNameNum12__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount12__c"/>
+                        <apex:inputField value="{!la.ProductCount12__c}" id="ProductCount12__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧13" for="ProductNameNum13__c"/>
+                        <apex:inputField value="{!la.ProductNameNum13__c}" id="ProductNameNum13__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount13__c"/>
+                        <apex:inputField value="{!la.ProductCount13__c}" id="ProductCount13__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧14" for="ProductNameNum14__c"/>
+                        <apex:inputField value="{!la.ProductNameNum14__c}" id="ProductNameNum14__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount14__c"/>
+                        <apex:inputField value="{!la.ProductCount14__c}" id="ProductCount14__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧15" for="ProductNameNum15__c"/>
+                        <apex:inputField value="{!la.ProductNameNum15__c}" id="ProductNameNum15__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount15__c"/>
+                        <apex:inputField value="{!la.ProductCount15__c}" id="ProductCount15__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧16" for="ProductNameNum16__c"/>
+                        <apex:inputField value="{!la.ProductNameNum16__c}" id="ProductNameNum16__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount16__c"/>
+                        <apex:inputField value="{!la.ProductCount16__c}" id="ProductCount16__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧17" for="ProductNameNum17__c"/>
+                        <apex:inputField value="{!la.ProductNameNum17__c}" id="ProductNameNum17__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount17__c"/>
+                        <apex:inputField value="{!la.ProductCount17__c}" id="ProductCount17__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧18" for="ProductNameNum18__c"/>
+                        <apex:inputField value="{!la.ProductNameNum18__c}" id="ProductNameNum18__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount18__c"/>
+                        <apex:inputField value="{!la.ProductCount18__c}" id="ProductCount18__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧19" for="ProductNameNum19__c"/>
+                        <apex:inputField value="{!la.ProductNameNum19__c}" id="ProductNameNum19__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount19__c"/>
+                        <apex:inputField value="{!la.ProductCount19__c}" id="ProductCount19__c"/>
+                    </apex:pageBlockSectionItem> 
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="浜у搧20" for="ProductNameNum20__c"/>
+                        <apex:inputField value="{!la.ProductNameNum20__c}" id="ProductNameNum20__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏁伴噺" for="ProductCount20__c"/>
+                        <apex:inputField value="{!la.ProductCount20__c}" id="ProductCount20__c"/>
+                    </apex:pageBlockSectionItem> 
+                </apex:pageBlockSection>
+
+                <!-- <apex:pageBlockSection title="楂樼浜у搧" columns="2">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="OSIS(娲荤粏鑳�/TIRFM)/DP/Q-Imaging/ Andor/Hama" for="BS_OSIS__c"/>
+                        <apex:inputField value="{!la.BS_OSIS__c}" id="BS_OSIS__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="VS120" for="BS_VS120__c"/>
+                        <apex:inputField value="{!la.BS_VS120__c}" id="BS_VS120__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>  
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="FV/Bitplane/NewPort/Scientifica鈥︹��" for="BS_FV__c"/>
+                        <apex:inputField value="{!la.BS_FV__c}" id="BS_FV__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="scanR" for="BS_scanR__c"/>
+                        <apex:inputField value="{!la.BS_scanR__c}" id="BS_scanR__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="Spinsr" for="BS_Spinsr__c"/>
+                        <apex:inputField value="{!la.BS_Spinsr__c}" id="BS_Spinsr__c"/>
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection> -->
+
+                <apex:pageBlockSection title="鏍锋満甯屾湜鍊熷嚭鏈熼檺" columns="2">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="甯屾湜鍒拌揣鏃ユ湡" for="Request_shipping_Date__c"/>
+                        <apex:inputField value="{!la.Request_shipping_Date__c}" id="Request_shipping_Date__c" required="true"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="甯屾湜褰掕繕鏃�(鐢宠鑰�)" for="Request_return_Date__c"/>
+                        <apex:inputField value="{!la.Request_return_Date__c}" id="Request_return_Date__c" required="true"/>
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+
+                <apex:pageBlockSection title="鏀朵欢浜轰俊鎭�" columns="2">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏀朵欢浜哄鍚�" for="Loaner_receive_staff__c"/>
+                        <apex:inputField value="{!la.Loaner_receive_staff__c}" id="Loaner_receive_staff__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                         <apex:outputLabel value="鑷彁鏃堕棿" for="pickup_time__c"/>
+                        <apex:inputField value="{!la.pickup_time__c}" id="pickup_time__c"/>
+                    </apex:pageBlockSectionItem>  
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏀朵欢浜鸿缁嗗湴鍧�" for="direct_shippment_address__c"/>
+                        <apex:inputField value="{!la.direct_shippment_address__c}" id="direct_shippment_address__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏀朵欢浜虹數璇�" for="Loaner_receive_staff_phone__c"/>
+                        <apex:inputField value="{!la.Loaner_receive_staff_phone__c}" id="Loaner_receive_staff_phone__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        &nbsp;
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="閭紪" for="Post_Code__c"/>
+                        <apex:inputField value="{!la.Post_Code__c}" id="Post_Code__c"/>
+                    </apex:pageBlockSectionItem>                    
+                </apex:pageBlockSection>
+
+                <apex:pageBlockSection title="澶囨敞" >
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="澶囨敞" for="loaner_Remark__c"/>
+                        <apex:inputField value="{!la.loaner_Remark__c}" id="loaner_Remark__c" style="width: 700px;"/>
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+
+                <apex:pageBlockSection title="杞�熺敵璇�" columns="2" rendered="{!IF(typeName == 'BS', false , true)}">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏄惁杞�熺敵璇�" for="Loaner_LendOrder__c"/>
+                        <apex:inputField value="{!la.Loaner_LendOrder__c}" id="Loaner_LendOrder__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鍏冧唬鐞嗗晢鍚嶇О(鏂囨湰)" for="Dealer_From_txt__c"/>
+                        <apex:inputField value="{!la.Dealer_From_txt__c}" id="Dealer_From_txt__c"/>
+                    </apex:pageBlockSectionItem>  
+                </apex:pageBlockSection>
+
+                <apex:pageBlockSection title="杞�熺敵璇�" columns="2" rendered="{!IF(typeName == 'BS', true , false)}">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏄惁杞�熺敵璇�" for="Loaner_LendOrder__c"/>
+                        <apex:inputField value="{!la.Loaner_LendOrder__c}" id="Loaner_LendOrder__c"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鍏冧唬鐞嗗晢鍚嶇О(鏂囨湰)" for="DealerOrder_From__c"/>
+                        <apex:inputField value="{!la.DealerOrder_From__c}" id="DealerOrder_From__c"/>
+                    </apex:pageBlockSectionItem>  
+                </apex:pageBlockSection>
+
+                
+
+
+            </apex:outputPanel>
+        </apex:pageBlock>
+
+
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewLoanerApplication.page-meta.xml b/scr/pages/NewLoanerApplication.page-meta.xml
new file mode 100644
index 0000000..397a330
--- /dev/null
+++ b/scr/pages/NewLoanerApplication.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewLoanerApplication</label>
+</ApexPage>
diff --git a/scr/pages/NewLoanerUser.page b/scr/pages/NewLoanerUser.page
new file mode 100644
index 0000000..66989ea
--- /dev/null
+++ b/scr/pages/NewLoanerUser.page
@@ -0,0 +1,70 @@
+<apex:page standardController="loaner_user__c" extensions="NewLoanerUserController" showHeader="true" sidebar="false" action="{!init}" title="鏂板缓鏍锋満鍊熺敤瀹㈡埛">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+
+function saveJs() {
+	if(confirm('鑱旂郴浜哄拰瀹㈡埛涓哄繀濉俊鎭�,濡傛灉涓虹┖灏嗕笉淇濆瓨姝ゆ潯璁板綍,鏄惁宸茬‘璁ゆ墍鏈夐渶瑕佷繚瀛樼殑淇℃伅璇ュ瓧娈甸兘涓嶄负绌�?')){
+		blockme();
+		updateUser();
+	}
+}
+</script>
+
+
+
+<style type="text/css">
+	.dateFormat{
+		display: none;
+	}
+</style>
+
+	<apex:form id="allForm">
+		 <apex:actionFunction name="updateUser" action="{!updateUser}" rerender="allForm,message,allPanel" onComplete="unblockUI();"></apex:actionFunction>
+		 <apex:outputPanel id="message">
+            <apex:messages />
+        </apex:outputPanel>
+
+         <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <table style="width: 100%;">
+                	<tr>
+                		<th style="text-align: left;font-size: 20px;">
+                			鏂板缓鏍锋満鍊熺敤瀹㈡埛
+                		</th>
+                		<th style="text-align: right;">
+                    		<apex:commandButton action="{!cancelBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                    		<apex:commandButton onclick="saveJs();" value="纭" rerender="allForm" style="width: 70px;"/>
+                    	</th>
+                	</tr>
+                </table>
+                	<div style="overflow: scroll;height: 300px;width: 1260px; ">
+               		<apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+    					        <div style="width: 1260px;">
+                        {!$ObjectType.loaner_user__c.fields.Customer__c.label}:
+                        <apex:inputField value="{!line.Customer__c}" />
+                   			{!$ObjectType.loaner_user__c.fields.Contact__c.label}:
+                   			<apex:inputField value="{!line.Contact__c}" />
+                   			{!$ObjectType.loaner_user__c.fields.FromThePeriod__c.label}:
+                   			<apex:inputField value="{!line.FromThePeriod__c}"/>
+                   			{!$ObjectType.loaner_user__c.fields.EndThePeriod__c.label}:
+                   			<apex:inputField value="{!line.EndThePeriod__c}"/>
+                        {!$ObjectType.loaner_user__c.fields.Follow_UP_Opp__c.label}:
+                        <apex:inputField value="{!line.Follow_UP_Opp__c}"/>
+                   			{!$ObjectType.loaner_user__c.fields.Remarks__c.label}:
+                   			<apex:inputField value="{!line.Remarks__c}"/>
+                        
+               				<apex:variable value="{!cnt + 1}" var="cnt" />
+               			</div>
+                    </apex:repeat>
+                </div>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+
+	</apex:form>
+
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewLoanerUser.page-meta.xml b/scr/pages/NewLoanerUser.page-meta.xml
new file mode 100644
index 0000000..d3a529f
--- /dev/null
+++ b/scr/pages/NewLoanerUser.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewLoanerUser</label>
+</ApexPage>
diff --git a/scr/pages/NewOpportunity.page b/scr/pages/NewOpportunity.page
new file mode 100644
index 0000000..a31dc35
--- /dev/null
+++ b/scr/pages/NewOpportunity.page
@@ -0,0 +1,428 @@
+<apex:page id="Page" Controller="NewOpportunityController" sidebar="true" showHeader="true" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+    function saveJs() {
+        blockme();
+        saveBtn();
+    }
+
+    function saveYesJs() {
+        blockme();
+        saveBtnYes();
+    }
+
+    function saveNoJs() {
+        blockme();
+        saveBtnNo();
+    }
+
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+        var rtUrl = '{!rtUrl}';
+        if (rtUrl == 'null' || rtUrl == '') {
+            rtUrl = '{!conId}';
+        }
+        window.location.href = baseUrl + "/" + rtUrl;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnYes}" name="saveBtnYes" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnNo}" name="saveBtnNo" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+
+        <input type="hidden" id="hasError" value="{!hasError}"/>
+        <input type="hidden" id="isDealerPage" value="{!isDealerPage}"/>
+
+        <apex:pageBlock id="idSearchSetProduct" title="鏂板缓璇环" tabStyle="Opportunity">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="saveYesJs();" value="鏄�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+                <apex:commandButton style="width:50px" onclick="saveNoJs();" value="鍚�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+            </apex:pageBlockButtons>
+<apex:outputPanel layout="none" rendered="{!IF(isDealerPage == true, false, true)}">
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦" for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.BudgetAmount__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢" for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦" for="opp_Amount"/>
+                    <apex:inputField value="{!opp.Amount}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+            <!--NO.6 gwy 2021-06-03-->
+                <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'IE', true, false)}">
+                    <apex:outputLabel value="COMPO璇环" for="compo_opp"/>
+                    <apex:inputField value="{!opp.compo_opp__c}" id="compo_opp"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'BS', true, false)}">
+                    <apex:outputLabel value="鐢ㄩ��" for="useing"/>
+                    <apex:inputField value="{!opp.useing__c}" id="useing"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡" for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.ExpectedOrderDate__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡" for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.ExpectedDeliveryDate__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem rendered="{!IF(isIEDealer == true, false, true)}">
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮" for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.LeadSource}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem rendered="{!IF(isIEDealer == true, true, false)}">
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮锛圛E鐢級" for="opp_LeadSourceIE"/>
+                    <apex:inputField value="{!opp.CustomerSourceIE__c}" id="opp_LeadSourceIE" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤" for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.TradeType__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�" for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.SalesChannel__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+                
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', false, true)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName"/>
+                    </apex:pageBlockSectionItem>
+                
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', true, false)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName" required="true"/>
+                    </apex:pageBlockSectionItem>
+              
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="涓棿鍟嗗悕" for="opp_SubDealer"/>
+                    <apex:inputField value="{!opp.SubDealer__c}" id="opp_SubDealer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗘湇鍔℃媴褰撹�呭悕" for="opp_DealerService"/>
+                    <apex:inputField value="{!opp.DealerService__c}" id="opp_DealerService"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1" for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1" for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2" for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2" for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode2__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3" for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3" for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode3__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4" for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4" for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode4__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5" for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5" for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode5__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6" for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6" for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode6__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7" for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7" for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode7__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8" for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8" for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.CompetitorProductCode8__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+            <apex:outputPanel rendered="{!IF(ProductSegment == 'IE' || ProductSegment == 'BS', true, false)}">
+                 <apex:pageBlockSection title="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳" columns="2">
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳?" for="Have_Computer"/>
+                        <apex:inputField value="{!opp.Have_Computer__c}" id="Have_Computer"/>
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="鍏宠仈璇环" for="Association_Opportunity"/>
+                        <apex:inputField value="{!opp.Association_Opportunity__c}" id="Association_Opportunity"/>
+                    </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+            </apex:outputPanel>
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+</apex:outputPanel>
+<apex:outputPanel layout="none" rendered="{!IF(isDealerPage == true, true, false)}">
+            <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勭畻閲戦." for="opp_BudgetAmount"/>
+                    <apex:inputField value="{!opp.Budget_Amount_D__c}" id="opp_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢." for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts_D__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦." for="opp_Amount"/>
+                    <apex:inputField value="{!opp.AmountD__c}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="opp_DealerSelectOwner"/>
+                    <apex:inputField value="{!opp.DealerSelectOwner__c}" id="opp_DealerSelectOwner" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁撴灉淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="棰勫畾涓嬪崟鏃ユ湡." for="opp_ExpectedOrderDate"/>
+                    <apex:inputField value="{!opp.Expected_Order_Date_D__c}" id="opp_ExpectedOrderDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯屾湜鍑鸿揣鏃ユ湡." for="opp_ExpectedDeliveryDate"/>
+                    <apex:inputField value="{!opp.Expected_delivery_date_D__c}" id="opp_ExpectedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="娼滃湪瀹㈡埛鏉ユ簮." for="opp_LeadSource"/>
+                    <apex:inputField value="{!opp.LeadSource_D__c}" id="opp_LeadSource" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤." for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.Trade_Type_D__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�." for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.Sales_Channel_D__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+                <!-- <apex:outputPanel layout="none" rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', false, true)}"> -->
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', false, true)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕." for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.Dealer_Sales_Staff_Name_D__c}" id="opp_DealerSalesStaffName"/>
+                    </apex:pageBlockSectionItem>
+                <!-- </apex:outputPanel> -->
+                <!-- <apex:outputPanel rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', true, false)}" layout="inline"> -->
+                    <apex:pageBlockSectionItem rendered="{!IF(ProductSegment == 'NDT' || ProductSegment == 'ANI', true, false)}">
+                        <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕." for="opp_DealerSalesStaffName"/>
+                        <apex:inputField value="{!opp.Dealer_Sales_Staff_Name_D__c}" id="opp_DealerSalesStaffName" required="true"/>
+                    </apex:pageBlockSectionItem>
+               <!--  </apex:outputPanel> -->
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="涓棿鍟嗗悕." for="opp_SubDealer"/>
+                    <apex:inputField value="{!opp.Sub_Dealer_D__c}" id="opp_SubDealer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗘湇鍔℃媴褰撹�呭悕." for="opp_DealerService"/>
+                    <apex:inputField value="{!opp.Dealer_Service_D__c}" id="opp_DealerService"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="绔炰簤鑰呬俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧1." for="opp_CompetitorProduct"/>
+                    <apex:inputField value="{!opp.Competitor_Product_D__c}" id="opp_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿1." for="opp_CompetitorProductCode"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code_D__c}" id="opp_CompetitorProductCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧2." for="opp_CompetitorProduct2"/>
+                    <apex:inputField value="{!opp.Competitor_Product2_D__c}" id="opp_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿2." for="opp_CompetitorProductCode2"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code2_D__c}" id="opp_CompetitorProductCode2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧3." for="opp_CompetitorProduct3"/>
+                    <apex:inputField value="{!opp.Competitor_Product3_D__c}" id="opp_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿3." for="opp_CompetitorProductCode3"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code3_D__c}" id="opp_CompetitorProductCode3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧4." for="opp_CompetitorProduct4"/>
+                    <apex:inputField value="{!opp.Competitor_Product4_D__c}" id="opp_CompetitorProduct4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿4." for="opp_CompetitorProductCode4"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code4_D__c}" id="opp_CompetitorProductCode4"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧5." for="opp_CompetitorProduct5"/>
+                    <apex:inputField value="{!opp.Competitor_Product5_D__c}" id="opp_CompetitorProduct5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿5." for="opp_CompetitorProductCode5"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code5_D__c}" id="opp_CompetitorProductCode5"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧6." for="opp_CompetitorProduct6"/>
+                    <apex:inputField value="{!opp.Competitor_Product6_D__c}" id="opp_CompetitorProduct6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿6." for="opp_CompetitorProductCode6"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code6_D__c}" id="opp_CompetitorProductCode6"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧7." for="opp_CompetitorProduct7"/>
+                    <apex:inputField value="{!opp.Competitor_Product7_D__c}" id="opp_CompetitorProduct7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿7." for="opp_CompetitorProductCode7"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code7_D__c}" id="opp_CompetitorProductCode7"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧8." for="opp_CompetitorProduct8"/>
+                    <apex:inputField value="{!opp.Competitor_Product8_D__c}" id="opp_CompetitorProduct8"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绔炰簤浜у搧鍨嬪彿8." for="opp_CompetitorProductCode8"/>
+                    <apex:inputField value="{!opp.Competitor_Product_Code8_D__c}" id="opp_CompetitorProductCode8"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+             <apex:outputPanel rendered="{!IF(ProductSegment == 'IE' || ProductSegment == 'BS', true, false)}">
+             <apex:pageBlockSection title="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏈鍗曡喘涔颁骇鍝佹槸鍚﹀惈鐢佃剳?" for="Have_Computer"/>
+                    <apex:inputField value="{!opp.Have_Computer__c}" id="Have_Computer"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏宠仈璇环" for="Association_Opportunity"/>
+                    <apex:inputField value="{!opp.Association_Opportunity__c}" id="Association_Opportunity"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+            </apex:outputPanel>
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="opp_Remark"/>
+                    <apex:inputField value="{!opp.Remark__c}" id="opp_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+</apex:outputPanel>
+        </apex:pageBlock>
+    </apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewOpportunity.page-meta.xml b/scr/pages/NewOpportunity.page-meta.xml
new file mode 100644
index 0000000..d912815
--- /dev/null
+++ b/scr/pages/NewOpportunity.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewOpportunity</label>
+</ApexPage>
diff --git a/scr/pages/NewOrder.page b/scr/pages/NewOrder.page
new file mode 100644
index 0000000..a8d5bd7
--- /dev/null
+++ b/scr/pages/NewOrder.page
@@ -0,0 +1,26 @@
+<apex:page standardController="Order" extensions="NewOrderController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="鍚堝悓閰嶇疆">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <apex:form id="allForm">
+        <apex:outputPanel rendered="{!errorflg}" layout="none">
+            <table width="200px">
+                <tr>
+                    <td align="left"><div class="errorMsg">{!errorMessage}</div></td>
+                </tr>
+            </table>
+        </apex:outputPanel>
+        <apex:outputPanel id="allPanel">
+            <table class="linetable" border="0" style="border-collapse: collapse;width:200px;table-layout:fixed;">
+                <tr>
+                    <td style="width: 40%;text-align: right;">鏂囦欢鍚嶇О</td>
+                    <td style="width: 60%;text-align: left;"><apex:inputText id="fileName" value="{!fileName}" style="width:90%;"/></td>
+                </tr>
+                <tr>
+                    <td style="width: 100%;text-align: center;"><apex:commandButton action="{!csvExport}" value="閰嶇疆瀵煎嚭"/></td>
+                </tr>
+            </table>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewOrder.page-meta.xml b/scr/pages/NewOrder.page-meta.xml
new file mode 100644
index 0000000..99a7224
--- /dev/null
+++ b/scr/pages/NewOrder.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewOrder</label>
+</ApexPage>
diff --git a/scr/pages/NewQuoteDevide.page b/scr/pages/NewQuoteDevide.page
new file mode 100644
index 0000000..1795164
--- /dev/null
+++ b/scr/pages/NewQuoteDevide.page
@@ -0,0 +1,2 @@
+<apex:page standardController="Quote" extensions="NewQuoteDevideController" sidebar="false" showHeader="false" action="{!init}">
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewQuoteDevide.page-meta.xml b/scr/pages/NewQuoteDevide.page-meta.xml
new file mode 100644
index 0000000..febb47f
--- /dev/null
+++ b/scr/pages/NewQuoteDevide.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewQuoteDevide</label>
+</ApexPage>
diff --git a/scr/pages/NewQuoteEntry.page b/scr/pages/NewQuoteEntry.page
new file mode 100644
index 0000000..0d72380
--- /dev/null
+++ b/scr/pages/NewQuoteEntry.page
@@ -0,0 +1,1109 @@
+<apex:page standardController="Quote" extensions="NewQuoteEntryController" sidebar="false" action="{!init}" id="Page">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.NewQuoteEntryJS)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+    <script type="text/javascript">
+
+        var oppId = '{!oppId}';
+        var openQuoteExcelImportWindow = null;
+        var baseUrl = '{!baseUrl}';
+        
+        function searchProduct(i,str,setStr){
+            // CNY USD銈掑彇寰�
+            //j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).attr('readonly',true);
+
+            openPopup(baseUrl + '/apex/SearchProduct?lineno=' + i + '&val=' + encodeURIComponent(str) + '&set=' + encodeURIComponent(setStr) +'&oppId=' + encodeURIComponent(oppId), 'setsearch', 950, 450, 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+
+        function openQuoteExcelImport(e) {
+            if ( openQuoteExcelImportWindow == null || openQuoteExcelImportWindow.closed) {
+                openQuoteExcelImportWindow = window.open(baseUrl + '/apex/QuoteExcelImport', 'xlsdoc', 'width=450,height=210');
+            }
+            else {
+                openQuoteExcelImportWindow.focus();
+            }
+        }
+
+        function getLastLineNoNext(doc) {
+            var hasRecordFlg = false;
+            var lastLineNo = 0;
+            for(var i=99; i>=0; i--){
+                if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != ''){
+                    if (!hasRecordFlg) {
+                        lastLineNo = i;
+                    }
+                    hasRecordFlg = true;
+                }
+                if (hasRecordFlg == true) {
+                    if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() == ''){
+                        var moveCheckbox = true;
+                        //deletelist(i, doc, moveCheckbox);
+                        lastLineNo = i;
+                    }
+                }
+            }
+            if (hasRecordFlg) {
+                lastLineNo = lastLineNo + 1;
+            }
+            return lastLineNo;
+        }
+
+        function save2btn() {
+            //checkchangedAfterPrint();
+            //var changedAfterPrint = j$(escapeVfId('Page:mainForm:changedAfterPrint')).value();
+            //var changedAfterBid = j$(escapeVfId('Page:mainForm:changedAfterBid')).value();
+            var changedAfterPrint = false;
+            var changedAfterBid = false;
+
+            if (changedAfterBid == 'true') {
+                if (confirm(Confirm_ChangedAfterBid)) {
+                    blockme();
+                    Save.call();
+                    return;
+                }
+            } else if (changedAfterPrint == 'true') {
+                if (confirm(Confirm_ChangedAfterPrint)) {
+                    blockme();
+                    Save.call();
+                    return true;
+                }
+            } else {
+                blockme();
+                Save.call();
+                return true;
+            }
+        }
+
+        function doRefresh() {
+            blockme();
+            Refresh.call();
+            return true;
+
+        }
+
+        function oppReflection2btn() {
+
+            var changedAfterPrint = false;
+
+            if (changedAfterPrint == 'true') {
+                if (confirm(Confirm_ChangedAfterPrint)) {
+                    blockme();
+                    OppReflection.call();
+                    return true;
+                }
+            } else {
+                blockme();  
+                OppReflection.call();
+                return true;
+            }
+        }
+
+        function decidebtn() {
+            if (confirm('鎶ヤ环鍐冲畾鍚庯紝璇环涓嶈兘鍚屾鍏朵粬鎶ヤ环锛屾槸鍚﹀喅瀹氭姤浠凤紵') == false) {
+                return;
+            }
+            blockme();
+            Decide.call();
+            return true;
+        }
+
+        function undecidebtn() {
+            if (confirm('鏄惁鍙栨秷鍐冲畾锛�') == false) {
+                return;
+            }
+            blockme();
+            unDecide.call();
+            return true;
+        }
+
+        function backbtn() {
+            BackBtn.call();
+            return true;
+        }
+
+        function excelImportGateway(str) {
+            blockme();
+            excelImport(str);
+        }
+
+        function printPDF() {
+            var quoid = j$(escapeVfId('quoid')).value();
+            var printPrice = j$(escapeVfId('isPrintPrice')).prop('checked');
+            var baseUrl = '{!baseUrl}';
+            window.open(baseUrl + '/apex/QuotePDF?id=' + encodeURIComponent(quoid) + '&printprice=' + printPrice);
+        }
+
+        function setall() {
+            var discount = j$(escapeVfId('Page:mainForm:block:discount')).value();
+            if (isNaN(discount) == true) {
+                alert('璇疯緭鍏ユ暟瀛椼��');
+                return false;
+            }
+            var quoteEntryMaxLine = {!quoteEntryMaxLine};
+            for (var i = 0; i < quoteEntryMaxLine; i++) {
+                var SingleProduct = j$(escapeVfId("Page:mainForm:block:lists:"+i+":SingleProduct")).value();
+                if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '' && SingleProduct == 'true') {
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).val(discount);
+                }
+                setTotalPrice(i,true);
+            }
+        }
+
+        function setPrice(i) {
+            var distingush = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Distingush')).value();
+            if (distingush == 'A') {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price1')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            } else if (distingush == 'B') {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price2')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            } else if (distingush == 'C') {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price3')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            } else {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price0')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            }
+        }
+
+        function setTotalPrice(i,Discountflag) {
+            //var discount_n = j$(escapeVfId('Page:mainForm:block:discount_n')).value();
+            if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                var quantity = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).value();
+                var unitprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).value();
+                var discount = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).value();
+                var totalprice = Math.round(quantity * unitprice * (100 - discount)) / 100;
+                //var discountF = discount_n * (1 - discount / 100);
+                //var totalprice = Math.round(quantity * unitprice * discountF);
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text(totalprice);
+                //XHL-20190515-AddStart 
+                var SingleProduct = j$(escapeVfId("Page:mainForm:block:lists:"+i+":SingleProduct")).value();
+                var QuantityReference = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':QuantityReference')).value();
+                var DiscountReference = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':DiscountReference')).value();
+                
+                if (SingleProduct == 'false' && quantity != QuantityReference) {
+                    alert('濂楄浜у搧鐨勬暟閲忎笉鍙洿鏀�');
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).val(QuantityReference);
+                    var totalprice = Math.round(QuantityReference * unitprice * (100 - discount)) / 100;
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text(totalprice);
+                }
+        
+                if (SingleProduct == 'false' && discount != DiscountReference && Discountflag == false) {
+                    alert('濂楄浜у搧鐨勬姌鎵d笉鍙洿鏀�');
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).val(DiscountReference);
+                    var totalprice = Math.round(quantity * unitprice * (100 - DiscountReference)) / 100;
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text(totalprice);
+                }
+                //XHL-20190515-AddEnd 
+            }
+        }
+
+        function changeLimit(i) {
+            if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                var unitprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).value();
+                var salesprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price0')).value();
+                var ispm = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':isProductModel')).value();
+                var isPartsdirect = j$(escapeVfId('isPartsdirect')).value();
+                var isHiddenUser = j$(escapeVfId('isHiddenUser')).value();
+                var specialDealer = j$(escapeVfId('specialDealer')).value();
+                var isDealerUser = j$(escapeVfId('isDealerUser')).value();
+                var hiddenflg = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':hiddenflg')).value();
+                if (isPartsdirect == 'true' || ispm == 'true') {
+                    setTotalPrice(i,false);
+                } else {
+                    alert("涓嶈兘鎵嬪姩淇敼閿�鍞环鏍笺��");
+                    if (specialDealer == 'true' ||isHiddenUser == 'true' || isDealerUser == 'true' && hiddenflg == 'true') {
+                        j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(0);
+                    } else {
+                        j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(salesprice);
+                    }
+                }
+            }
+        }
+
+        function setCPD() {
+            var quoteEntryMaxLine = {!quoteEntryMaxLine};
+            var total = 0;
+            var cnt = 0;
+            for (var i = 0; i < quoteEntryMaxLine; i++) {
+                if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                    //var line = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text();
+                    var quantity = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).value();
+                    var unitprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price0')).value();
+                    var discount = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).value();
+                    var line = Math.round(quantity * unitprice * (100 - discount)) / 100;
+                    total += localParseFloat(line);
+                    cnt += localParseFloat(1);
+                }
+            }
+            var totalCP = j$(escapeVfId('Page:mainForm:block:totalCustomPrice')).value();
+            j$(escapeVfId('Page:mainForm:block:totalCustomPrice')).val(toNum(totalCP));
+            totalCP = localParseFloat(totalCP);
+
+            var isHiddenUser = j$(escapeVfId('isHiddenUser')).value();
+            var isDealerUser = j$(escapeVfId('isDealerUser')).value();
+            var specialDealer = j$(escapeVfId('specialDealer')).value();
+            
+            var totalCPD = 0;
+            for (var i = 0; i < cnt - 1; i++) {
+                var hiddenflg = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':hiddenflg')).value();
+                //var line = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text();
+                var quantity = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).value();
+                var unitprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price0')).value();
+                var discount = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).value();
+                var line = Math.round(quantity * unitprice * (100 - discount)) / 100;
+                line = localParseFloat(line);
+                var lineCP = line / total * totalCP;
+                lineCP = lineCP.toFixed(0);
+                totalCPD += localParseFloat(lineCP);
+                if (specialDealer == 'true' || isHiddenUser == 'true' || isDealerUser == 'true' && hiddenflg == 'true' ) {
+                    // alert('11111('+i+')11111');
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPrice')).val(toNum(0));
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPriceHidden')).val(toNum(lineCP));
+                } else {
+                    // alert('22222('+i+')22222_' + toNum(lineCP));
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPrice')).val(toNum(lineCP));
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPriceHidden')).val(toNum(lineCP));
+                }
+            }
+            var hiddenflg = j$(escapeVfId('Page:mainForm:block:lists:' + (cnt - 1) + ':hiddenflg')).value();
+            if ( specialDealer == 'true' || isHiddenUser == 'true' || isDealerUser == 'true' && hiddenflg == 'true') {
+                // alert('3333333333' +toNum(totalCP - totalCPD) );
+                j$(escapeVfId('Page:mainForm:block:lists:' + (cnt - 1) + ':CustomPrice')).val(toNum(0));
+                j$(escapeVfId('Page:mainForm:block:lists:' + (cnt - 1) + ':CustomPriceHidden')).val(toNum(totalCP - totalCPD));
+            } else {
+                // alert('4444444444' + toNum(totalCP - totalCPD));
+                j$(escapeVfId('Page:mainForm:block:lists:' + (cnt - 1) + ':CustomPrice')).val(toNum(totalCP - totalCPD));
+                j$(escapeVfId('Page:mainForm:block:lists:' + (cnt - 1) + ':CustomPriceHidden')).val(toNum(totalCP - totalCPD));
+            }
+        }
+
+        function doReroadJs(line) {
+            var pname = j$(escapeVfId('Page:mainForm:block:lists:' + line + ':ProductName')).value();
+            //XHL-20190515-AddStart
+            var ProductNameReference = j$(escapeVfId('Page:mainForm:block:lists:' + line + ':ProductNameReference')).value();
+            var SingleProduct = j$(escapeVfId("Page:mainForm:block:lists:"+line+":SingleProduct")).value();
+            var hidSet = j$(escapeVfId("Page:mainForm:block:lists:"+line+":hidSet")).value();
+            if (SingleProduct == 'false' && pname != ProductNameReference && hidSet != '') {
+                alert('濂楄浜у搧鐨勪骇鍝佸悕绉颁笉鍙洿鏀�');
+
+                j$(escapeVfId('Page:mainForm:block:lists:' + line + ':ProductName')).val(ProductNameReference);
+            }
+            //XHL-20190515-AddEnd
+            if (pname == null || pname == '') {
+                doReroad();
+            } else {
+                return;
+            }
+        }
+
+        function doReroad() {
+            var quoteEntryMaxLine = {!quoteEntryMaxLine};
+            var isHiddenAll = j$(escapeVfId('isHiddenAll')).value();
+            var tmp = "false";
+            for (var i = 0; i < quoteEntryMaxLine; i++) {
+                var pname = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value();
+                var phidden = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':hiddenflg')).value();
+                if (pname != '' && phidden == "true") {
+                    tmp = "true";
+                    break;
+                }
+            }
+            if (isHiddenAll != tmp) {
+                blockme();
+                reloadPage(tmp);
+            }
+        }
+
+        function dummy(){
+
+            dummy1();
+            document.getElementById('hid').style.visibility="hidden";
+           /* var hid = document.getElementById('hid');
+            hid.style.display = 'none';*/
+        }
+    </script>
+
+    <style type="text/css">
+        div#iframelike {
+            color: #fff;
+            height: 300px;
+            overflow: auto;
+        }
+        div#iframelikeheader {
+            color: #fff;
+            height: 23px;
+            overflow: auto;
+        }
+        input {
+            font-size: 10.5px;
+        }
+        body {
+            font-size: 10.5px;
+        }
+
+        hr {
+            height: 15px;
+            color: #fff;
+            margin: 0px;
+            padding: 0px;
+            border: 0px;
+        }
+
+    </style>
+    <apex:form id="mainForm">
+
+        <apex:actionFunction action="{!Refresh}" name="Refresh" reRender="mainForm,message1" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!excelImport}" name="excelImport" reRender="mainForm" oncomplete="unblockUI();">
+            <apex:param assignTo="{!excel_text}" name="select_index" value=""/>
+        </apex:actionFunction>
+         <apex:actionFunction action="{!dummy2}" name="dummy1" reRender="message1"/>
+
+        <apex:actionFunction action="{!Save}" name="Save" reRender="mainForm,message1" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!OppReflection}" name="OppReflection" reRender="mainForm" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!Decide}" name="Decide" reRender="mainForm" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!UnDecide}" name="unDecide" reRender="mainForm" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!BackBtn}" name="BackBtn" reRender="mainForm,message1" />
+
+        <apex:actionFunction action="{!reloadPage}" name="reloadPage" reRender="mainForm" oncomplete="unblockUI();">
+            <apex:param assignTo="{!is_hidden_all}" name="firstparam" value=""/>
+        </apex:actionFunction>
+        <apex:actionFunction action="{!setProductEntry}" name="setProductEntry" reRender="mainForm" oncomplete="unblockUI();">
+            <apex:param assignTo="{!setProduct_text}" name="setProduct_text" value=""/>
+        </apex:actionFunction>
+
+        <!-- <apex:actionFunction action="{!emptyData}" name="emptyData" reRender="mainForm" >
+            <apex:param assignTo="{!setProduct_text}" name="setProduct_text" value=""/>
+        </apex:actionFunction> -->
+        <apex:pageBlock id="block">
+
+            <apex:inputHidden value="{!pricebook2Id}" id="pricebook2Id"/>
+            <input type="hidden" value="{!quoId}" id="quoid"/>
+            <input type="hidden" value="{!is_Parts_direct}" id="isPartsdirect"/>
+            <input type="hidden" value="{!is_hidden_user}" id="isHiddenUser"/>
+            <input type="hidden" value="{!specialDealer}" id="specialDealer"/>
+            <input type="hidden" value="{!is_dealer_user}" id="isDealerUser"/>
+            <input type="hidden" value="{!is_hidden_all}" id="isHiddenAll"/>
+
+            <input type="hidden" id="activitiesSize" value="{!activitiesSize}" />
+            <input type="hidden" id="quoteLineSetNameDiscountJson" value="{!quoteLineSetNameDiscountJson}" />
+
+            <apex:outputPanel id="message1">
+                <apex:messages styleClass="editListError"/>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!errorflg}" >
+                <table width="100%">
+                    <tr>
+                        <td align="left"><div class="errorMsg">{!errorMessage}</div></td>
+                    </tr>
+                </table>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!Messageflg}" >
+                <table width="100%">
+                    <tr>
+                        <td align="left">{!Message}</td>
+                    </tr>
+                </table>
+            </apex:outputPanel>
+
+            <div>
+                <table border="0">
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.QuoteNumber.label}</th>
+                        <td style="text-align:right;width:130px;"><apex:outputLabel value="{!quo.QuoteNumber}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Name.label}</th>
+                        <td style="width:130px;"><apex:inputField value="{!quo.Name}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Account.fields.name.label}</th>
+                        <td style="text-align:right;width:130px;" colspan="2"><apex:outputLabel value="{!quo.Account.name}"/></td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+
+                    <BR></BR>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Discount_Normal__c.label}</th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:outputText style="width:90%;" id="discount_n" value="{0,number,###,###,##0.00}">
+                                    <apex:param value="{!dealer_coefficient}"/>
+                                </apex:outputText>%
+                            </apex:outputPanel>
+                        </td>
+                        <td style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Discount_Special__c.label}</td>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:outputField id="discount_s" value="{!quo.Discount_Special__c}"/>
+                            </apex:outputPanel>
+                        </td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Subtotal.label}</th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                {!quo.currencyISOCode}&nbsp;<apex:outputText value="{0,number,###,###,##0.00}"><apex:param value="{!quo.Subtotal}"/></apex:outputText>
+                            </apex:outputPanel>
+                        </td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Discount.label}</th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:outputField value="{!quo.Discount}"/>
+                            </apex:outputPanel>
+                        </td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.TotalPrice.label}</th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                {!quo.currencyISOCode}&nbsp;<apex:outputText value="{0,number,###,###,##0.00}"><apex:param value="{!quo.TotalPrice}"/></apex:outputText>
+                            </apex:outputPanel>
+                        </td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+
+                    <apex:outputPanel layout="none" rendered="{!IF(productSegment = 'IE' || productSegment = 'RVI', true, false)}">
+                    <tr>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <th style="text-align:right;width:90px;">杩愪繚璐�</th>
+                        <td style="text-align:right;width:130px;"><apex:inputField value="{!quo.ShippingHandling}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.GrandTotal.label}</th>
+                        <td style="text-align:right;width:130px;">{!quo.currencyISOCode}&nbsp;<apex:outputText value="{0,number,###,###,##0.00}"><apex:param value="{!quo.GrandTotal}"/></apex:outputText></td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+                    </apex:outputPanel>
+
+                    <BR></BR>
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.PaymentTerms__c.label}</th>
+                        <td style="text-align:left;" colspan="3"><apex:inputField value="{!quo.PaymentTerms__c}" style="width: 99%"/></td>
+                        <td style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Shipment_Term__c.label}</td>
+                        <td style="text-align:left;width:130px;"><apex:inputField value="{!quo.Shipment_Term__c}"/></td>
+                        <td style="text-align:right;width:110px;">{!$ObjectType.Quote.fields.Shipment_Term2__c.label}</td>
+                        <td style="text-align:left;width:130px;"><apex:inputField value="{!quo.Shipment_Term2__c}"/></td>
+                        <td style="text-align:left;width:50px;">AIRPORT</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.DeliveryLeadTime__c.label}</th>
+                        <td style="text-align:right;width:130px;"><apex:inputField value="{!quo.DeliveryLeadTime__c}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Warranty__c.label}</th>
+                        <td style="text-align:right;width:130px;"><apex:inputField value="{!quo.Warranty__c}"/></td> 
+                        <th style="text-align:right;width:90px;">鎶ヤ环鍒版湡鏃ユ湡</th>
+                        <td style="text-align:left;width:130px;" colspan="2"><apex:inputField value="{!quo.ExpirationDate}"/></td>              
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName1__c.label}" rendered="{!hidFlg[0]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName1__c}" rendered="{!hidFlg[0]}" id="SetName1"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty1__c.label}" rendered="{!hidFlg[0]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty1__c}" rendered="{!hidFlg[0]}" id="SetQty1"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName2__c.label}" rendered="{!hidFlg[1]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName2__c}" rendered="{!hidFlg[1]}" id="SetName2"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty2__c.label}" rendered="{!hidFlg[1]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty2__c}" rendered="{!hidFlg[1]}" id="SetQty2"/>
+                        </td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="doRefresh();return false;" value="{!$Label.Status_Update}" style="width:110px;" rerender="dummy"/></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName3__c.label}" rendered="{!hidFlg[2]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName3__c}" rendered="{!hidFlg[2]}" id="SetName3"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty3__c.label}" rendered="{!hidFlg[2]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty3__c}" rendered="{!hidFlg[2]}" id="SetQty3"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName4__c.label}" rendered="{!hidFlg[3]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName4__c}" rendered="{!hidFlg[3]}" id="SetName4"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty4__c.label}" rendered="{!hidFlg[3]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty4__c}" rendered="{!hidFlg[3]}" id="SetQty4"/>
+                        </td>
+                        <td style="text-align:right;width:50px;">&nbsp;</td>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName5__c.label}" rendered="{!hidFlg[4]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName5__c}" rendered="{!hidFlg[4]}" id="SetName5"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty5__c.label}" rendered="{!hidFlg[4]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty5__c}" rendered="{!hidFlg[4]}" id="SetQty5"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName6__c.label}" rendered="{!hidFlg[5]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName6__c}" rendered="{!hidFlg[5]}" id="SetName6"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty6__c.label}" rendered="{!hidFlg[5]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty6__c}" rendered="{!hidFlg[5]}" id="SetQty6"/>
+                        </td>
+                        <th style="text-align:right;width:50px;">鏂囦欢鍚嶏細</th>
+                        <td style="text-align:right;width:110px;"><apex:inputText value="{!fileName}" /><!-- <apex:commandButton onclick="openQuoteExcelImport(event);return false;"  value="{!$Label.Excel_Import}" style="width:110px;" rerender="dummy"/> --></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName7__c.label}" rendered="{!hidFlg[6]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName7__c}" rendered="{!hidFlg[6]}" id="SetName7"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty7__c.label}" rendered="{!hidFlg[6]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty7__c}" rendered="{!hidFlg[6]}" id="SetQty7"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName8__c.label}" rendered="{!hidFlg[7]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName8__c}" rendered="{!hidFlg[7]}" id="SetName8"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty8__c.label}" rendered="{!hidFlg[7]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty8__c}" rendered="{!hidFlg[7]}" id="SetQty8"/>
+                        </td>
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton action="{!csvExport}" value="閰嶇疆瀵煎嚭" /></td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName9__c.label}" rendered="{!hidFlg[8]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName9__c}" rendered="{!hidFlg[8]}" id="SetName9"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty9__c.label}" rendered="{!hidFlg[8]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty9__c}" rendered="{!hidFlg[8]}" id="SetQty9"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName10__c.label}" rendered="{!hidFlg[9]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName10__c}" rendered="{!hidFlg[9]}" id="SetName10"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty10__c.label}" rendered="{!hidFlg[9]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty10__c}" rendered="{!hidFlg[9]}" id="SetQty10"/>
+                        </td>
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;">&nbsp;</td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName11__c.label}" rendered="{!hidFlg[10]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName11__c}" rendered="{!hidFlg[10]}" id="SetName11"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty11__c.label}" rendered="{!hidFlg[10]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty11__c}" rendered="{!hidFlg[10]}" id="SetQty11"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName12__c.label}" rendered="{!hidFlg[11]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName12__c}" rendered="{!hidFlg[11]}" id="SetName12"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty12__c.label}" rendered="{!hidFlg[11]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty12__c}" rendered="{!hidFlg[11]}" id="SetQty12"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName13__c.label}" rendered="{!hidFlg[12]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName13__c}" rendered="{!hidFlg[12]}" id="SetName13"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty13__c.label}" rendered="{!hidFlg[12]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty13__c}" rendered="{!hidFlg[12]}" id="SetQty13"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName14__c.label}" rendered="{!hidFlg[13]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName14__c}" rendered="{!hidFlg[13]}" id="SetName14"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty14__c.label}" rendered="{!hidFlg[13]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty14__c}" rendered="{!hidFlg[13]}" id="SetQty14"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName15__c.label}" rendered="{!hidFlg[14]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName15__c}" rendered="{!hidFlg[14]}" id="SetName15"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty15__c.label}" rendered="{!hidFlg[14]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty15__c}" rendered="{!hidFlg[14]}" id="SetQty15"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName16__c.label}" rendered="{!hidFlg[15]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName16__c}" rendered="{!hidFlg[15]}" id="SetName16"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty16__c.label}" rendered="{!hidFlg[15]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty16__c}" rendered="{!hidFlg[15]}" id="SetQty16"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName17__c.label}" rendered="{!hidFlg[16]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName17__c}" rendered="{!hidFlg[16]}" id="SetName17"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty17__c.label}" rendered="{!hidFlg[16]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty17__c}" rendered="{!hidFlg[16]}" id="SetQty17"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName18__c.label}" rendered="{!hidFlg[17]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName18__c}" rendered="{!hidFlg[17]}" id="SetName18"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty18__c.label}" rendered="{!hidFlg[17]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty18__c}" rendered="{!hidFlg[17]}" id="SetQty18"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName19__c.label}" rendered="{!hidFlg[18]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName19__c}" rendered="{!hidFlg[18]}" id="SetName19"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty19__c.label}" rendered="{!hidFlg[18]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty19__c}" rendered="{!hidFlg[18]}" id="SetQty19"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName20__c.label}" rendered="{!hidFlg[19]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName20__c}" rendered="{!hidFlg[19]}" id="SetName20"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty20__c.label}" rendered="{!hidFlg[19]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty20__c}" rendered="{!hidFlg[19]}" id="SetQty20"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName21__c.label}" rendered="{!hidFlg[20]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName21__c}" rendered="{!hidFlg[20]}" id="SetName21"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty21__c.label}" rendered="{!hidFlg[20]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty21__c}" rendered="{!hidFlg[20]}" id="SetQty21"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName22__c.label}" rendered="{!hidFlg[21]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName22__c}" rendered="{!hidFlg[21]}" id="SetName22"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty22__c.label}" rendered="{!hidFlg[21]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty22__c}" rendered="{!hidFlg[21]}" id="SetQty22"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName23__c.label}" rendered="{!hidFlg[22]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName23__c}" rendered="{!hidFlg[22]}" id="SetName23"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty23__c.label}" rendered="{!hidFlg[22]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty23__c}" rendered="{!hidFlg[22]}" id="SetQty23"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName24__c.label}" rendered="{!hidFlg[23]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName24__c}" rendered="{!hidFlg[23]}" id="SetName24"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty24__c.label}" rendered="{!hidFlg[23]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty24__c}" rendered="{!hidFlg[23]}" id="SetQty24"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName25__c.label}" rendered="{!hidFlg[24]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName25__c}" rendered="{!hidFlg[24]}" id="SetName25"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty25__c.label}" rendered="{!hidFlg[24]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty25__c}" rendered="{!hidFlg[24]}" id="SetQty25"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName26__c.label}" rendered="{!hidFlg[25]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName26__c}" rendered="{!hidFlg[25]}" id="SetName26"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty26__c.label}" rendered="{!hidFlg[25]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty26__c}" rendered="{!hidFlg[25]}" id="SetQty26"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName27__c.label}" rendered="{!hidFlg[26]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName27__c}" rendered="{!hidFlg[26]}" id="SetName27"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty27__c.label}" rendered="{!hidFlg[26]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty27__c}" rendered="{!hidFlg[26]}" id="SetQty27"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName28__c.label}" rendered="{!hidFlg[27]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName28__c}" rendered="{!hidFlg[27]}" id="SetName28"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty28__c.label}" rendered="{!hidFlg[27]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty28__c}" rendered="{!hidFlg[27]}" id="SetQty28"/>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName29__c.label}" rendered="{!hidFlg[28]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName29__c}" rendered="{!hidFlg[28]}" id="SetName29"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty29__c.label}" rendered="{!hidFlg[28]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty29__c}" rendered="{!hidFlg[28]}" id="SetQty29"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetName30__c.label}" rendered="{!hidFlg[29]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetName30__c}" rendered="{!hidFlg[29]}" id="SetName30"/>
+                        </td>
+                        <th style="text-align:right;width:90px;">
+                            <apex:outputLabel value="{!$ObjectType.Quote.fields.SetQty30__c.label}" rendered="{!hidFlg[29]}"/></th>
+                        <td style="text-align:right;width:130px;">
+                            <apex:outputField value="{!quo.SetQty30__c}" rendered="{!hidFlg[29]}" id="SetQty30"/>
+                        </td>
+                    </tr>
+                </table>
+            </div>
+
+            <table style="width:1200px;" border="0">
+                <tr>
+                    <th style="text-align:right;width:20px;">&nbsp;</th>
+                    <th style="text-align:center;width:80px;">&nbsp;</th>
+                    <th style="text-align:center;width:190px;">&nbsp;</th>
+                    <th style="text-align:center;width:80px;">&nbsp;</th>
+                    <th style="text-align:center;width:80px;">&nbsp;</th>
+                    <th style="text-align:center;width:110px;">&nbsp;</th>
+                    <th style="text-align:right;width:70px;">
+                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                        {!$ObjectType.QuoteLineItem.fields.TotalPrice.label}
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                        {!$ObjectType.QuoteLineItem.fields.Discount.label}
+                        <!-- {!$ObjectType.Quote.fields.Discount_Special__c.label} -->
+                    </apex:outputPanel>
+                    </th>
+                    <th style="text-align:center;width:120px;">
+                        <apex:inputText id="discount" value="{!discount}" style="width: 105px;text-align: right;"/>
+                    </th>
+                    <th style="text-align:right;width:110px;">
+                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                        &nbsp;&nbsp;&nbsp;&nbsp;瀹㈡埛鎬讳环
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                        % <input type="button" value="閫傜敤" onclick="setall();"/>&nbsp;&nbsp;&nbsp;&nbsp;瀹㈡埛鎬讳环
+                    </apex:outputPanel>
+                    </th>
+                    <th style="text-align:center;width:120px;"><apex:inputField id="totalCustomPrice" value="{!quo.Custom_Price_Total_Text__c}" style="width: 105px;text-align: right;"/></th>
+                    <th style="text-align:left;width:220px;">
+                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                        &nbsp;
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                         <input type="button" value="纭畾" onclick="setCPD();"/>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                        <input type="button" value="浜у搧閰嶅鎼滅储" onclick="searchSetProduct();"/>
+                    </apex:outputPanel>
+                    </th>
+                </tr>
+                <tr>
+                    <th style="text-align:right;">No</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Set__c.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.Product2.fields.name.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.Product2.fields.ProductCode.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.Product2.fields.Product_ECCode__c.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.UnitPrice.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Quantity.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Discount.label} %</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.TotalPrice.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Custom_Price__c.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Description.label}</th>
+                </tr>
+            </table>
+
+            <div id="iframelike" style="width:1218px;">
+                <table class="list" style="border-bottom-width: 0px; font-size:11px; border-spacing:0; width:1200px; border-collapse: collapse; table-layout: fixed;" border="0">
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!activities}" var="s" id="lists">
+                        <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                            <td class="dataCell" style="width:10px;text-align:left;">
+                                <apex:inputHidden id="PbeId" value="{!s.pageObject.PricebookEntryId}"/>
+                                <apex:inputHidden id="ProId" value="{!s.pageObject.Product2Id}"/>
+                                <apex:inputHidden id="price0" value="{!s.salesPrice}"/>
+                                <apex:inputHidden id="price1" value="{!s.salesPriceA}"/>
+                                <apex:inputHidden id="price2" value="{!s.salesPriceB}"/>
+                                <apex:inputHidden id="price3" value="{!s.salesPriceC}"/>
+                                <apex:inputHidden id="hidSet" value="{!s.pageObject.Set__c}"/>
+                                <apex:inputHidden id="hiddenflg" value="{!s.hiddenflg}"/>
+                                <apex:outputLabel id="indexNo" value="{!IF(s.productName==null,null,s.lineNo + 1)}" style="width:90%;text-align:center;"/>
+                                <!-- XHL-20190515-AddStart -->
+                                <apex:inputHidden id="QuantityReference" value="{!s.pageObject.Quantity}"/>
+                                <apex:inputHidden id="ProductNameReference" value="{!s.productName}"/>
+                                <apex:inputHidden id="DiscountReference" value="{!s.pageObject.Discount}"/>
+                                <apex:inputHidden id="SingleProduct" value="{!s.pageObject.SingleProduct__c}"/>
+                                <!-- XHL-20190515-AddEnd -->
+                            </td>
+                            
+                            <td class="dataCell" style="text-align:center;width:70px;">
+                                <apex:outputText id="Set" style="width:90%;text-align:right;" value="{!s.setName}"/>
+                                <apex:inputHidden id="SetName" value="{!s.setName}"/>
+                                <!-- XHL-20190426-AddStart -->
+                                <!-- <apex:inputHidden id="SingleProduct" value="{!s.pageObject.SingleProduct__c}"/> -->
+                                <!-- XHL-20190426-AddEnd -->
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:170px;">
+                                <apex:inputText id="ProductName" style="width:90%;" value="{!s.productName}" onclick="searchProduct('{!s.lineNo}',this.value,'{!s.pageObject.Set__c}')" onchange="doReroadJs('{!s.lineNo}');" />
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:70px;">
+                                <apex:outputText id="ProductCode" style="width:90%;text-align:right;" value="{!s.productCode}" />
+                                <apex:inputHidden id="ProductCodeHidden" value="{!s.productCode}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:70px;">
+                                <apex:outputText id="ProductEC" style="width:90%;text-align:right;" value="{!s.productEC}"/>
+                                <apex:inputHidden id="ProductECHidden" value="{!s.productEC}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:100px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:inputText id="UnitPrice" style="width:90%;text-align:right;" value="{!s.pageObject.UnitPrice}" onchange="changeLimit({!cnt-1});"/>
+                            </apex:outputPanel>
+                                <apex:inputHidden id="isProductModel" value="{!s.isProductModel}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:60px;">
+                                <apex:inputText id="Quantity" style="width:90%;text-align:right;" value="{!s.pageObject.Quantity}" onchange="setTotalPrice({!cnt-1},false)"/>
+                                <!-- <apex:inputHidden id="QuantityReference" value="{!s.pageObject.Quantity}"/> -->
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:110px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:inputText id="Discount" style="width:90%;text-align:right;" value="{!s.pageObject.Discount}" onchange="setTotalPrice({!cnt-1},false)" />
+                                <!-- <apex:inputText id="Discount" style="width:90%;text-align:right;" value="{!s.Discount}" onchange="setTotalPrice({!cnt-1})"/> -->
+                            </apex:outputPanel>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:100px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:outputText id="TotalPrice" style="width:90%;text-align:right;" value="{0, number, ###,##0.00}">
+                                    <apex:param value="{!s.totalPrice}" />
+                                </apex:outputText>
+                            </apex:outputPanel>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:110px;">
+                            <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                &nbsp;
+                            </apex:outputPanel>
+                            <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                <apex:inputText id="CustomPrice" style="width:90%;text-align:right;" value="{!s.customPrice}"/>
+                            </apex:outputPanel>
+                                <apex:inputHidden id="CustomPriceHidden" value="{!s.pageObject.Custom_Price__c}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:200px;">
+                                <apex:inputText id="Description" style="width:90%;text-align:left;" value="{!s.pageObject.Description}"/>
+                            </td>
+                           
+
+                        </tr>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </apex:repeat>
+                </table>
+            </div>
+            <BR></BR>
+
+            <div>
+                <table border="0">
+                    <tr>
+                        <td colspan="1">&nbsp;</td>
+                        <th colspan="7">{!$ObjectType.Quote.fields.Comment__c.label}</th>
+                        <td colspan="3">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <td colspan="1">&nbsp;</td>
+                        <td colspan="7"><apex:inputTextarea id="comment" value="{!quo.Comment__c}" rows="5" style="width: 100%;resize: none;"/></td>
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td colspan="2"><apex:commandButton onclick="undecidebtn();" value="{!$Label.UnDecide_Button}" style="width:110px;" rerender="dummy" disabled="{!!isdecide || !isAdmin}" rendered="{!isAdmin}"/></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="save2btn();return false;" value="{!$Label.Save_Button}" style="width:110px;" rerender="dummy" disabled="{!isdecide}"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="oppReflection2btn();" value="{!$Label.Save_Close_Button}" style="width:110px;" rerender="dummy" disabled="{!isdecide}"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="decidebtn();" value="{!$Label.Decide_Button}" style="width:110px;" rerender="dummy" disabled="{!decideFlg || isdecide}"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="width:110px;" align="right"><apex:commandButton onclick="backbtn();" value="{!$Label.NoSave_Return_Button}" style="width:90px;" rerender="dummy"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="width:110px;" align="right"><apex:commandButton onclick="printPDF();" value="鎵撳嵃PDF" style="width:110px;" rerender="dummy" disabled="{!!printFlg}"/></td>
+
+                        <td width="120px">鎵撳嵃鏄庣粏浠锋牸&nbsp;<input type="checkbox" id="isPrintPrice"/></td>
+
+                    </tr>
+                </table>
+            </div>
+           
+        </apex:pageBlock>
+            
+             <!--  <hr id="hid" onmouseout="dummy();" /> -->
+    </apex:form>
+
+    <apex:form id="fileForm">
+        <table border="0">
+            <tr>
+                <th>鎶ヤ环瀵煎叆锛�</th>
+                <th>1.<apex:inputFile value="{!contentFile}" filename="{!nameFile}" /></th>
+            </tr>
+            <tr>
+                <th>&nbsp;</th>
+                <th>2.&nbsp;<apex:commandButton action="{!csvRead}"  value="璇诲彇CSV"/></th>
+                <!-- <th>2.&nbsp;<apex:commandButton onclick="dummy1();" value="璇诲彇CSV"/></th>-->
+            </tr>
+        </table>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewQuoteEntry.page-meta.xml b/scr/pages/NewQuoteEntry.page-meta.xml
new file mode 100644
index 0000000..bdcbc91
--- /dev/null
+++ b/scr/pages/NewQuoteEntry.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewQuoteEntry</label>
+</ApexPage>
diff --git a/scr/pages/NewQuoteService.page b/scr/pages/NewQuoteService.page
new file mode 100644
index 0000000..c88d415
--- /dev/null
+++ b/scr/pages/NewQuoteService.page
@@ -0,0 +1,534 @@
+<apex:page standardController="Quote" extensions="NewQuoteEntryController" sidebar="false" action="{!init}" id="Page">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+    <script type="text/javascript">
+
+        var oppId = '{!oppId}';
+        var openQuoteExcelImportWindow = null;
+        var baseUrl = '{!baseUrl}';
+
+        function searchProduct(i,str,setStr){
+            // CNY USD銈掑彇寰�
+            //j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).attr('readonly',true);
+            var openType = j$(escapeVfId('openType')).value();
+            openPopup(baseUrl + '/apex/SearchProduct?lineno=' + i + '&val=' + encodeURIComponent(str) + '&set=' + encodeURIComponent(setStr) +'&oppId=' + encodeURIComponent(oppId) + '&openType=' + encodeURIComponent(openType), 'setsearch', 950, 450, 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+
+        function openQuoteExcelImport(e) {
+            if ( openQuoteExcelImportWindow == null || openQuoteExcelImportWindow.closed) {
+                openQuoteExcelImportWindow = window.open(baseUrl + '/apex/QuoteExcelImport', 'xlsdoc', 'width=450,height=210');
+            }
+            else {
+                openQuoteExcelImportWindow.focus();
+            }
+        }
+
+        function getLastLineNoNext(doc) {
+            var hasRecordFlg = false;
+            var lastLineNo = 0;
+            for(var i=99; i>=0; i--){
+                if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != ''){
+                    if (!hasRecordFlg) {
+                        lastLineNo = i;
+                    }
+                    hasRecordFlg = true;
+                }
+                if (hasRecordFlg == true) {
+                    if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() == ''){
+                        var moveCheckbox = true;
+                        //deletelist(i, doc, moveCheckbox);
+                        lastLineNo = i;
+                    }
+                }
+            }
+            if (hasRecordFlg) {
+                lastLineNo = lastLineNo + 1;
+            }
+            return lastLineNo;
+        }
+
+        function save2btn() {
+            //checkchangedAfterPrint();
+            //var changedAfterPrint = j$(escapeVfId('Page:mainForm:changedAfterPrint')).value();
+            //var changedAfterBid = j$(escapeVfId('Page:mainForm:changedAfterBid')).value();
+            var changedAfterPrint = false;
+            var changedAfterBid = false;
+
+            if (changedAfterBid == 'true') {
+                if (confirm(Confirm_ChangedAfterBid)) {
+                    blockme();
+                    Save.call();
+                    return;
+                }
+            } else if (changedAfterPrint == 'true') {
+                if (confirm(Confirm_ChangedAfterPrint)) {
+                    blockme();
+                    Save.call();
+                    return true;
+                }
+            } else {
+                blockme();
+                Save.call();
+                return true;
+            }
+        }
+
+        function doRefresh() {
+            blockme();
+            Refresh.call();
+            return true;
+
+        }
+
+        function oppReflection2btn() {
+
+            var changedAfterPrint = false;
+
+            if (changedAfterPrint == 'true') {
+                if (confirm(Confirm_ChangedAfterPrint)) {
+                    blockme();
+                    OppReflection.call();
+                    return true;
+                }
+            } else {
+                blockme();  
+                OppReflection.call();
+                return true;
+            }
+        }
+
+        function decidebtn() {
+            if (confirm('鎶ヤ环鍐冲畾鍚庯紝璇环涓嶈兘鍚屾鍏朵粬鎶ヤ环锛屾槸鍚﹀喅瀹氭姤浠凤紵') == false) {
+                return;
+            }
+            blockme();
+            Decide.call();
+            return true;
+        }
+
+        function undecidebtn() {
+            if (confirm('鏄惁鍙栨秷鍐冲畾锛�') == false) {
+                return;
+            }
+            blockme();
+            unDecide.call();
+            return true;
+        }
+
+        function backbtn() {
+            BackBtn.call();
+            return true;
+        }
+
+        function excelImportGateway(str) {
+            blockme();
+            excelImport(str);
+        }
+
+        function printPDF() {
+            var quoid = j$(escapeVfId('quoid')).value();
+            var printPrice = j$(escapeVfId('isPrintPrice')).prop('checked');
+            var baseUrl = '{!baseUrl}';
+            window.open(baseUrl + '/apex/QuotePDF?id=' + encodeURIComponent(quoid) + '&printprice=' + printPrice);
+        }
+
+        function setall() {
+            var discount = j$('#discount').value();
+            if (isNaN(discount) == true) {
+                alert('璇疯緭鍏ユ暟瀛椼��');
+                return false;
+            }
+            var quoteEntryMaxLine = {!quoteEntryMaxLine};
+            for (var i = 0; i < quoteEntryMaxLine; i++) {
+                if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).val(discount);
+                }
+            }
+        }
+
+        function setPrice(i) {
+            var distingush = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Distingush')).value();
+            if (distingush == 'A') {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price1')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            } else if (distingush == 'B') {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price2')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            } else if (distingush == 'C') {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price3')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            } else {
+                var price = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price0')).value();
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(price);
+            }
+        }
+
+        function setTotalPrice(i) {
+            if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                var quantity = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).value();
+                var unitprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).value();
+                var discount = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Discount')).value();
+                var totalprice = Math.round(quantity * unitprice * (100 - discount)) / 100;
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text(totalprice);
+            }
+        }
+
+        function changeLimit(i) {
+            if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                var unitprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).value();
+                var salesprice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':price0')).value();
+                var ispm = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':isProductModel')).value();
+                var isPartsdirect = j$(escapeVfId('isPartsdirect')).value();
+                var isPartsdealer = j$(escapeVfId('isPartsdealer')).value();
+                var hidset = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':hidSet')).value();
+                if (isPartsdirect == 'true') {
+                    alert("閿�鍞环鏍兼牴鎹鎴蜂环鏍艰嚜鍔ㄨ绠椼��");
+                    var quantity = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).value();
+                    var customPrice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPrice')).value();
+                    if (quantity == 0) {
+                        quantity = 1;
+                        j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).val(quantity);
+                    }
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(customPrice / quantity);
+                    setTotalPrice(i);
+                } else if (ispm == 'true' || (isPartsdealer == 'true' && (hidset == 'set02' || hidset == 'set03'))) {
+                    setTotalPrice(i);
+                } else {
+                    alert("涓嶈兘鎵嬪姩淇敼閿�鍞环鏍笺��");
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(salesprice);
+                }
+            }
+        }
+
+        function setUnitPrice(i) {
+            if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                var isPartsdirect = j$(escapeVfId('isPartsdirect')).value();
+                if (isPartsdirect == 'true') {
+                    var quantity = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).value();
+                    var customPrice = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPrice')).value();
+                    if (quantity == 0) {
+                        quantity = 1;
+                        j$(escapeVfId('Page:mainForm:block:lists:' + i + ':Quantity')).val(quantity);
+                    }
+                    j$(escapeVfId('Page:mainForm:block:lists:' + i + ':UnitPrice')).val(customPrice / quantity);
+                }
+            }
+        }
+
+        function setCPD() {
+            var quoteEntryMaxLine = {!quoteEntryMaxLine};
+            var total = 0;
+            var cnt = 0;
+            for (var i = 0; i < quoteEntryMaxLine; i++) {
+                if (j$(escapeVfId('Page:mainForm:block:lists:' + i + ':ProductName')).value() != '') {
+                    var line = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text();
+                    total += localParseFloat(line);
+                    cnt += localParseFloat(1);
+                }
+            }
+            var totalCP = j$(escapeVfId('totalCustomPrice')).value();
+            j$(escapeVfId('totalCustomPrice')).val(toNum(totalCP));
+            var totalCPD = 0;
+            for (var i = 0; i < cnt - 1; i++) {
+                var line = j$(escapeVfId('Page:mainForm:block:lists:' + i + ':TotalPrice')).text();
+                line = localParseFloat(line);
+                var lineCP = line / total * totalCP;
+                lineCP = lineCP.toFixed(0);
+                totalCPD += localParseFloat(lineCP);
+                j$(escapeVfId('Page:mainForm:block:lists:' + i + ':CustomPrice')).val(toNum(lineCP));
+            }
+        }
+    </script>
+
+    <style type="text/css">
+        div#iframelike {
+            color: #fff;
+            height: 300px;
+            overflow: auto;
+        }
+        div#iframelikeheader {
+            color: #fff;
+            height: 23px;
+            overflow: auto;
+        }
+        input {
+            font-size: 10.5px;
+        }
+        body {
+            font-size: 10.5px;
+        }
+    </style>
+    <apex:form id="mainForm">
+
+        <apex:actionFunction action="{!Refresh}" name="Refresh" reRender="mainForm,message1" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!excelImport}" name="excelImport" reRender="mainForm" oncomplete="unblockUI();">
+            <apex:param assignTo="{!excel_text}" name="select_index" value=""/>
+        </apex:actionFunction>
+
+        <apex:actionFunction action="{!Save}" name="Save" reRender="mainForm,message1" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!OppReflection}" name="OppReflection" reRender="mainForm" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!Decide}" name="Decide" reRender="mainForm" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!UnDecide}" name="unDecide" reRender="mainForm" oncomplete="unblockUI();"/>
+
+        <apex:actionFunction action="{!BackBtn}" name="BackBtn" reRender="mainForm,message1" />
+
+        <apex:pageBlock id="block">
+
+            <apex:inputHidden value="{!pricebook2Id}" id="pricebook2Id"/>
+            <input type="hidden" value="{!quoId}" id="quoid"/>
+            <input type="hidden" value="{!openType}" id="openType"/>
+            <input type="hidden" value="{!is_Parts_direct}" id="isPartsdirect"/>
+            <input type="hidden" value="{!is_Parts_dealer}" id="isPartsdealer"/>
+
+            <apex:outputPanel id="message1">
+                <apex:messages styleClass="editListError"/>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!errorflg}" >
+                <table width="100%">
+                    <tr>
+                        <td align="left"><div class="errorMsg">{!errorMessage}</div></td>
+                    </tr>
+                </table>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!Messageflg}" >
+                <table width="100%">
+                    <tr>
+                        <td align="left">{!Message}</td>
+                    </tr>
+                </table>
+            </apex:outputPanel>
+            <div>
+                <table border="0">
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.QuoteNumber.label}</th>
+                        <td style="text-align:right;width:130px;"><apex:outputLabel value="{!quo.QuoteNumber}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Name.label}</th>
+                        <td style="width:130px;"><apex:inputText value="{!quo.Name}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Account.fields.name.label}</th>
+                        <td style="text-align:right;width:130px;" colspan="2"><apex:outputLabel value="{!quo.Account.name}"/></td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Subtotal.label}</th>
+                        <td style="text-align:right;width:130px;">{!quo.currencyISOCode}&nbsp;<apex:outputText value="{0,number,###,###,##0.00}"><apex:param value="{!quo.Subtotal}"/></apex:outputText></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Discount.label}</th>
+                        <td style="text-align:right;width:130px;"><apex:outputField value="{!quo.Discount}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.TotalPrice.label}</th>
+                        <td style="text-align:right;width:130px;">{!quo.currencyISOCode}&nbsp;<apex:outputText value="{0,number,###,###,##0.00}"><apex:param value="{!quo.TotalPrice}"/></apex:outputText></td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.PaymentTerms__c.label}</th>
+                        <td style="text-align:left;width:310px;" colspan="3"><apex:inputField value="{!quo.PaymentTerms__c}"/></td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:left;width:130px;">&nbsp;</td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:left;width:130px;">&nbsp;</td>
+                        <td style="text-align:left;width:90px;">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.DeliveryLeadTime__c.label}</th>
+                        <td style="text-align:left;width:130px;"><apex:inputField value="{!quo.DeliveryLeadTime__c}"/></td>
+                        <th style="text-align:right;width:90px;">{!$ObjectType.Quote.fields.Warranty__c.label}</th>
+                        <td style="text-align:left;width:130px;"><apex:inputField value="{!quo.Warranty__c}"/></td>
+                        <th style="text-align:right;width:90px;">鎶ヤ环鍒版湡鏃ユ湡</th>
+                        <td style="text-align:left;width:130px;" colspan="2"><apex:inputField value="{!quo.ExpirationDate}"/></td>
+                        <td style="text-align:right;width:90px;">&nbsp;</td>
+                        <td style="text-align:right;width:130px;">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Main_Model__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Main_Model__c}"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Main_Serial_Number__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Main_Serial_Number__c}"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Type__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Service_Type__c}" style="width: 90%"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Contract_Number__c.label}</th>
+                        <td style="text-align:right;"><apex:inputField value="{!quo.Contract_Number__c}"/></td>
+                        <th style="text-align:right;width:90px;">&nbsp;</th>
+                        <td style="text-align:right;width:130px;"><apex:commandButton onclick="doRefresh();return false;" value="{!$Label.Status_Update}" style="width:110px;" rerender="dummy"/></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Date__c.label}</th>
+                        <td style="text-align:right;"><apex:inputField value="{!quo.Service_Date__c}"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Finish_Date__c.label}</th>
+                        <td style="text-align:right;"><apex:inputField value="{!quo.Service_Finish_Date__c}"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Location__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Service_Location__c}" style="width: 90%"/></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Engineer_Sign__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Service_Engineer_Sign__c}"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Pickup_Sign__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Service_Pickup_Sign__c}"/></td>
+                        <th style="text-align:right;">{!$ObjectType.Quote.fields.Service_Check_Sign__c.label}</th>
+                        <td style="text-align:left;"><apex:inputField value="{!quo.Service_Check_Sign__c}"/></td>
+                        <td style="text-align:right;">&nbsp;</td>
+                        <td style="text-align:right;">&nbsp;</td>
+                        <th style="text-align:right;width:90px;">鏂囦欢鍚嶏細</th>
+                        <td style="text-align:right;width:130px;"><apex:inputText value="{!fileName}" /></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;vertical-align:top;">{!$ObjectType.Quote.fields.Service_Status__c.label}</th>
+                        <td style="text-align:left;" colspan="3"><apex:inputField value="{!quo.Service_Status__c}" style="width:95%;resize:none;"/></td>
+                        <th style="text-align:right;vertical-align:top;">{!$ObjectType.Quote.fields.Service_Content__c.label}</th>
+                        <td style="text-align:left;" colspan="3"><apex:inputField value="{!quo.Service_Content__c}" style="width:95%;resize:none;"/></td>
+                        <th style="text-align:right;width:90px;">&nbsp;</th>
+                        <td style="text-align:right;vertical-align:top;width:130px;"><apex:commandButton action="{!csvExport}" value="鍑哄姏CSV" /></td>
+                    </tr>
+                </table>
+            </div>
+
+            <br/>
+
+            <table style="width:1080px;" border="0">
+                <tr>
+                    <th style="text-align:right;width:20px;">&nbsp;</th>
+                    <th style="text-align:center;width:80px;">&nbsp;</th>
+                    <th style="text-align:center;width:190px;">&nbsp;</th>
+                    <th style="text-align:center;width:80px;">&nbsp;</th>
+                    <th style="text-align:center;width:110px;">&nbsp;</th>
+                    <th style="text-align:right;width:70px;">{!$ObjectType.QuoteLineItem.fields.Discount.label}</th>
+                    <th style="text-align:center;width:80px;"><input type="text" id="discount" value="{!quo.Discount}" style="width: 65px;text-align: right;"/></th>
+                    <th style="text-align:left;width:110px;">% <input type="button" value="閫傜敤" onclick="setall();"/>&nbsp;&nbsp;&nbsp;&nbsp;瀹㈡埛鎬讳环</th>
+                    <th style="text-align:center;width:120px;"><apex:inputField id="totalCustomPrice" value="{!quo.Custom_Price_Total_Text__c}" style="width: 105px;text-align: right;"/></th>
+                    <th style="text-align:left;width:220px;"> <input type="button" value="纭畾" onclick="setCPD();"/></th>
+                </tr>
+                <tr>
+                    <th style="text-align:right;">No</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Set__c.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.Product2.fields.name.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.Product2.fields.ProductCode.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.UnitPrice.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Quantity.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Discount.label} %</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.TotalPrice.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Custom_Price__c.label}</th>
+                    <th style="text-align:center;">{!$ObjectType.QuoteLineItem.fields.Description.label}</th>
+                </tr>
+            </table>
+
+            <div id="iframelike" style="width:1098px;">
+                <table class="list" style="border-bottom-width: 0px; font-size:11px; border-spacing:0; width:1080px; border-collapse: collapse; table-layout: fixed;" border="0">
+                    <apex:variable value="{!1}" var="cnt" />
+                    <apex:repeat value="{!activities}" var="s" id="lists">
+                        <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                            <td class="dataCell" style="width:10px;text-align:left;">
+                                <apex:inputHidden id="PbeId" value="{!s.pageObject.PricebookEntryId}"/>
+                                <apex:inputHidden id="ProId" value="{!s.pageObject.Product2Id}"/>
+                                <apex:inputHidden id="price0" value="{!s.salesPrice}"/>
+                                <apex:inputHidden id="price1" value="{!s.salesPriceA}"/>
+                                <apex:inputHidden id="price2" value="{!s.salesPriceB}"/>
+                                <apex:inputHidden id="price3" value="{!s.salesPriceC}"/>
+                                <apex:inputHidden id="hidSet" value="{!s.pageObject.Set__c}"/>
+                                <apex:outputLabel id="indexNo" value="{!IF(s.productName==null,null,s.lineNo + 1)}" style="width:90%;text-align:center;"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:70px;">
+                                <apex:outputText id="Set" style="width:90%;text-align:right;" value="{!s.setName}"/>
+                                <apex:inputHidden id="SetName" value="{!s.setName}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:170px;">
+                                <apex:inputText id="ProductName" style="width:90%;" value="{!s.productName}" onclick="searchProduct('{!s.lineNo}',this.value,'{!s.pageObject.Set__c}')" />
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:70px;">
+                                <apex:outputText id="ProductCode" style="width:90%;text-align:right;" value="{!s.productCode}"/>
+                                <apex:inputHidden id="ProductCodeHidden" value="{!s.productCode}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:100px;">
+                                <apex:inputText id="UnitPrice" style="width:90%;text-align:right;" value="{!s.pageObject.UnitPrice}" onchange="changeLimit({!cnt-1});"/>
+                                <apex:inputHidden id="isProductModel" value="{!s.isProductModel}"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:60px;">
+                                <apex:inputText id="Quantity" style="width:90%;text-align:right;" value="{!s.pageObject.Quantity}" onchange="setUnitPrice({!cnt-1});setTotalPrice({!cnt-1});"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:70px;">
+                                <apex:inputText id="Discount" style="width:90%;text-align:right;" value="{!s.pageObject.Discount}" onchange="setTotalPrice({!cnt-1})"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:100px;">
+                                <apex:outputText id="TotalPrice" style="width:90%;text-align:right;" value="{0, number, ###,##0.00}">
+                                    <apex:param value="{!s.totalPrice}" />
+                                </apex:outputText>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:110px;">
+                                <apex:inputText id="CustomPrice" style="width:90%;text-align:right;" value="{!s.pageObject.Custom_Price__c}" onchange="setUnitPrice({!cnt-1})"/>
+                            </td>
+
+                            <td class="dataCell" style="text-align:center;width:200px;">
+                                <apex:inputText id="Description" style="width:90%;text-align:left;" value="{!s.pageObject.Description}"/>
+                            </td>
+                        </tr>
+                        <apex:variable value="{!cnt + 1}" var="cnt" />
+                    </apex:repeat>
+                </table>
+            </div>
+            <BR></BR>
+
+            <div>
+                <table border="0">
+                    <tr>
+                        <td colspan="1">&nbsp;</td>
+                        <th colspan="7">{!$ObjectType.Quote.fields.Comment__c.label}</th>
+                        <td colspan="3">&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <td colspan="1">&nbsp;</td>
+                        <td colspan="7"><apex:inputTextarea id="comment" value="{!quo.Comment__c}" rows="5" style="width: 100%;resize: none;"/></td>
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td colspan="2"><apex:commandButton onclick="undecidebtn();" value="{!$Label.UnDecide_Button}" style="width:110px;" rerender="dummy" disabled="{!!isdecide || !isAdmin}" rendered="{!isAdmin}"/></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="save2btn();return false;" value="{!$Label.Save_Button}" style="width:110px;" rerender="dummy" disabled="{!isdecide}"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="oppReflection2btn();" value="{!$Label.Save_Close_Button}" style="width:110px;" rerender="dummy" disabled="{!isdecide}"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="text-align:right;width:110px;"><apex:commandButton onclick="decidebtn();" value="{!$Label.Decide_Button}" style="width:110px;" rerender="dummy" disabled="{!decideFlg || isdecide}"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="width:110px;" align="right"><apex:commandButton onclick="backbtn();" value="{!$Label.NoSave_Return_Button}" style="width:90px;" rerender="dummy"/></td>
+
+                        <th style="text-align:right;width:50px;">&nbsp;</th>
+                        <td style="width:110px;" align="right"><apex:commandButton onclick="printPDF();" value="鎵撳嵃PDF" style="width:110px;" rerender="dummy" disabled="{!!printFlg}"/></td>
+
+                        <td width="120px">鎵撳嵃鏄庣粏浠锋牸&nbsp;<input type="checkbox" id="isPrintPrice"/></td>
+
+                    </tr>
+                </table>
+            </div>
+        </apex:pageBlock>
+    </apex:form>
+    <apex:form id="fileForm">
+        <table border="0">
+            <tr>
+                <th>鎶ヤ环瀵煎叆锛�</th>
+                <th>1.<apex:inputFile value="{!contentFile}" filename="{!nameFile}"/></th>
+            </tr>
+            <tr>
+                <th>&nbsp;</th>
+                <th>2.&nbsp;<apex:commandButton action="{!csvRead}" value="璇诲彇CSV"/></th>
+            </tr>
+        </table>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewQuoteService.page-meta.xml b/scr/pages/NewQuoteService.page-meta.xml
new file mode 100644
index 0000000..1039a49
--- /dev/null
+++ b/scr/pages/NewQuoteService.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewQuoteService</label>
+</ApexPage>
diff --git a/scr/pages/NewRepairParts.page b/scr/pages/NewRepairParts.page
new file mode 100644
index 0000000..08429c6
--- /dev/null
+++ b/scr/pages/NewRepairParts.page
@@ -0,0 +1,284 @@
+<apex:page id="Page" controller="NewRepairPartsController" action="{!init}" sidebar="false" showHeader="false">
+<!-- <apex:page standardController="RepairPart__c" id="Page" extensions="NewRepairPartsController" action="{!init}" sidebar="false" showHeader="false"> -->
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <style>
+        .pbSubheader {
+            background: #BFB19C!important;
+            /*background-color: #FFFFFF!important;*/
+            /*background: #BFB19C;*/
+            /*background-color: #44A3BB!important;
+            background-color: #E6E6FA!important;*/
+            /*background-color: #1797c0!important;*/
+            background-color: #DFE6F0!important;
+            /*color:#607799;*/
+            /*color:#FFFFFF!important;*/
+            /*background-color: #FFFFFF!important;*/
+            /*font-size:12pt;
+            font-family:verdana;*/
+            font-weight:bold;
+        }
+    </style>
+    <script>
+        //var isReturn = true;
+    	function returnSWOPage(){
+           var pageClose = j$(escapeVfId("pageClose")).value();
+           if(pageClose == "true"  ){
+                var repairPartId = j$(escapeVfId("repairPartId")).value();
+                var swoId = j$(escapeVfId("swoId")).value();
+                window.opener.repairReturnJS(repairPartId,swoId); 
+                window.close();
+           }
+    	}
+
+    	function saveJS(){
+    		blockme();
+    		save();
+    	}
+
+    	function closePage(){
+    		window.close();
+    	}
+
+    	function deleteJS(){
+    		if(confirm('鏄惁鍒犻櫎?')==true){
+                var Id = j$(escapeVfId("id")).value();
+                if(Id == null || Id == ""){
+                    closePage();
+                    return;
+                }
+    			blockme();
+    			deleteAction();
+    		}
+    	}
+        function toSearchProduct(){
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            window.open(baseUrl + '/apex/NewSearchProductPage','_blank', 'width=500,height=300,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+        function searchProduct(){
+           var baseUrl = '{!baseUrl}';
+           
+            openPopup(baseUrl + '/apex/NewSearchProductPage', 'setsearch', 950, 450, 'width=500,height=300,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+        function productReturnJS(id,code,eccode,description){
+            j$(escapeVfId("Product")).val(id);
+            j$(escapeVfId("Page:formInfo:RepairPartInfo:j_id42:j_id46:ITEM")).val(code);
+            j$(escapeVfId("PART_NUMBER")).val(eccode);
+            j$(escapeVfId("DESCRIPTION")).val(description);
+        }
+
+       function setProduct(){
+            blockme();
+            var productId = j$(escapeVfId("Page:formInfo:RepairPartInfo:j_id39:j_id43:Product")).val();
+            productReturn(productId);
+       }
+
+    </script>
+    
+	<apex:form id="formInfo">
+        <apex:outputPanel id="message">
+            <apex:pagemessages />
+        </apex:outputPanel>
+		<apex:actionFunction name="save" action="{!save}" oncomplete="returnSWOPage();unblockUI();" reRender="formInfo,message"/>
+		<apex:actionFunction name="deleteAction" action="{!deleteAction}" oncomplete="returnSWOPage();unblockUI();" reRender="formInfo,message"/>
+        <apex:actionFunction name="productReturn" action="{!productReturn}" oncomplete="unblockUI();" reRender="formInfo">
+            <apex:param name="productId" value="{!productId}" />
+        </apex:actionFunction>
+        <input type="hidden" id="repairPartId" value="{!repairId}" />
+		<input type="hidden" id="pageClose" value="{!pageClose}" />
+		<input type="hidden" id="swoId" value="{!repairPart.SWO_ID__c}" />
+        <input type="hidden" id="id" value="{!repairPart.Id}" />
+        <input type="hidden" id="baseUrl" value="{!baseUrl}" />
+        <input type="hidden" id="Product" value="{!repairPart.Product__c}" />
+        <input type="hidden" id="PART_NUMBER" value="{!repairPart.PART_NUMBER__c}" />
+        <input type="hidden" id="DESCRIPTION" value="{!repairPart.DESCRIPTION__c}" />
+		<apex:pageBlock id="RepairPartInfo" title="RepairPart">
+			<apex:pageBlockButtons location="top">
+				<apex:commandButton onclick="saveJS()" value="Save" oncomplete="returnSWOPage();" reRender="formInfo,messageInfo" style="width: 10%">
+					
+				</apex:commandButton>
+
+				<apex:commandButton onclick="closePage();" value="Cancel" style="width: 10%">
+					
+				</apex:commandButton>
+                <!-- onclick="deleteJS();" -->
+                <apex:commandButton onclick="deleteJS();" oncomplete="returnSWOPage();" value="Delete" style="width: 10%">
+				<!-- <apex:commandButton action="{!deleteAction}" oncomplete="returnSWOPage();" reRender="formInfo" value="鍒犻櫎" > -->
+					
+				</apex:commandButton>
+			</apex:pageBlockButtons>
+			<apex:pageBlockSection title="RepairPart" columns="2">
+					<apex:pageBlockSectionItem >
+	                   
+                    </apex:pageBlockSectionItem>
+
+					<apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.SWO_ID__c.label}" for="SWO_ID"/>
+	                    <apex:outputField value="{!repairPart.SWO_ID__c}" id="SWO_ID" />
+                    </apex:pageBlockSectionItem>
+
+					<!-- <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.Product__c.label}" for="ITEM"/>
+	                    <apex:inputField value="{!repairPart.Product__c}" id="ITEM" required="true"/>
+                    </apex:pageBlockSectionItem> -->
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.Product__c.label}" for="Product"/>
+                        <apex:inputField value="{!repairPart.Product__c}" id="Product" required="true" />
+                    </apex:pageBlockSectionItem>
+                    
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.ITEM_ProductCode__c.label}" for="ITEM"/>
+                        <apex:inputField value="{!repairPart.ITEM_ProductCode__c}" id="ITEM"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.PART_NUMBERNew__c.label}" for="PART_NUMBER"/>
+                        <apex:inputField value="{!repairPart.PART_NUMBERNew__c}" id="PART_NUMBER"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                        <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.DescriptionNew__c.label}" for="Description"/>
+                        <apex:inputField value="{!repairPart.DescriptionNew__c}" id="Description"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.QUANTITY__c.label}" for="QUANTITY"/>
+                    <apex:inputField value="{!repairPart.QUANTITY__c}" id="QUANTITY" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.INST_SERIAL__c.label}" for="INST_SERIAL"/>
+	                    <apex:inputField value="{!repairPart.INST_SERIAL__c}" id="INST_SERIAL"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.DEFECT_PART_NUMBER__c.label}" for="DEFECT_PART_NUMBER"/>
+	                    <apex:inputField value="{!repairPart.DEFECT_PART_NUMBER__c}" id="DEFECT_PART_NUMBER"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.LOCATION__c.label}" for="LOCATION"/>
+	                    <apex:inputField value="{!repairPart.LOCATION__c}" id="LOCATION" required="true"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.DEFECT_SERIAL_NUMBER__c.label}" for="DEFECT_SERIAL_NUMBER"/>
+	                    <apex:inputField value="{!repairPart.DEFECT_SERIAL_NUMBER__c}" id="DEFECT_SERIAL_NUMBER"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.ECN__c.label}" for="ECN"/>
+	                    <apex:inputField value="{!repairPart.ECN__c}" id="ECN"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.ANI_DEFECT_CATEGORY__c.label}" for="ANI_DEFECT_CATEGORY"/>
+	                    <apex:inputField value="{!repairPart.ANI_DEFECT_CATEGORY__c}" id="ANI_DEFECT_CATEGORY"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.PICKED_BY__c.label}" for="PICKED_BY"/>
+	                    <apex:inputField value="{!repairPart.PICKED_BY__c}" id="PICKED_BY"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.HOURS__c.label}" for="HOURS"/>
+	                    <apex:inputField value="{!repairPart.HOURS__c}" id="HOURS"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.INVENTORY_AVAILABILITY__c.label}" for="INVENTORY_AVAILABILITY"/>
+	                    <apex:inputField value="{!repairPart.INVENTORY_AVAILABILITY__c}" id="INVENTORY_AVAILABILITY"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.BILL_AT_0_VALUE__c.label}" for="BILL_AT_0_VALUE"/>
+	                    <apex:inputField value="{!repairPart.BILL_AT_0_VALUE__c}" id="BILL_AT_0_VALUE"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.Webster_Loaner__c.label}" for="Webster_Loaner"/>
+	                    <apex:inputField value="{!repairPart.Webster_Loaner__c}" id="Webster_Loaner"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.QTY_PICKED__c.label}" for="QTY_PICKED"/>
+	                    <apex:inputField value="{!repairPart.QTY_PICKED__c}" id="QTY_PICKED"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                   
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.PICKED_DATE__c.label}" for="PICKED_DATE"/>
+	                    <apex:inputField value="{!repairPart.PICKED_DATE__c}" id="PICKED_DATE"/>
+                    </apex:pageBlockSectionItem>
+
+                    <apex:pageBlockSectionItem >
+	                   
+                    </apex:pageBlockSectionItem>
+                    <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="{!$ObjectType.RepairPart__c.fields.NOTES__c.label}" for="NOTES"/>
+	                    <apex:inputField value="{!repairPart.NOTES__c}" id="NOTES"/>
+                    </apex:pageBlockSectionItem>
+			</apex:pageBlockSection>
+		</apex:pageBlock>
+	</apex:form>
+
+    <!-- 閫夋嫨浜у搧寮瑰嚭灞傞儴鍒� -->
+
+    <!-- <div id="popBox">
+        <div class="close">
+            <a href="javascript:void(0)" onclick="closeBox()">鍏抽棴</a>
+        </div>
+        <div class="content">
+            <table width="100%">
+                <colgroup>
+                    <col width="33%"></col>
+                    <col width="33%"></col>
+                    <col width="33%"></col>
+                </colgroup>
+                <tr>
+                    <td>
+                        <apex:selectList id="type" value="{!ConditionType}" size="1">
+                            <apex:selectOption itemLabel="浜у搧鍚嶇О" itemValue="name"></apex:selectOption>
+                            <apex:selectOption itemLabel="浜у搧浠g爜" itemValue="code"></apex:selectOption>
+                            <apex:selectOption itemLabel="EC浠g爜" itemValue="eccode"></apex:selectOption>
+                        </apex:selectList>
+                    </td>
+                    <td>
+                        <apex:inputText value="{!ByCondition}"></apex:inputText>
+                    </td>
+                    <td>
+                        <apex:commandButton action="{!doSearch}" onclick="blockme();" reRender="data" oncomplete="unblockUI();" value="鏌ヨ"></apex:commandButton>
+                    </td>
+                </tr>
+                <tr>
+                    <th>浜у搧鍚嶇О</th>
+                    <th>浜у搧浠g爜</th>
+                    <th>EC浠g爜</th>
+                </tr>
+            </table>
+            <div style="width: 100%;height: 100%;overflow:auto;">
+                <table width="100%">
+                    <colgroup>
+                        <col width="33%"></col>
+                        <col width="33%"></col>
+                        <col width="33%"></col>
+                    </colgroup>
+                    <apex:repeat value="{!dataList}" var="line" id="result">
+                        <tr>
+                            <td><apex:outputLink value="javascript:void(0)" onclick="returnBefore('{!line.id}','{!line.code}','{!line.eccode}','{!line.description}')">{!line.name}</apex:outputLink></td>
+                            <td><apex:outputLink value="javascript:void(0)" onclick="returnBefore('{!line.id}','{!line.code}','{!line.eccode}','{!line.description}')">{!line.code}</apex:outputLink></td>
+                            <td><apex:outputLink value="javascript:void(0)" onclick="returnBefore('{!line.id}','{!line.code}','{!line.eccode}','{!line.description}')">{!line.eccode}</apex:outputLink></td>
+                        </tr>
+                    </apex:repeat>
+                </table>
+            </div>
+        </div>
+    </div>
+    <div id="popLayer">
+    </div> -->
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewRepairParts.page-meta.xml b/scr/pages/NewRepairParts.page-meta.xml
new file mode 100644
index 0000000..1457158
--- /dev/null
+++ b/scr/pages/NewRepairParts.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewRepairParts</label>
+</ApexPage>
diff --git a/scr/pages/NewRepairPartsRead.page b/scr/pages/NewRepairPartsRead.page
new file mode 100644
index 0000000..f654d6a
--- /dev/null
+++ b/scr/pages/NewRepairPartsRead.page
@@ -0,0 +1,2 @@
+<apex:page >
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewRepairPartsRead.page-meta.xml b/scr/pages/NewRepairPartsRead.page-meta.xml
new file mode 100644
index 0000000..24620f3
--- /dev/null
+++ b/scr/pages/NewRepairPartsRead.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewRepairPartsRead</label>
+</ApexPage>
diff --git a/scr/pages/NewReplacementOpportunity.page b/scr/pages/NewReplacementOpportunity.page
new file mode 100644
index 0000000..9934402
--- /dev/null
+++ b/scr/pages/NewReplacementOpportunity.page
@@ -0,0 +1,108 @@
+<apex:page id="Page" Controller="NewReplacementOpportunityController" sidebar="true" showHeader="true" action="{!init}">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <script>
+        function saveJs() {
+            blockme();
+            saveBtn();
+        }
+
+        function saveYesJs() {
+            blockme();
+            saveBtnYes();
+        }
+
+        function saveNoJs() {
+            blockme();
+            saveBtnNo();
+        }
+
+        function cancelJs() {
+            var baseUrl = '{!baseUrl}';
+            var rtUrl = '{!rtUrl}';
+            if (rtUrl == 'null' || rtUrl == '') {
+                rtUrl = '{!conId}';
+            }
+            window.location.href = baseUrl + "/" + rtUrl;
+        }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!saveBtn}" name="saveBtn" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnYes}" name="saveBtnYes" reRender="mainForm,message" oncomplete="unblockUI();"/>
+        <apex:actionFunction action="{!saveBtnNo}" name="saveBtnNo" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+
+        <input type="hidden" id="hasError" value="{!hasError}"/>
+        <input type="hidden" id="isDealerPage" value="{!isDealerPage}"/>
+         <apex:pageBlock id="idSearchSetProduct" title="鏂板缓璇环" tabStyle="Opportunity">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px" onclick="saveJs();" value="淇濆瓨" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="cancelJs();" value="鍙栨秷" rerender="dummy" rendered="{!IF(hasError == true, false, true)}"/>
+                <apex:commandButton style="width:50px" onclick="saveYesJs();" value="鏄�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+                <apex:commandButton style="width:50px" onclick="saveNoJs();" value="鍚�" rerender="dummy" rendered="{!IF(hasError == true, true, false)}"/>
+            </apex:pageBlockButtons>
+
+             <apex:pageBlockSection title="璇环淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环鍚嶇О" for="opp_Name"/>
+                    <apex:inputField value="{!opp.Name}" id="opp_Name"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="opp_ProductSegment"/>
+                    <apex:inputField value="{!opp.ProductSegment__c}" id="opp_ProductSegment" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="opp_Account"/>
+                    <apex:inputField value="{!opp.AccountId}" id="opp_Account" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璇环甯佺" for="opp_CurrencyIsoCode"/>
+                    <apex:inputField value="{!opp.CurrencyIsoCode}" id="opp_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绫诲瀷" for="opp_Type"/>
+                    <apex:inputField value="{!opp.Type}" id="opp_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閲戦" for="opp_Amount"/>
+                    <apex:inputField value="{!opp.Amount}" id="opp_Amount"/>
+                </apex:pageBlockSectionItem>
+                 <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏁存満/闆朵欢" for="opp_MachineParts"/>
+                    <apex:inputField value="{!opp.Machine_Parts__c}" id="opp_MachineParts"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍐呰锤 / 澶栬锤" for="opp_TradeType"/>
+                    <apex:inputField value="{!opp.TradeType__c}" id="opp_TradeType" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閿�鍞柟寮�" for="opp_SalesChannel"/>
+                    <apex:inputField value="{!opp.SalesChannel__c}" id="opp_SalesChannel" required="true"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="缁忛攢鍟嗙浉鍏充俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗗悕" for="opp_Dealer"/>
+                    <apex:inputField value="{!opp.Dealer__c}" id="opp_Dealer"/>
+                </apex:pageBlockSectionItem>
+            	<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浠g悊鍟嗛攢鍞媴褰撹�呭悕" for="opp_DealerSalesStaffName"/>
+                    <apex:inputField value="{!opp.DealerSalesStaffName__c}" id="opp_DealerSalesStaffName" required="true"/>
+            	</apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+        </apex:pageBlock>
+
+
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewReplacementOpportunity.page-meta.xml b/scr/pages/NewReplacementOpportunity.page-meta.xml
new file mode 100644
index 0000000..b3d705b
--- /dev/null
+++ b/scr/pages/NewReplacementOpportunity.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewReplacementOpportunity</label>
+</ApexPage>
diff --git a/scr/pages/NewSearchProductPage.page b/scr/pages/NewSearchProductPage.page
new file mode 100644
index 0000000..8140f67
--- /dev/null
+++ b/scr/pages/NewSearchProductPage.page
@@ -0,0 +1,65 @@
+<apex:page id="Page" Controller="NewSearchProductController" sidebar="false" showHeader="false" action="{!init}">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+	<script>
+		function returnBefore(id,code,eccode,description){
+			/*window.opener.productReturnJS(id,code,eccode,description); 
+            window.close();*/
+            window.opener.j$(escapeVfId("Page:formInfo:RepairPartInfo:j_id42:j_id46:ITEM")).val(code);
+            window.opener.j$(escapeVfId("Product")).val(id);
+            window.opener.j$(escapeVfId("PART_NUMBER")).val(eccode);
+            window.opener.j$(escapeVfId("DESCRIPTION")).val(description);
+		}
+	</script>
+	<apex:form id="data">
+		<input type="hidden" id="BaseUrl" value="{!BaseUrl}" />
+		<div style="width: 100%;height: 270px;">
+			<table width="100%">
+				<colgroup>
+					<col width="33%"></col>
+					<col width="33%"></col>
+					<col width="33%"></col>
+				</colgroup>
+				<tr>
+					<td>
+						<apex:selectList id="type" value="{!ConditionType}" size="1">
+							<apex:selectOption itemLabel="浜у搧鍚嶇О" itemValue="name"></apex:selectOption>
+							<apex:selectOption itemLabel="浜у搧浠g爜" itemValue="code"></apex:selectOption>
+							<apex:selectOption itemLabel="EC浠g爜" itemValue="eccode"></apex:selectOption>
+			 			</apex:selectList>
+		 			</td>
+		 			<td>
+		 				<apex:inputText value="{!ByCondition}"></apex:inputText>
+		 			</td>
+		 			<td>
+		 				<apex:commandButton action="{!doSearch}" onclick="blockme();" reRender="data" oncomplete="unblockUI();" value="鏌ヨ"></apex:commandButton>
+		 			</td>
+				</tr>
+				<tr>
+					<th>浜у搧鍚嶇О</th>
+					<th>浜у搧浠g爜</th>
+					<th>EC浠g爜</th>
+				</tr>
+			</table>
+			<div style="width: 100%;height: 100%;overflow:auto;">
+				<table width="100%">
+					<colgroup>
+						<col width="33%"></col>
+						<col width="33%"></col>
+						<col width="33%"></col>
+					</colgroup>
+					<apex:repeat value="{!dataList}" var="line" id="result">
+						<tr>
+							<td><apex:outputLink value="javascript:void(0)" onclick="returnBefore('{!line.id}','{!line.code}','{!line.eccode}','{!line.description}')">{!line.name}</apex:outputLink></td>
+							<td><apex:outputLink value="javascript:void(0)" onclick="returnBefore('{!line.id}','{!line.code}','{!line.eccode}','{!line.description}')">{!line.code}</apex:outputLink></td>
+							<td><apex:outputLink value="javascript:void(0)" onclick="returnBefore('{!line.id}','{!line.code}','{!line.eccode}','{!line.description}')">{!line.eccode}</apex:outputLink></td>
+						</tr>
+					</apex:repeat>
+				</table>
+			</div>
+		</div>
+	</apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/NewSearchProductPage.page-meta.xml b/scr/pages/NewSearchProductPage.page-meta.xml
new file mode 100644
index 0000000..bc44147
--- /dev/null
+++ b/scr/pages/NewSearchProductPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>NewSearchProductPage</label>
+</ApexPage>
diff --git a/scr/pages/OppInternalMessage.page b/scr/pages/OppInternalMessage.page
new file mode 100644
index 0000000..ca39872
--- /dev/null
+++ b/scr/pages/OppInternalMessage.page
@@ -0,0 +1,41 @@
+<apex:page standardController="Opportunity" extensions="OppInternalMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    //blockme();
+    if ('{!usertype}' == 'PowerPartner'){
+    window.open('/production/apex/OppInternalMessagePopup?raid=' + '{!URLENCODE(Opportunity.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    } else{
+    window.open('/apex/OppInternalMessagePopup?raid=' + '{!URLENCODE(Opportunity.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    }
+}
+
+function reloadjs() {
+    //blockme();
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="璁板綍" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!ra.InternalMessage__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OppInternalMessage.page-meta.xml b/scr/pages/OppInternalMessage.page-meta.xml
new file mode 100644
index 0000000..d4841b8
--- /dev/null
+++ b/scr/pages/OppInternalMessage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OppInternalMessage</label>
+</ApexPage>
diff --git a/scr/pages/OppInternalMessagePopup.page b/scr/pages/OppInternalMessagePopup.page
new file mode 100644
index 0000000..32f6256
--- /dev/null
+++ b/scr/pages/OppInternalMessagePopup.page
@@ -0,0 +1,51 @@
+<apex:page Controller="OppInternalMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.Opportunity.fields.InternalMessage__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="淇濆瓨" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra1.InternalMessage__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OppInternalMessagePopup.page-meta.xml b/scr/pages/OppInternalMessagePopup.page-meta.xml
new file mode 100644
index 0000000..002a968
--- /dev/null
+++ b/scr/pages/OppInternalMessagePopup.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OppInternalMessagePopup</label>
+</ApexPage>
diff --git a/scr/pages/OppTestPage.page b/scr/pages/OppTestPage.page
new file mode 100644
index 0000000..ad504ad
--- /dev/null
+++ b/scr/pages/OppTestPage.page
@@ -0,0 +1,48 @@
+<apex:page Controller="OppTestController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="娴嬭瘯">
+		<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+		<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+		<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+		<apex:form id="allForm">
+			<apex:pageBlock id="idSearchSetProduct" title="缂栬緫瀛︾敓淇℃伅" tabStyle="Opportunity">
+	            <apex:pageBlockButtons location="top">
+	                <apex:commandButton style="width:50px"  value="淇濆瓨" />
+	                <apex:commandButton style="width:50px"  value="鍙栨秷" />
+	            </apex:pageBlockButtons>
+
+		        <apex:pageBlockSection title="瀛︾敓淇℃伅" columns="2">
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="濮撳悕"/>
+	                    <apex:inputText value="{!dl.classType1}"/>
+	                </apex:pageBlockSectionItem>
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="骞撮緞"/>
+	                    <apex:inputText value="{!dl.classType2}"/>
+	                </apex:pageBlockSectionItem>
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="鎬у埆"/>
+	                    <apex:inputText value="{!dl.classType3}"/>
+	                </apex:pageBlockSectionItem>
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="鐝骇"/>
+	                    <apex:inputText value="{!dl.classType4}"/>
+	                </apex:pageBlockSectionItem>
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="鍒嗘暟"/>
+	                    <apex:inputText value="{!dl.classType5}"/>
+	                </apex:pageBlockSectionItem>
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="瀹℃壒鐘舵��"/>
+	                    <apex:inputText value="{!dl.classType6}"/>
+	                </apex:pageBlockSectionItem>
+	                <apex:pageBlockSectionItem >
+	                    <apex:outputLabel value="澶囨敞"/>
+	                    <apex:inputText value="{!dl.classType7}"/>
+	                </apex:pageBlockSectionItem>
+
+            </apex:pageBlockSection>
+        </apex:pageBlock>
+			
+		</apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OppTestPage.page-meta.xml b/scr/pages/OppTestPage.page-meta.xml
new file mode 100644
index 0000000..56ee7f7
--- /dev/null
+++ b/scr/pages/OppTestPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OppTestPage</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityAAdvanced.page b/scr/pages/OpportunityAAdvanced.page
new file mode 100644
index 0000000..e057ba7
--- /dev/null
+++ b/scr/pages/OpportunityAAdvanced.page
@@ -0,0 +1,231 @@
+<apex:page standardController="Opportunity" extensions="OpportunityAAdvancedController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="楂樼浜у搧">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+// 淇濆瓨
+function saveJs() {
+    blockme();
+    saveLine();
+}
+//鍒锋柊璇环椤甸潰
+function refreshPage(){
+    var baseUrl = j$(escapeVfId("baseUrl")).value();
+    window.parent.location.href = baseUrl + '/{!URLENCODE(opp.id)}';
+}
+
+function systemChange(){
+    /*var OppSystemId = 'allPage:allForm:allBlock:j_id9:OppSystem:OppSystem:OppSystem';
+    var oldSystem = j$(escapeVfId("oldSystem")).value();
+    
+    var newSystem = document.getElementById(OppSystemId).value;
+    
+    if (newSystem != oldSystem) {
+        alert('姝ゅ涓嶅彲淇敼System鐨勫��');
+        document.getElementById(OppSystemId).value = oldSystem;
+    }*/
+    blockme();
+    updat();
+}
+</script>
+<apex:form id="allForm">
+
+        <apex:actionFunction name="saveLine" action="{!saveLine}" rerender="allBlock,message" onComplete="unblockUI();refreshPage();">
+        </apex:actionFunction>
+         <apex:actionFunction name="updat" action="{!init}" rerender="allPanel" oncomplete="unblockUI()"></apex:actionFunction>
+
+        <input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+       
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="saveJs();" value="淇濆瓨楂樼浜у搧" rerender="dummy" disabled=""/>
+                        <apex:outputPanel id="message">
+                            <apex:messages />
+                        </apex:outputPanel>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel layout="none" id="OppSystem">
+                    <!-- <apex:pageBlockSection title="System" columns="2" rendered="true" >
+
+                        <apex:pageBlockSectionItem id="OppSystem" >
+                            <apex:outputLabel value="System" for="OppSystem"/>
+                            <apex:variable var="v" value="" id="OppSystem">
+                                <apex:inputField onchange="systemChange()" value="{!opp.OppSystem__c}" id="OppSystem" style="width: 300px" />
+                            </apex:variable>
+                        </apex:pageBlockSectionItem>
+                    </apex:pageBlockSection> -->
+
+                    <apex:pageBlockSection title="FV3000" columns="2" rendered="{!FV3000Flag}">
+
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Scanner" for="la_Type" />
+                            <apex:inputField value="{!opp.Scanner_FV3000__c}" id="FV3000_Scanner" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Detector" for="la_Type"/>
+                            <apex:inputField value="{!opp.Detector_FV3000__c}" id="FV3000_Detector" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Laser" for="la_Type"/>
+                            <apex:inputField value="{!opp.Laser_FV3000__c}" id="FV3000_Laser" style="width: 300px" />
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Frame" for="la_Type"/>
+                            <apex:inputField value="{!opp.Frame_FV3000__c}" id="FV3000_Frame" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Software" for="la_Type"/>
+                            <apex:inputField value="{!opp.Software_FV3000__c}" id="FV3000_Software" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Customization" for="la_Type"/>
+                            <apex:inputField value="{!opp.Customization_FV3000__c}" id="FV3000_Customization" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Remark" for="FV3000_Remark"/>
+                            
+                           <apex:inputField value="{!opp.Remark_FV3000__c}" id="FV3000_Remark" style="width: 294px"/>
+                           
+                        </apex:pageBlockSectionItem>
+                      
+                    </apex:pageBlockSection>
+                </apex:outputPanel>
+
+                <apex:outputPanel layout="none" >
+                    <apex:pageBlockSection title="FVMPE-RS" columns="2" rendered="{!FVMPERSFlag}">
+
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="IR laser" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.IR_laser_FVMPE_RS__c}" id="FVMPERS_OppIRlaser" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Detector" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.detector_FVMPE_RS__c}" id="FVMPERS_Detector" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="SIM" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.SIM_FVMPE_RS__c}" id="FVMPERS_SIM" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Frame" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Frame_FVMPE_RS__c}" id="FVMPERS_Frame" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Software" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Software_FVMPE_RS__c}" id="FVMPERS_Software" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="AC objective" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.AC_objective_FVMPE_RS__c}" id="FVMPERS_ACobjective" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Customization" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Customization_FVMPE_RS__c}" id="FVMPERS_Customization" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Remark" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Remark_FVMPE_RS__c}" id="FVMPERS_Remark" style="width: 294px"/>
+                        </apex:pageBlockSectionItem>
+                      
+                    </apex:pageBlockSection>
+                </apex:outputPanel>
+
+                <apex:outputPanel layout="none" >
+                    <apex:pageBlockSection title="SPIN" columns="2" rendered="{!SPINFlag}">
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Scanner" for="la_Type"/>
+                            <apex:inputField value="{!opp.Scanner_SPIN__c}" id="SPIN_Scanner" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Laser" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Laser_SPIN__c}" id="SPIN_Laser" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Camera" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Camera_SPIN__c}" id="SPIN_Camera" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Software" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Software_SPIN__c}" id="SPIN_Software" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Upgrade" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Upgrade_SPIN__c}" id="SPIN_Upgrade" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Remark" for="Loaner_Ser__c"/>
+                            <apex:inputField value="{!opp.Remark_SPIN__c}" id="SPIN_Remark" style="width: 294px" />
+                        </apex:pageBlockSectionItem>
+                      
+                    </apex:pageBlockSection>
+                </apex:outputPanel>
+
+                <apex:outputPanel layout="none" >
+                    <apex:pageBlockSection title="VS200" columns="2" rendered="{!VS200Flag}">
+
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Observation Set" for="la_Name"/>
+                            <apex:inputField value="{!opp.Observation_Set_VS200__c}" id="VS200_ObservationSet" style="width: 300px"/>
+                        </apex:pageBlockSectionItem> 
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Loader" for="la_Type"/>
+                            <apex:inputField value="{!opp.Loader_VS200__c}" id="VS200_Loader" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="FL Camera" for="la_Type"/>
+                            <apex:inputField value="{!opp.FL_Camera_VS200__c}" id="VS200_FLCamera" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Software" for="la_Type"/>
+                            <apex:inputField value="{!opp.Software_VS200__c}" id="VS200_Software" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Upgrade" for="la_Type"/>
+                            <apex:inputField value="{!opp.Upgrade_VS200__c}" id="VS200_Upgrade" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                       
+                      
+                    </apex:pageBlockSection>
+                </apex:outputPanel>
+
+                 <apex:outputPanel layout="none" >
+                    <apex:pageBlockSection title="Phaseview" columns="2" rendered="{!PhaseviewFlag}">
+
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Light sheet illuminator" for="la_Name"/>
+                            <apex:inputField value="{!opp.Light_sheet_illuminator_Phaseview__c}" id="Light_sheet_illuminator_Phaseview" style="width: 300px"/>
+                        </apex:pageBlockSectionItem> 
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Laser" for="la_Type"/>
+                            <apex:inputField value="{!opp.Laser_Phaseview__c}" id="Laser_Phaseview" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem >
+                            <apex:outputLabel value="Camera" for="la_Type"/>
+                            <apex:inputField value="{!opp.Camera_Phaseview__c}" id="Camera_Phaseview" style="width: 300px"/>
+                        </apex:pageBlockSectionItem>
+                       
+                      
+                    </apex:pageBlockSection>
+                </apex:outputPanel>
+
+                <apex:pageBlockSection title="鍏朵粬" columns="2" rendered="true" >
+
+                        <apex:pageBlockSectionItem id="Party" >
+                            <apex:outputLabel value="3rd party Product" for="Party"/>
+                            <apex:variable var="v" value="" id="Party">
+                                <apex:inputField value="{!opp.OppPartyProduct__c}" id="Party" style="width: 300px"/>
+                            </apex:variable>
+                        </apex:pageBlockSectionItem>
+                        <apex:pageBlockSectionItem id="Description" >
+                            <apex:outputLabel value="鍏朵粬璇存槑 Ohters" for="Description"/>
+                            <apex:variable var="v" value="" id="Description">
+                                <apex:inputField value="{!opp.OppOtherDescription__c}" id="Description" style="width: 300px"/>
+                            </apex:variable>
+                        </apex:pageBlockSectionItem>
+                </apex:pageBlockSection>
+            </apex:pageBlock>
+        </apex:outputPanel>
+
+</apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityAAdvanced.page-meta.xml b/scr/pages/OpportunityAAdvanced.page-meta.xml
new file mode 100644
index 0000000..1ac2a6c
--- /dev/null
+++ b/scr/pages/OpportunityAAdvanced.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityAAdvanced</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityCSVExport.page b/scr/pages/OpportunityCSVExport.page
new file mode 100644
index 0000000..9f8b456
--- /dev/null
+++ b/scr/pages/OpportunityCSVExport.page
@@ -0,0 +1,7 @@
+<apex:page standardController="Opportunity" extensions="OpportunityProductController" cache="true" contentType="text/csv;charset=utf-8;#{!fileName}.csv" language="zh-CN">"濂楄","浜у搧code","浜у搧鍚嶇О","鏁伴噺","OCSM鎶樻墸"
+    <apex:variable value="{!1}" var="line" />
+    <apex:repeat value="{!csv_activities}" var="item">
+"","{!item.productCode}","{!item.productName}","{!item.oli.Quantity}","{!item.discount}"
+    <apex:variable value="{!line + 1}" var="line" />
+    </apex:repeat>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityCSVExport.page-meta.xml b/scr/pages/OpportunityCSVExport.page-meta.xml
new file mode 100644
index 0000000..976ad1f
--- /dev/null
+++ b/scr/pages/OpportunityCSVExport.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityCSVExport</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityMessage.page b/scr/pages/OpportunityMessage.page
new file mode 100644
index 0000000..8c6914b
--- /dev/null
+++ b/scr/pages/OpportunityMessage.page
@@ -0,0 +1,35 @@
+<apex:page standardController="Opportunity" extensions="OpportunityMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    //blockme();
+    window.open('/apex/OpportunityMessagePopUp?raid=' + '{!URLENCODE(Opportunity.Id)}',
+                'OpportunityNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+}
+
+function reloadjs() {
+    //blockme();
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="鐣欒█" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!ra.OCN_Internal_Notes__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityMessage.page-meta.xml b/scr/pages/OpportunityMessage.page-meta.xml
new file mode 100644
index 0000000..466a40f
--- /dev/null
+++ b/scr/pages/OpportunityMessage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityMessage</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityMessagePopUp.page b/scr/pages/OpportunityMessagePopUp.page
new file mode 100644
index 0000000..609fd4d
--- /dev/null
+++ b/scr/pages/OpportunityMessagePopUp.page
@@ -0,0 +1,51 @@
+<apex:page Controller="OpportunityMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.Opportunity.fields.OCN_Internal_Notes__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="鐣欒█" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra1.OCN_Internal_Notes__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityMessagePopUp.page-meta.xml b/scr/pages/OpportunityMessagePopUp.page-meta.xml
new file mode 100644
index 0000000..de4944a
--- /dev/null
+++ b/scr/pages/OpportunityMessagePopUp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityMessagePopUp</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityOpenAlert.page b/scr/pages/OpportunityOpenAlert.page
new file mode 100644
index 0000000..cd8f0a3
--- /dev/null
+++ b/scr/pages/OpportunityOpenAlert.page
@@ -0,0 +1,119 @@
+<apex:page standardController="Opportunity" showHeader="false" sidebar="false">
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        var is_new = '{!Opportunity.IsNew__c}' == 'true';
+        var approval_status = '{!Opportunity.ApprovalStatus_D__c}';
+        var productSegment = '{!Opportunity.ProductSegment__c}';
+        var recordTypeId = '{!Opportunity.RecordTypeId}';
+        
+        if (productSegment == 'BS' || productSegment == 'IE' || productSegment == 'RVI' || recordTypeId.substring(0,15) == '01228000000NJt5') {
+            if (approval_status == 'Pass' && '{!Opportunity.DealerSelectOwner__c}' != '{!Opportunity.OwnerId}') {
+                var oid = "{!Opportunity.Id}"; 
+                var uid = "{!Opportunity.OwnerId}"; 
+                
+                var rac = new sforce.SObject("Opportunity"); 
+                rac.Id = "{!Opportunity.Id}"; 
+                rac.OwnerId = '{!Opportunity.DealerSelectOwner__c}';
+                var result = sforce.connection.update([rac]); 
+                var messages = getConnectDMLErrorMessages(result); 
+                if (messages.length > 0) { 
+                    alert(messages.join("\n")); 
+                } else {
+                    var rs = sforce.apex.execute("OpportunityWebService", "UpdateShare", {opportunityId: oid, userId: uid});
+                    if (rs == '1') {
+                        window.top.location.reload();
+                    } else {
+                        alert(rs);
+                    }
+                }
+            }
+        } else {
+            var now_status = '{!Opportunity.Amount_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Budget_Amount_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Cancel_Reason_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Cancel_reason_IsChangedc__c}' == 'true' || 
+                                '{!Opportunity.CloseDate_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Company_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product2_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product3_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product4_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product5_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product6_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product7_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product8_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code2_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code3_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code4_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code5_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code6_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code7_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Competitor_Product_Code8_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Dealer_Sales_Staff_Name_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Dealer_Service_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Expected_delivery_date_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Expected_Order_Date_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Inquiry_result_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Inquiry_result_cancel_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Inquiry_result_lost_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Inquiry_result_order_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.LeadSource_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Lost_competitor_product_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Lost_Reason_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Lost_reason_IsChangedc__c}' == 'true' || 
+                                '{!Opportunity.New_Inquiry_Date_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Phase1Date_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Phase2Date_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Phase3Date_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Sales_Channel_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Sub_Dealer_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Trade_Type_IsChanged__c}' == 'true' || 
+                                '{!Opportunity.Sub_Dealer_IsChanged__c}' == 'true';
+            if ((is_new || now_status) && approval_status != 'Submit') {
+                //alert("鏂板缓鎴栦慨鏀硅浠蜂俊鎭悗锛岃鍙婃椂鎻愪氦瀹℃壒銆�");
+            }
+        }
+        var syncquo = '{!Opportunity.SyncedQuote_No__c}';
+        var uploadquo = '{!Opportunity.the_Upload_of_quotation_number__c}';
+        if (uploadquo != '' && uploadquo != syncquo) {
+            alert("鍚屾鐨勬姤浠峰拰鏈�杩戜笂浼犵殑鎶ヤ环涓嶄竴鑷达紝璇蜂笂浼犲綋鍓嶅悓姝ョ殑鎶ヤ环銆�");
+        }
+
+
+function getConnectDMLErrorMessages(results) { 
+var messages = [], 
+i = 0, 
+len = results.length, 
+r; 
+for (; i < len; i++) { 
+r = results[i]; 
+if (! r.getBoolean("success")) { 
+messages = messages.concat(getConnectDMLMessagesOfAResult(r)); 
+} 
+} 
+return messages; 
+}; 
+function getConnectDMLMessagesOfAResult(res) { 
+var messages = [], 
+errors = res.getArray("errors"), 
+i = 0, 
+len = errors.length, 
+e; 
+for (; i < len; i++) { 
+e = errors[i]; 
+messages.push(e.message + " " + getConnectDMLErrorFields(e)); 
+} 
+return messages; 
+}; 
+function getConnectDMLErrorFields(error) { 
+var fields = error.getArray('fields'); 
+if (fields.length > 0) { 
+return "[" + fields.join(",") + "]" 
+} else { 
+return ""; 
+} 
+}; 
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityOpenAlert.page-meta.xml b/scr/pages/OpportunityOpenAlert.page-meta.xml
new file mode 100644
index 0000000..9e28e7d
--- /dev/null
+++ b/scr/pages/OpportunityOpenAlert.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityOpenAlert</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityPage.page b/scr/pages/OpportunityPage.page
new file mode 100644
index 0000000..1c8bdef
--- /dev/null
+++ b/scr/pages/OpportunityPage.page
@@ -0,0 +1,22 @@
+<apex:page standardController="Opportunity" showHeader="false" sidebar="false">
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        var check = '{!Opportunity.ProductInventoryCheck__c}';
+        
+        if(check != '1' && check != null && check != ''){
+            alert(check);
+            var rac = new sforce.SObject("Opportunity"); 
+            rac.Id = "{!Opportunity.Id}"; 
+            rac.ProductInventoryCheck__c = '1';
+            var result = sforce.connection.update([rac]);
+            var messages = getConnectDMLErrorMessages(result);
+            if (messages.length > 0) { 
+                alert(messages.join("\n")); 
+            } else {
+                window.top.location.reload();
+            }
+        }
+
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityPage.page-meta.xml b/scr/pages/OpportunityPage.page-meta.xml
new file mode 100644
index 0000000..678a814
--- /dev/null
+++ b/scr/pages/OpportunityPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityPage</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityProduct.page b/scr/pages/OpportunityProduct.page
new file mode 100644
index 0000000..097acb9
--- /dev/null
+++ b/scr/pages/OpportunityProduct.page
@@ -0,0 +1,484 @@
+<apex:page standardController="Opportunity" extensions="OpportunityProductController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="璇环浜у搧">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+<script>
+function saveJs() {
+    blockme();
+    saveLine();
+}
+function addJs() {
+    blockme();
+    addLine();
+}
+function deleteJs(line) {
+    blockme();
+    deleteLine(line);
+}
+function refreshPage(){
+    var errflg = j$(escapeVfId("errorflag")).value();
+    var refreshflg = j$(escapeVfId("refresh")).value();
+    var baseUrl = j$(escapeVfId("baseUrl")).value();
+    if (errflg == "false" && refreshflg == "true") {
+        window.parent.location.href = baseUrl + '/{!URLENCODE(opp.id)}';
+    }
+}
+function openSelectWindow(line, str) {
+    var baseUrl = j$(escapeVfId("baseUrl")).value();
+    var oppid = j$(escapeVfId("oppId")).value();
+    var str = j$(escapeVfId("allPage:allForm:allBlock:records:" + (line - 1) + ":product")).value();
+    window.open(baseUrl + '/apex/SearchProduct?lineno=' + line + '&val=' + encodeURIComponent(str) + '&oppId=' + encodeURIComponent(oppid) + '&openFlag=opp', 'pselect', 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+}
+function getLastLineNoNext(doc) {
+    var hasRecordFlg = false;
+    var lastLineNo = 0;
+    for(var i=99; i>=0; i--){
+        if (j$(escapeVfId('allPage:allForm:allBlock:records:' + i + ':productId')).value() != ''){
+            if (!hasRecordFlg) {
+                lastLineNo = i;
+            }
+            hasRecordFlg = true;
+        }
+    }
+    if (hasRecordFlg) {
+        lastLineNo = lastLineNo + 1 + 1;
+    }
+    return lastLineNo;
+}
+function changeLimit(i) {
+    if (j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':productId')).value() != ''){
+        var unitprice = j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':unitPrice')).value();
+        var salesprice = j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':price0')).value();
+        var ispm = j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':isProductModel')).value();
+        var isPartsdirect = j$(escapeVfId('isPartsdirect')).value();
+        var isHiddenUser = j$(escapeVfId('isHiddenUser')).value();
+        var isDealerUser = j$(escapeVfId('isDealerUser')).value();
+        var hiddenflg = j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':hiddenflg')).value();
+        //alert(ispm);
+        if (isPartsdirect == 'true' || ispm == 'true') {
+            //setTotalPrice((i - 1));
+        } else {
+            alert("涓嶈兘鎵嬪姩淇敼閿�鍞环鏍笺��");
+            if (isHiddenUser == 'true' || isDealerUser == 'true' && hiddenflg == 'true') {
+                j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':unitPrice')).val(0);
+            } else {
+                j$(escapeVfId('allPage:allForm:allBlock:records:' + (i - 1) + ':unitPrice')).val(salesprice);
+            }
+        }
+    }
+}
+function doReroadJs(line) {
+    var pname = j$(escapeVfId('allPage:allForm:allBlock:records:' + line + ':product')).value();
+    if (pname == null || pname == '') {
+        doReroad();
+    } else {
+        return;
+    }
+}
+
+function doReroad() {
+    var maxLine = {!maxLine};
+    var isHiddenAll = j$(escapeVfId('isHiddenAll')).value();
+    var tmp = "false";
+    for (var i = 0; i < maxLine; i++) {
+        var pname = j$(escapeVfId('allPage:allForm:allBlock:records:' + i + ':product')).value();
+        if (pname == null || pname == '') {
+            pname = j$(escapeVfId('allPage:allForm:allBlock:records:' + i + ':productLink')).text();
+        }
+        var phidden = j$(escapeVfId('allPage:allForm:allBlock:records:' + i + ':hiddenflg')).value();
+        if (pname != '' && phidden == "true") {
+            tmp = "true";
+            break;
+        }
+    }
+    if (isHiddenAll != tmp) {
+        blockme();
+        reloadPage(tmp);
+    }
+}
+</script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="saveLine" action="{!saveLine}" rerender="allBlock,message" onComplete="unblockUI();refreshPage();">
+        </apex:actionFunction>
+        <apex:actionFunction name="addLine" action="{!addLine}" rerender="allBlock" onComplete="unblockUI();">
+        </apex:actionFunction>
+        <apex:actionFunction name="deleteLine" action="{!deleteLine}" rerender="allBlock" onComplete="unblockUI();">
+            <apex:param name="firstParam" assignTo="{!lineNo}" value="" />
+        </apex:actionFunction>
+        <apex:actionFunction action="{!reloadPage}" name="reloadPage" reRender="allForm" oncomplete="unblockUI();">
+            <apex:param assignTo="{!is_hidden_all}" name="firstparam" value=""/>
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="saveJs();" value="淇濆瓨浜у搧" rerender="dummy" disabled="{!saveBtnDisabled}"/>
+<!--                    <apex:commandButton onclick="addJs();" value="娣诲姞琛�" rerender="dummy" disabled="{!saveBtnDisabled}"/> -->
+                        <apex:outputPanel id="message">
+                            <apex:messages />
+                        </apex:outputPanel>
+                </apex:pageBlockButtons>
+                
+                <input type="hidden" id="oppId" value="{!oppId}"/>
+                <input type="hidden" id="errorflag" value="{!errorFlag}"/>
+                <input type="hidden" id="refresh" value="{!refresh}"/>
+                <input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+                <input type="hidden" value="{!is_Parts_direct}" id="isPartsdirect"/>
+                <input type="hidden" value="{!is_hidden_user}" id="isHiddenUser"/>
+                <input type="hidden" value="{!is_dealer_user}" id="isDealerUser"/>
+                <input type="hidden" value="{!specialDealer}" id="isSpecialDealer"/>
+                <input type="hidden" value="{!is_hidden_all}" id="isHiddenAll"/>
+                <input type="hidden" value="{!is_IE}" id="isIE"/>
+
+                <apex:outputPanel layout="none" rendered="{!IF(is_IE == true, true, false)}">
+                <table class="linetable" border="0" style="border-collapse: collapse;width:1000px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                    </colgroup>
+                     <apex:outputPanel rendered="{!IF(is_NDT == true, true, false)}">
+                        <tr>
+                            <th style="text-align:center">&nbsp;</th>
+                            <th style="text-align:center">浠樻鏉′欢</th>
+                            <td style="text-align:left;" colspan="7">&nbsp;<apex:inputField style="width:90%;" id="paymentTerms" value="{!opp.IE_Payment_terms__c}"></apex:inputField></td>
+                            <th style="text-align:center">&nbsp;</th>
+                        </tr>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(is_NDT == true, false, true)}">
+                        <tr>
+                            <th style="text-align:center">&nbsp;</th>
+                            <th style="text-align:center">浠樻鏉′欢</th>
+                            <td style="text-align:left;" colspan="7">&nbsp;<apex:inputField style="width:90%;" id="paymentTerms1" value="{!opp.Payment_terms__c}"></apex:inputField></td>
+                            <th style="text-align:center">&nbsp;</th>
+                        </tr>
+                    </apex:outputPanel>
+                    <tr>
+                        <th style="text-align:center">&nbsp;</th>
+                        <th style="text-align:center">淇濅慨鏈�(骞�)</th>
+                        <td style="text-align:center"><apex:inputField style="width:90%;" id="warranty" value="{!opp.IE_Warranty__c}"></apex:inputField></td>
+                        <!-- <script type="text/javascript">
+                            j$(escapeVfId('allPage:allForm:allBlock:warranty')).attr("readonly","readonly");
+                        </script> -->
+                        <!--澶栬锤璇环浼樺寲2021-05-28 start-->
+                        <th style="text-align:center">鍥介檯璐告槗鏉′欢</th>
+                        <td style="text-align:center"><apex:inputField style="width:90%;" id="shipmentTerms" value="{!opp.IE_ShipmentTerm__c}"></apex:inputField></td>
+                        <th style="text-align:center">鍥介檯璐告槗鏉′欢2</th>
+                        <td style="text-align:center"><apex:inputField style="width:90%;" id="shipmentTerm2s" value="{!opp.IE_Shipment_Term2__c}"></apex:inputField></td>
+                        <!--澶栬锤璇环浼樺寲2021-05-28 end-->
+                        <th style="text-align:center">&nbsp;</th>
+                        <th style="text-align:center">&nbsp;</th>
+                        <th style="text-align:center">&nbsp;</th>
+                    </tr>
+                    <tr>
+                        <th style="text-align:center">&nbsp;</th>
+<!--                       <apex:outputPanel layout="none" rendered="{!IF(is_RVI == true, false, true)}"> -->
+                        <apex:outputPanel layout="none" rendered="{!IF(is_NDT == false && is_IE_direct == false, true, false)}">
+                            <th style="text-align:center">浠g悊鍟嗙郴鏁�</th>
+                            <td style="text-align:left">
+                                <apex:outputText style="width:90%;" id="discount_n" value="{0,number,###,###,##0.00}">
+                                    <apex:param value="{!dealer_coefficient}"/>
+                                </apex:outputText>
+                            </td>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(is_NDT != true, false, true)}">
+                            <th style="text-align:center">鎬讳环</th>
+                            <td style="text-align:left">
+                                <apex:outputField style="width:90%;" id="TotalPrice1" value="{!opp.Quote_TotalPrice__c}"></apex:outputField>
+                            </td>
+                        </apex:outputPanel>
+<!--                       </apex:outputPanel>
+                      <apex:outputPanel layout="none" rendered="{!IF(is_RVI == true, true, false)}">
+                        <th style="text-align:center">&nbsp;</th>
+                        <th style="text-align:center">&nbsp;</th>
+                      </apex:outputPanel> -->
+                        <th style="text-align:center">鐗规畩鎶樻墸</th>
+                        <td style="text-align:left"><apex:inputField style="width:90%;" id="discount_sp" value="{!opp.IE_Discount_Special__c}"></apex:inputField></td>
+                        <th style="text-align:center">瀹㈡埛鎬讳环</th>
+                        <td style="text-align:left"><div class="requiredInput"><div class="requiredBlock"></div>
+                        <apex:inputField style="width:90%;" id="customPrice" value="{!opp.IE_Custom_Price__c}"></apex:inputField></div></td>
+                        <th style="text-align:center">&nbsp;</th>
+                    </tr>
+                    <tr>
+                        <th style="text-align:center">&nbsp;</th>
+                        <th style="text-align:center">鎶樻墸鍓嶉噾棰�</th>
+                        <td style="text-align:left"><apex:outputField style="width:90%;" id="subtotal" value="{!opp.IE_Subtotal__c}"></apex:outputField></td>
+                        <th style="text-align:center">鏈�缁堟姌鎵g巼</th>
+                        <td style="text-align:left"><apex:outputField style="width:90%;" id="discount_f" value="{!opp.IE_Discount_final__c}"></apex:outputField></td>
+                        <th style="text-align:center">鎶樻墸鍚庨噾棰�</th>
+                        <td style="text-align:left"><apex:outputField style="width:90%;" id="totalprice" value="{!opp.Amount}"></apex:outputField></td>
+                        <th style="text-align:center">&nbsp;</th>
+                    </tr>
+                    <tr>
+                        <th style="text-align:center">&nbsp;</th>
+                        <th style="text-align:center">杩愪繚璐�</th>
+                        <td style="text-align:left"><apex:inputField style="width:90%;" id="shippinghandling" value="{!opp.IE_ShippingHandling__c}"></apex:inputField></td>
+                        <th style="text-align:center">鍥藉唴鎴愭湰閲戦</th>
+                        <td style="text-align:left"><apex:inputField style="width:90%;" id="localcost" value="{!opp.IE_local_cost__c}"></apex:inputField></td>
+                    <apex:outputPanel layout="none" rendered="{!IF(is_IE_direct == true, false, true)}">
+                        <th style="text-align:center">浠g悊鍟嗗埄娑﹂</th>
+                        <td style="text-align:left"><apex:outputField style="width:90%;" id="profit" value="{!opp.IE_dealer_profit__c}"></apex:outputField></td>
+                        <th style="text-align:center">浠g悊鍟嗗埄娑︾巼</th>
+                        <td style="text-align:left"><apex:outputField style="width:90%;" id="profitprecent" value="{!opp.IE_dealer_profit_percent__c}"></apex:outputField></td>
+                    </apex:outputPanel>
+                        <th style="text-align:center">&nbsp;</th>
+                    </tr>
+                </table>
+                </apex:outputPanel>
+                
+                <apex:outputPanel layout="none" rendered="{!IF(is_IE == true, false, true)}">
+                    <apex:outputPanel layout="none" rendered="{!IF(specialDealer == true, false , true)}">
+                        <table class="linetable" border="0" style="border-collapse: collapse;width:1000px;table-layout:fixed;">
+                            <colgroup>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                            </colgroup>
+                            <tr>
+                                <th style="text-align:center">&nbsp;</th>
+                                <th style="text-align:center">浠g悊鍟嗘姌鎵�</th>
+                                <td style="text-align:left">
+                                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                        &nbsp;
+                                    </apex:outputPanel>
+                                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                    <apex:outputText style="width:90%;" id="discount_n2" value="{0,number,###,###,##0.00}">
+                                        <apex:param value="{!dealer_coefficient}"/>
+                                    </apex:outputText>%
+                                    </apex:outputPanel>
+                                </td>
+                                <th style="text-align:center">鐗规畩鎶樻墸</th>
+                                <td style="text-align:left">
+                                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                        &nbsp;
+                                    </apex:outputPanel>
+                                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                    <apex:outputField style="width:90%;" id="discount_sp2" value="{!opp.IE_Discount_Special__c}"></apex:outputField>
+                                    </apex:outputPanel>
+                                </td>
+                                <th style="text-align:center">鏈�缁堟姌鎵g巼</th>
+                                <td style="text-align:left">
+                                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                        &nbsp;
+                                    </apex:outputPanel>
+                                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                    <apex:outputText style="width:90%;" id="discount_f2" value="{0,number,###,###,##0.00}">
+                                        <apex:param value="{!dealer_discount}"/>
+                                    </apex:outputText>%
+                                    <!-- <apex:outputField style="width:90%;" id="discount_f2" value="{!opp.dealer_discount}"></apex:outputField> -->
+                                    </apex:outputPanel>
+                                </td>
+                            </tr>
+                        </table>
+                    </apex:outputPanel>
+
+                     <apex:outputPanel layout="none" rendered="{!specialDealer}">
+                        <table class="linetable" border="0" style="border-collapse: collapse;width:1000px;table-layout:fixed;">
+                            <colgroup>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                                <col width="100"/>
+                            </colgroup>
+                            <tr>
+                                
+                                <th style="text-align:left"></th>
+                                <th style="text-align:left"></th>
+                                <th style="text-align:left">鎬讳环</th>
+                                <td style="text-align:left"><apex:inputField style="width:90%;" id="discount_sp1" value="{!opp.Amount}"></apex:inputField></td>
+                                
+                                <th style="text-align:left"></th>
+                                <th style="text-align:left"></th>
+                                <th style="text-align:left">瀹㈡埛鎬讳环</th>
+                                <apex:outputPanel layout="none" rendered="{!hasQuote}">
+                                    <td style="text-align:left"><apex:outputField style="width:90%;"  value="{!opp.Quote_CustomPrice__c}"></apex:outputField></td>
+                                </apex:outputPanel>
+                                <apex:outputPanel layout="none" rendered="{!!hasQuote}">
+                                    <td style="text-align:left"><apex:inputField style="width:90%;"  value="{!opp.IE_Custom_Price__c}"></apex:inputField></td>
+                                </apex:outputPanel>
+                            </tr>
+
+
+                        </table>
+                    </apex:outputPanel>
+                </apex:outputPanel>
+                <table class="linetable" border="0" style="border-collapse: collapse;width:'965px'};table-layout:fixed;">
+                    <tr>
+                        <td style="width: 80%;text-align: right;">鏂囦欢鍚嶇О</td>
+                        <td style="width: 10%;text-align: center;"><apex:inputText id="fileName" value="{!fileName}" style="width:90%;"/></td>
+                        <td style="width: 10%;text-align: left;"><apex:commandButton action="{!csvExport}" value="閰嶇疆瀵煎嚭"/></td>
+                    </tr>
+                </table>
+                <table class="linetable" border="1" style="border-collapse: collapse;width:'965px'};table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="180"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="80"/>
+                        <col width="100"/>
+                        <col width="80"/>
+                        <col width="180"/>
+                        <col width="60"/>
+                        <col width="60"/>
+<!--                        <col width="60"/> -->
+                    </colgroup>
+                    <tr style="background-color:#DCDCDC;">
+                        <th style="text-align:center">No.</th>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.Product_Search__c.label}</th>
+                        <apex:outputPanel layout="none" rendered="{!IF(is_NDT == true, false, true)}">
+                            <th style="text-align:center">{!$ObjectType.Product_Search__c.fields.ProductCode__c.label}</th>
+                            <th style="text-align:center">{!$ObjectType.Product_Search__c.fields.Product_ECCode__c.label}</th>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(is_NDT != true, false, true)}">
+                            <th style="text-align:center">U8 CODE</th>
+                            <th style="text-align:center">UPC CODE</th>
+                        </apex:outputPanel>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.QuantityD__c.label}</th>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.UnitPriceD__c.label}</th>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.Discount.label}</th>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.DescriptionD__c.label}</th>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.IsNew__c.label}</th>
+                        <th style="text-align:center">{!$ObjectType.OpportunityLineItem.fields.IsDelete__c.label}</th>
+<!--                        <th style="text-align:center">鎿嶄綔</th> -->
+                    </tr>
+                </table>
+                <div style="width:'990px'};height:115px;overflow:auto;">
+                    <table class="linetable" border="1" style="border-collapse: collapse;width:'965px'};table-layout:fixed;">
+                        <colgroup>
+                            <col width="25"/>
+                            <col width="180"/>
+                            <col width="100"/>
+                            <col width="100"/>
+                            <col width="80"/>
+                            <col width="100"/>
+                            <col width="80"/>
+                            <col width="180"/>
+                            <col width="60"/>
+                            <col width="60"/>
+<!--                            <col width="60"/> -->
+                        </colgroup>
+                        <apex:repeat value="{!OPInfoList}" var="OPInfo" id="records">
+                            <tr>
+                                <td align="center">
+                                    <apex:outputText id="lineno" value="{!OPInfo.LineNo}"></apex:outputText>
+                                    <apex:inputHidden id="price0" value="{!OPInfo.salesPrice}"/>
+                                    <apex:inputHidden id="hiddenflg" value="{!OPInfo.hiddenflg}"/>
+                                </td>
+                                <td align="center">
+                                    <apex:outputPanel layout="none" rendered="{!IF(OPInfo.isNew, true, false)}">
+                                        <apex:inputText style="width:90%" id="product" value="{!OPInfo.productName}" onclick="openSelectWindow({!OPInfo.LineNo});" onchange="doReroadJs('{!OPInfo.lineNo}');"></apex:inputText>
+                                    </apex:outputPanel>
+                                    <apex:outputPanel layout="none" rendered="{!IF(OPInfo.isNew, false, true)}">
+                                        <apex:outputLink id="productLink" value="{!baseUrl}/{!OPInfo.oli.Product_Search__c}" target="_blank">{!OPInfo.productName}</apex:outputLink>
+                                        <!--<a href="/production/{!OPInfo.oli.Product_Search__c}" id="" target="_blank">{!OPInfo.productName}</a>-->
+                                        <!--<apex:outputField style="width:85%" id="productR" value="{!OPInfo.oli.DealerSelectProduct__c}"></apex:outputField>-->
+                                    </apex:outputPanel>
+                                    <apex:inputHidden id="productId" value="{!OPInfo.productId}"></apex:inputHidden>
+                                </td>
+                                <td align="center">
+                                    <apex:outputText style="width:90%;" id="productCode" value="{!OPInfo.productCode}"></apex:outputText>
+                                    <apex:inputHidden id="productCodeHidden" value="{!OPInfo.productCode}"></apex:inputHidden>
+                                </td>
+                                <td align="center">
+                                    <apex:outputText style="width:90%;" id="productEC" value="{!OPInfo.productEC}"></apex:outputText>
+                                    <apex:inputHidden id="productECHidden" value="{!OPInfo.productEC}"></apex:inputHidden>
+                                </td>
+                                <td align="center"><apex:inputField style="width:90%;text-align:right;" id="quantity" value="{!OPInfo.oli.QuantityD__c}"></apex:inputField></td>
+                                <td align="center">
+                                    <apex:inputHidden id="isProductModel" value="{!OPInfo.isProductModel}"/>
+                                    <!-- "{!OPInfo.isProductModel}" -->
+                                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+
+                                        <apex:outputPanel rendered="{!AND(specialDealer ,OPInfo.isProductModel ) }" layout="none">
+                                            <apex:inputText style="width:90%;text-align:right;" id="specialDealerunitPrice" value="{!OPInfo.oli.UnitPriceD__c}" onchange="changeLimit({!OPInfo.LineNo});"/>
+                                        </apex:outputPanel>
+                                        <apex:outputPanel rendered="{!!AND(specialDealer ,OPInfo.isProductModel ) }" layout="none" >
+                                           <!-- "{!OPInfo.isProductModel}" -->
+                                           &nbsp;
+                                        </apex:outputPanel>
+                                    </apex:outputPanel>
+                                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                        <apex:inputField style="width:90%;text-align:right;" id="unitPrice" value="{!OPInfo.oli.UnitPriceD__c}" onchange="changeLimit({!OPInfo.LineNo});"></apex:inputField>
+                                    </apex:outputPanel>
+                                    <!-- <apex:inputHidden id="isProductModel" value="{!OPInfo.isProductModel}"/> -->
+                                </td>
+                                <td align="center">
+                                    <apex:outputPanel layout="none" rendered="{!IF(is_IE == true, true, false)}">
+                                        <apex:outputText style="width:90%;text-align:right;" id="discountIE" value="{!OPInfo.discount}"/>
+                                    </apex:outputPanel>
+                                    <apex:outputPanel layout="none" rendered="{!IF(is_IE == true, false, true)}">
+                                    <apex:outputPanel rendered="{!is_hidden_all}" layout="none">
+                                         &nbsp; 
+                                    </apex:outputPanel>
+                                    <apex:outputPanel rendered="{!!is_hidden_all}" layout="none">
+                                        <apex:inputText style="width:90%;text-align:right;" id="discount" value="{!OPInfo.discount}"/>
+                                    </apex:outputPanel>
+                                    </apex:outputPanel>
+                                </td>
+                                <td align="center"><apex:inputField style="width:90%" id="description" value="{!OPInfo.oli.DescriptionD__c}"></apex:inputField></td>
+                                <td align="center"><apex:outputField style="width:90%" id="isNew" value="{!OPInfo.oli.IsNew__c}"></apex:outputField></td>
+                                <td align="center">
+                                    <apex:outputPanel layout="none" rendered="{!IF(OPInfo.isNew, true, false)}">
+                                        <apex:outputField style="width:90%;" id="isDelete" value="{!OPInfo.oli.IsDelete__c}"></apex:outputField>
+                                    </apex:outputPanel>
+                                    <apex:outputPanel layout="none" rendered="{!IF(OPInfo.isNew, false, true)}">
+                                        <apex:inputField style="width:90%;" id="isDeleteR" value="{!OPInfo.oli.IsDelete__c}"></apex:inputField>
+                                    </apex:outputPanel>
+                                </td>
+<!--                                <td align="center">
+                                    <apex:outputPanel layout="none" rendered="{!IF(OPInfo.isNew, true, false)}">
+                                        <input style="width:90%;" type="button" value="鍒犻櫎" onclick="deleteJs({!OPInfo.lineNo})"/>
+                                    </apex:outputPanel>
+                                    <apex:outputPanel layout="none" rendered="{!IF(OPInfo.isNew, false, true)}">
+                                        <input style="width:90%;" type="button" value="鍒犻櫎" onclick="deleteJs({!OPInfo.lineNo})" disabled="disabled"/>
+                                    </apex:outputPanel>
+                                </td> -->
+                            </tr>
+                        </apex:repeat>
+                    </table>
+                </div>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+     <apex:form id="fileForm">
+        <apex:outputPanel rendered="{!errorflag}" layout="none">
+            <table width="100%">
+                <tr>
+                    <td align="left"><div class="errorMsg">{!errorMessage}</div></td>
+                </tr>
+            </table>
+        </apex:outputPanel>
+        <table border="0">
+            <tr>
+                <th>浜у搧瀵煎叆锛�</th>
+                <th>1.<apex:inputFile value="{!contentFile}" filename="{!nameFile}"/></th>
+            </tr>
+            <tr>
+                <th>&nbsp;</th>
+                <th>2.&nbsp;<apex:commandButton action="{!csvRead}" value="璇诲彇CSV"/></th>
+            </tr>
+        </table>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityProduct.page-meta.xml b/scr/pages/OpportunityProduct.page-meta.xml
new file mode 100644
index 0000000..77bb6bb
--- /dev/null
+++ b/scr/pages/OpportunityProduct.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OpportunityProduct</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityVisitNotes.page b/scr/pages/OpportunityVisitNotes.page
new file mode 100644
index 0000000..9663980
--- /dev/null
+++ b/scr/pages/OpportunityVisitNotes.page
@@ -0,0 +1,41 @@
+<apex:page standardController="Opportunity" extensions="OpportunityVisitNotesController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    //blockme();
+    if ('{!usertype}' == 'PowerPartner'){
+    window.open('/production/apex/OpportunityVisitNotesPopUp?raid=' + '{!URLENCODE(Opportunity.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    } else{
+    window.open('/apex/OpportunityVisitNotesPopUp?raid=' + '{!URLENCODE(Opportunity.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    }
+}
+
+function reloadjs() {
+    //blockme();
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="璁板綍" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!ra.Visit_Notes__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityVisitNotes.page-meta.xml b/scr/pages/OpportunityVisitNotes.page-meta.xml
new file mode 100644
index 0000000..70e30a9
--- /dev/null
+++ b/scr/pages/OpportunityVisitNotes.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>璇环鎷滆璁板綍涓荤獥鍙�</description>
+    <label>OpportunityVisitNotes</label>
+</ApexPage>
diff --git a/scr/pages/OpportunityVisitNotesPopUp.page b/scr/pages/OpportunityVisitNotesPopUp.page
new file mode 100644
index 0000000..31d975f
--- /dev/null
+++ b/scr/pages/OpportunityVisitNotesPopUp.page
@@ -0,0 +1,51 @@
+<apex:page Controller="OpportunityVisitNotesController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.Opportunity.fields.Visit_Notes__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="淇濆瓨" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra1.Visit_Notes__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OpportunityVisitNotesPopUp.page-meta.xml b/scr/pages/OpportunityVisitNotesPopUp.page-meta.xml
new file mode 100644
index 0000000..100ddcc
--- /dev/null
+++ b/scr/pages/OpportunityVisitNotesPopUp.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>璇环鎷滆璁板綍寮瑰嚭绐楀彛</description>
+    <label>OpportunityVisitNotesPopUp</label>
+</ApexPage>
diff --git a/scr/pages/OrderApproveAlert.page b/scr/pages/OrderApproveAlert.page
new file mode 100644
index 0000000..14cf775
--- /dev/null
+++ b/scr/pages/OrderApproveAlert.page
@@ -0,0 +1,21 @@
+<apex:page standardController="Order" showHeader="false" sidebar="false">
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+      
+        var approval_status = '{!Order.ApproveStatus__c}';
+        var userid = sforce.connection.getUserInfo().userId;
+        
+        if (approval_status == 'Submit' && ('{!Order.IE_SP1_D__c}' == 'true' || '{!Order.IE_SP7_D__c}' == 'true')
+        && userid == '00528000000YVEpAAO' && '{!Order.Is_IE_Special_BusinessApproved__c}' == 'false') {
+            alert("璇风‘璁ゆ槸鍚﹂渶瑕佷笟鍔¢儴瀹℃壒銆�");
+            
+        } 
+        
+        if (approval_status == 'Submit' && ('{!Order.IE_SP1_D__c}' == 'true' || '{!Order.IE_SP7_D__c}' == 'true')
+        && userid == '00528000000YVEpAAO' && '{!Order.Is_IE_Special_BusinessApproved__c}' == 'true') {
+            alert("璇锋鏌ヤ笟鍔¢儴鎵�濉埄鐩婅绠楃浉鍏冲唴瀹广��");
+            
+        }       
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderApproveAlert.page-meta.xml b/scr/pages/OrderApproveAlert.page-meta.xml
new file mode 100644
index 0000000..48c44b6
--- /dev/null
+++ b/scr/pages/OrderApproveAlert.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>IE鐗规畩鍚堝悓锛屽綋闄堝畤椋炲鎵规椂锛屽鏋滈�夋嫨浜�1锛�4鐗规畩鏉′欢锛屾彁閱掓槸鍚﹂渶瑕佷笟鍔¢儴瀹℃壒</description>
+    <label>OrderApproveAlert</label>
+</ApexPage>
diff --git a/scr/pages/OrderApproveAlert2.page b/scr/pages/OrderApproveAlert2.page
new file mode 100644
index 0000000..5faaceb
--- /dev/null
+++ b/scr/pages/OrderApproveAlert2.page
@@ -0,0 +1,9 @@
+<apex:page standardController="Order" showHeader="false" sidebar="false">
+    <script type="text/javascript">
+        var status = '{!Order.Status__c}';
+        var approval_status = '{!Order.ApproveStatus__c}';
+        if (status == 'Inactive' && (approval_status == 'Submit' || approval_status == 'OrderSubmit')) {
+            alert("鍚堝悓宸插け鏁堬紝璇烽┏鍥�");
+        }
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderApproveAlert2.page-meta.xml b/scr/pages/OrderApproveAlert2.page-meta.xml
new file mode 100644
index 0000000..df1f228
--- /dev/null
+++ b/scr/pages/OrderApproveAlert2.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderApproveAlert2</label>
+</ApexPage>
diff --git a/scr/pages/OrderCSVExport.page b/scr/pages/OrderCSVExport.page
new file mode 100644
index 0000000..08b632a
--- /dev/null
+++ b/scr/pages/OrderCSVExport.page
@@ -0,0 +1,7 @@
+<apex:page standardController="Order" extensions="NewOrderController" cache="true" contentType="text/csv;charset=utf-8;#{!fileName}.csv" language="zh-CN">"濂楄","浜у搧code","浜у搧鍚嶇О","鏁伴噺","OCSM鎶樻墸"
+    <apex:variable value="{!1}" var="line" />
+    <apex:repeat value="{!csv_activities}" var="item">
+"{!item.Set__c}","{!item.PriceBookEntry.Product2.ProductCode}","{!item.PriceBookEntry.Product2.Name}","{!item.Quantity}","{!item.Discount__c}"
+    <apex:variable value="{!line + 1}" var="line" />
+    </apex:repeat>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderCSVExport.page-meta.xml b/scr/pages/OrderCSVExport.page-meta.xml
new file mode 100644
index 0000000..2b8dc3d
--- /dev/null
+++ b/scr/pages/OrderCSVExport.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderCSVExport</label>
+</ApexPage>
diff --git a/scr/pages/OrderContract.page b/scr/pages/OrderContract.page
new file mode 100644
index 0000000..2d7904c
--- /dev/null
+++ b/scr/pages/OrderContract.page
@@ -0,0 +1,746 @@
+<apex:page controller="OrderPdfController" showHeader="false" sidebar="false" action="{!init}" id="allPage">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        function savejs() {
+            blockme();
+            savebtn();
+        }
+        function printjs(){
+            blockme();
+            printbtn();
+        }
+        function setNotifyFlag() {
+            var NotifyFlag = j$(escapeVfId('allPage:allForm:NotifyBlock:NotifyFlag')).val();
+            var PDF_N_NotifyParty = '';
+            var PDF_NOTIFY_PARTY = '';
+            var PDF_N_Address = '';
+            var PDF_N_Add = '';
+            var PDF_N_TEL = '';
+            var PDF_N_FAX = '';
+            var PDF_N_CONTACT = '';
+            var PDF_N_CONTACTPERSON = '';
+            if (NotifyFlag == '鏈�缁堢敤鎴�') {
+                PDF_N_NotifyParty = j$(escapeVfId('PDF_N_NotifyParty1')).val();
+                PDF_NOTIFY_PARTY = j$(escapeVfId('PDF_NOTIFY_PARTY1')).val();
+                PDF_N_Address = j$(escapeVfId('PDF_N_Address1')).val();
+                PDF_N_Add = j$(escapeVfId('PDF_N_Add1')).val();
+                PDF_N_TEL = j$(escapeVfId('PDF_N_TEL1')).val();
+                PDF_N_FAX = j$(escapeVfId('PDF_N_FAX1')).val();
+                PDF_N_CONTACT = j$(escapeVfId('PDF_N_CONTACT1')).val();
+                PDF_N_CONTACTPERSON = j$(escapeVfId('PDF_N_CONTACTPERSON1')).val();
+            } else if (NotifyFlag == '鏀惰揣浜�') {
+                PDF_N_NotifyParty = j$(escapeVfId('allPage:allForm:ConsigneeBlock:the_C_Consignee')).val();
+                PDF_NOTIFY_PARTY = j$(escapeVfId('allPage:allForm:ConsigneeBlock:the_Consignee')).val();
+                PDF_N_Address = j$(escapeVfId('allPage:allForm:ConsigneeBlock:C_Cadd')).val();
+                PDF_N_Add = j$(escapeVfId('allPage:allForm:ConsigneeBlock:Cadd')).val();
+                PDF_N_TEL = j$(escapeVfId('allPage:allForm:ConsigneeBlock:C_TEL')).val();
+                PDF_N_FAX = j$(escapeVfId('allPage:allForm:ConsigneeBlock:C_FAX')).val();
+                PDF_N_CONTACT = j$(escapeVfId('allPage:allForm:ConsigneeBlock:C_CONTACT')).val();
+                PDF_N_CONTACTPERSON = j$(escapeVfId('allPage:allForm:ConsigneeBlock:Cconperson')).val();
+            }
+            j$(escapeVfId('allPage:allForm:NotifyBlock:NotifyParty')).val(PDF_N_NotifyParty);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:BS_NotifyPartys')).val(PDF_NOTIFY_PARTY);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:Naddress')).val(PDF_N_Address);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:BS_Nadds')).val(PDF_N_Add);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:BS_Ntel')).val(PDF_N_TEL);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:BS_Nfax')).val(PDF_N_FAX);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:Ncontact')).val(PDF_N_CONTACT);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:BS_Nconperson')).val(PDF_N_CONTACTPERSON);
+
+            j$(escapeVfId('allPage:allForm:NotifyBlock:NotifyPartys')).val(PDF_NOTIFY_PARTY);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:Nadds')).val(PDF_N_Add);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:Ntel')).val(PDF_N_TEL);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:Nfax')).val(PDF_N_FAX);
+            j$(escapeVfId('allPage:allForm:NotifyBlock:Nconperson')).val(PDF_N_CONTACTPERSON);
+        }
+        function setForwarFlag() {
+            var ForwarFlag = j$(escapeVfId('allPage:allForm:ForwarBlock:ForwarFlag')).val();
+            var PDF_Forwarder = '';
+            var PDF_F_Add = '';
+            var PDF_F_TEL = '';
+            var PDF_F_FAX = '';
+            var PDF_F_ContactPerson = '';
+            if (ForwarFlag == '鏈�缁堢敤鎴�') {
+                PDF_Forwarder = j$(escapeVfId('PDF_Forwarder1')).val();
+                PDF_F_Add = j$(escapeVfId('PDF_F_Add1')).val();
+                PDF_F_TEL = j$(escapeVfId('PDF_F_TEL1')).val();
+                PDF_F_FAX = j$(escapeVfId('PDF_F_FAX1')).val();
+                PDF_F_ContactPerson = j$(escapeVfId('PDF_F_ContactPerson1')).val();
+            } else if (ForwarFlag == '鏀惰揣浜�') {
+                PDF_Forwarder = j$(escapeVfId('PDF_Forwarder2')).val();
+                PDF_F_Add = j$(escapeVfId('PDF_F_Add2')).val();
+                PDF_F_TEL = j$(escapeVfId('PDF_F_TEL2')).val();
+                PDF_F_FAX = j$(escapeVfId('PDF_F_FAX2')).val();
+                PDF_F_ContactPerson = j$(escapeVfId('PDF_F_ContactPerson2')).val();
+            }
+            j$(escapeVfId('allPage:allForm:ForwarBlock:Forwarder')).val(PDF_Forwarder);
+            j$(escapeVfId('allPage:allForm:ForwarBlock:F_Add')).val(PDF_F_Add);
+            j$(escapeVfId('allPage:allForm:ForwarBlock:F_TEL')).val(PDF_F_TEL);
+            j$(escapeVfId('allPage:allForm:ForwarBlock:F_FAX')).val(PDF_F_FAX);
+            j$(escapeVfId('allPage:allForm:ForwarBlock:F_ContactPerson')).val(PDF_F_ContactPerson);
+        }
+    </script>
+    <style type="text/css">
+        table {
+            border-color: grey;
+        }
+        td {
+            align :left;
+            width:300px;
+        }
+        .dateFormat {
+            display: none;
+        }
+    </style>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" rerender="allForm,message" action="{!saveBtn}" onComplete="unblockUI();" />
+        <apex:actionFunction name="printbtn" rerender="allForm,message" action="{!printBtn}"  onComplete="unblockUI();"/>
+        <apex:outputPanel id="message">
+            <apex:pageMessages />
+        </apex:outputPanel>
+        <apex:pageBlock id="contractBlock" tabStyle="Order" title="鍚堝悓淇℃伅">
+            <input type="hidden" id="PDF_N_NotifyParty1" value="{!PDF_N_NotifyParty1}"/>
+            <input type="hidden" id="PDF_NOTIFY_PARTY1" value="{!PDF_NOTIFY_PARTY1}"/>
+            <input type="hidden" id="PDF_N_Address1" value="{!PDF_N_Address1}"/>
+            <input type="hidden" id="PDF_N_Add1" value="{!PDF_N_Add1}"/>
+            <input type="hidden" id="PDF_N_TEL1" value="{!PDF_N_TEL1}"/>
+            <input type="hidden" id="PDF_N_FAX1" value="{!PDF_N_FAX1}"/>
+            <input type="hidden" id="PDF_N_CONTACT1" value="{!PDF_N_CONTACT1}"/>
+            <input type="hidden" id="PDF_N_CONTACTPERSON1" value="{!PDF_N_CONTACTPERSON1}"/>
+
+            <input type="hidden" id="PDF_N_NotifyParty2" value="{!PDF_N_NotifyParty2}"/>
+            <input type="hidden" id="PDF_NOTIFY_PARTY2" value="{!PDF_NOTIFY_PARTY2}"/>
+            <input type="hidden" id="PDF_N_Address2" value="{!PDF_N_Address2}"/>
+            <input type="hidden" id="PDF_N_Add2" value="{!PDF_N_Add2}"/>
+            <input type="hidden" id="PDF_N_TEL2" value="{!PDF_N_TEL2}"/>
+            <input type="hidden" id="PDF_N_FAX2" value="{!PDF_N_FAX2}"/>
+            <input type="hidden" id="PDF_N_CONTACT2" value="{!PDF_N_CONTACT2}"/>
+            <input type="hidden" id="PDF_N_CONTACTPERSON2" value="{!PDF_N_CONTACTPERSON2}"/>
+
+            <input type="hidden" id="PDF_Forwarder1" value="{!PDF_Forwarder1}"/>
+            <input type="hidden" id="PDF_F_Add1" value="{!PDF_F_Add1}"/>
+            <input type="hidden" id="PDF_F_TEL1" value="{!PDF_F_TEL1}"/>
+            <input type="hidden" id="PDF_F_FAX1" value="{!PDF_F_FAX1}"/>
+            <input type="hidden" id="PDF_F_ContactPerson1" value="{!PDF_F_ContactPerson1}"/>
+
+            <input type="hidden" id="PDF_Forwarder2" value="{!PDF_Forwarder2}"/>
+            <input type="hidden" id="PDF_F_Add2" value="{!PDF_F_Add2}"/>
+            <input type="hidden" id="PDF_F_TEL2" value="{!PDF_F_TEL2}"/>
+            <input type="hidden" id="PDF_F_FAX2" value="{!PDF_F_FAX2}"/>
+            <input type="hidden" id="PDF_F_ContactPerson2" value="{!PDF_F_ContactPerson2}"/>
+
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: right;">鍚堝悓鍚�:</th>
+                    <td align="left"><apex:inputField id="OrderName" value="{!od.Name}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鍚堝悓鍙�:</th>
+                    <td align="left"><apex:inputField id="OrderId" value="{!od.PDF_Order_No__c}"/></td>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">鎶ュ鍗曞彿:</th>
+                    <td align="left"><apex:inputField id="Report" value="{!od.PDF_I_Report__c}"/></td>
+                    </apex:outputPanel>
+                </tr>
+                <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI'&& Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">绛捐鍦扮偣(涓�):</th>
+                    <td align="left"><apex:inputField id="SignaturePlace" value="{!od.PDF_SignaturePlace__c}"/></td>
+                    <th style="text-align: right;">绛捐鍦扮偣(鑻�):</th>
+                    <td align="left"><apex:inputField id="SignaturePlaces" value="{!od.PDF_SignaturePlaces__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+                <tr>
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">绛捐鏃ユ湡:</th>
+                    <td><apex:inputField id="SignatureDate" value="{!od.PDF_SignatureDate__c}"/></td>
+                    </apex:outputPanel>
+                    <th style="text-align: right;">浜よ揣鏈�:</th>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'true', 'false')}" layout="none">
+                        <td><apex:inputField id="DeliveryTimeText" value="{!od.DeliveryTimeText__c}"/></td>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'false', 'true')}" layout="none">
+                        <td><apex:outputField id="DeliveryTimeText1" value="{!od.DeliveryTimeText__c}"/></td>
+                    </apex:outputPanel>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">&nbsp;</th>
+                    <td>&nbsp;</td>
+                    <th style="text-align: right;">浜よ揣鏈�(鑻�):</th>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'true', 'false')}" layout="none">
+                        <td><apex:inputField id="DeliveryTimeTextEn" value="{!od.DeliveryTimeTextEn__c}"/></td>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'false', 'true')}" layout="none">
+                        <td><apex:outputField id="DeliveryTimeTextEn1" value="{!od.DeliveryTimeTextEn__c}"/></td>
+                    </apex:outputPanel>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鎬讳环:</th>
+                    <td>
+                        <apex:outputText value="{0, number, ##0.00}">
+                            <apex:param value="{!TotalMoney}" />
+                        </apex:outputText>
+                    </td>
+                    <th style="text-align: right;">Total price(鑻�):</th>
+                    <td><apex:inputField id="TotalpriceE" value="{!od.Total_price_E__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">浠樻鏂瑰紡:</th>
+                    <td><apex:inputField id="PaymentTerms" value="{!od.PDF_PaymentTerms__c}" style="width:95%"/></td>
+                    <th style="text-align: right;">PaymentTerms(鑻�):</th>
+                    <td><apex:inputField id="PaymentTermsE" value="{!od.PDF_PaymentTerms_E__c}" style="width:95%"/></td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="BuyerBlock" tabStyle="Order" title="涔版柟">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">涔版柟ADD (鑻辨枃):</th>
+                    <td><apex:inputField id="BS_B_Add" value="{!od.PDF_B_Add__c}"/></td>
+                    <th style="text-align: right;">涔版柟CONTACT PERSON (鑻辨枃):</th>
+                    <td><apex:inputField id="BS_B_contactperson" value="{!od.PDF_B_contactperson__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">涔版柟ADD (鑻辨枃):</th>
+                    <td><apex:inputField id="IE_B_Add" value="{!od.PDF_B_Add__c}"/></td>
+                    <th style="text-align: right;">涔版柟CONTACT PERSON (鑻辨枃):</th>
+                    <td><apex:inputField id="IE_B_contactperson" value="{!od.PDF_B_contactperson__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">涔版柟绉戝/閮ㄩ棬(鑻辨枃):</th>
+                    <td><apex:inputField id="BS_B_Department" value="{!od.PDF_B_Department__c}"/></td>
+                    <th style="text-align: right;">&nbsp;</th>
+                    <td>&nbsp;</td>
+                </tr>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">涔版柟鐢ㄦ埛灞炴��:</th>
+                    <td><apex:inputField id="IE_B_Attri" value="{!od.PDF_B_Attri__c}"/></td>
+                    <th style="text-align: right;">&nbsp;</th>
+                    <td>&nbsp;</td>
+                </tr>
+                </apex:outputPanel>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="SellerBlock" tabStyle="Order" title="鍗栨柟">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') &&Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">鍗栨柟:</th>
+                    <td><apex:inputField id="BS_seller" value="{!od.PDF_SELLER__c}"/></td>
+                    <th style="text-align: right;">鍗栨柟鍦板潃 (涓枃):</th>
+                    <td><apex:inputField id="BS_Sadds" value="{!od.PDF_S_Adds__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鐢佃瘽 (TEL):</th>
+                    <td><apex:inputField id="BS_Stel" value="{!od.PDF_S_TEL__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IEW') && Opp.TradeType__c = 'Tax Exemption' , 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">鍗栨柟:</th>
+                    <td><apex:inputField id="IE_seller" value="{!od.PDF_SELLER__c}"/></td>
+                    <th style="text-align: right;">THE SELLER (鑻辨枃):</th>
+                    <td><apex:inputField id="IE_the_seller" value="{!od.PDF_THE_SELLER__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鍗栨柟鍦板潃 (涓枃):</th>
+                    <td><apex:inputField id="IE_Sadds" value="{!od.PDF_S_Adds__c}"/></td>
+                    <th style="text-align: right;">鍗栨柟ADD (鑻辨枃):</th>
+                    <td><apex:inputField id="IE_Saddress" value="{!od.PDF_S_Address__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI'|| Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">鍗栨柟:</th>
+                    <td><apex:outputText id="seller" value="{!od.PDF_SELLER__c}"/></td>
+                    <th style="text-align: right;">THE SELLER (鑻辨枃):</th>
+                    <td><apex:outputText id="the_seller" value="{!od.PDF_THE_SELLER__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鍗栨柟鍦板潃 (涓枃):</th>
+                    <td><apex:outputText id="Sadds" value="{!od.PDF_S_Adds__c}"/></td>
+                    <th style="text-align: right;">鍗栨柟ADD (鑻辨枃):</th>
+                    <td><apex:outputText id="Saddress" value="{!od.PDF_S_Address__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鐢佃瘽 (TEL):</th>
+                    <td><apex:outputText id="Stel" value="{!od.PDF_S_TEL__c}"/></td>
+                    <th style="text-align: right;">浼犵湡 (FAX):</th>
+                    <td><apex:outputText id="Sfax" value="{!od.PDF_S_FAX__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">Bank Name:</th>
+                    <td><apex:outputText id="Sbank" value="{!od.PDF_S_Bank_Name__c}"/></td>
+                    <th style="text-align: right;">Branch:</th>
+                    <td><apex:outputText id="Sbranch" value="{!od.PDF_S_Branch__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">Address:</th>
+                    <td><apex:outputText id="SbankAddress" value="{!od.PDF_S_Bank_Address__c}"/></td>
+                    <th style="text-align: right;">Account No:</th>
+                    <td><apex:outputText id="Saccount" value="{!od.PDF_S_Account_No__c}"/></td>
+                </tr>
+                <tr>
+                    
+                    <th style="text-align: right;">Swift Code:</th>
+                    <td><apex:outputText id="Sswift" value="{!od.PDF_S_Swift_Code__c}"/></td>
+                    <th style="text-align: right;">Account Name:</th>
+                    <td><apex:outputText id="SaccName" value="{!od.PDF_S_Account_Name__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="ConsigneeBlock" tabStyle="Order" title="鏀惰揣浜�">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                 <tr>
+                    <th style="text-align: right;">鏀惰揣浜�:</th>
+                    <td><apex:inputField id="the_C_Consignee" value="{!od.PDF_C_Consignee__c}"/></td>
+                    <th style="text-align: right;">THE CONSIGNEE (鑻辨枃):</th>
+                    <td><apex:inputField id="the_Consignee" value="{!od.PDF_C_THECONSIGNE__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鍦板潃:</th>
+                    <td><apex:inputField id="C_Cadd" value="{!od.PDF_C_Address__c}"/></td>
+                    <th style="text-align: right;">ADD (鑻辨枃):</th>
+                    <td><apex:inputField id="Cadd" value="{!od.PDF_C_Add__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鐢佃瘽锛圱el锛�:</th>
+                    <td><apex:inputField id="C_TEL" value="{!od.PDF_C_TEL__c}"/></td>
+                    <th style="text-align: right;">浼犵湡锛團ax锛�:</th>
+                    <td><apex:inputField id="C_FAX" value="{!od.PDF_C_FAX__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鑱旂郴浜�:</th>
+                    <td><apex:inputField id="C_CONTACT" value="{!od.PDF_C_CONTACT__c}"/></td>
+                    <th style="text-align: right;">CONTACT PERSON (鑻辨枃):</th>
+                    <td><apex:inputField id="Cconperson" value="{!od.PDF_C_contactperson__c}"/></td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+
+        <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+        <apex:pageBlock id="NotifyBlock" tabStyle="Order" title="閫氱煡浜�">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: right;">閫氱煡浜洪�夋嫨:</th>
+                    <td><apex:inputField id="NotifyFlag" value="{!od.PDF_NotifyFlag__c}" onchange="setNotifyFlag();"/></td>
+                </tr>
+                <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' || Opp.ProductSegment__c = 'IE'|| Opp.ProductSegment__c = 'RVI', 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">閫氱煡浜� (涓枃):</th>
+                    <td><apex:inputField id="NotifyParty" value="{!od.PDF_N_NotifyParty__c}"/></td>
+                    <th style="text-align: right;">THE NOTIFY PARTY (鑻辨枃):</th>
+                    <td><apex:inputField id="BS_NotifyPartys" value="{!od.PDF_NOTIFY_PARTY__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鍦板潃 (涓枃):</th>
+                    <td><apex:inputField id="Naddress" value="{!od.PDF_N_Address__c}"/></td>
+                    <th style="text-align: right;">閫氱煡浜篈DD (鑻辨枃):</th>
+                    <td><apex:inputField id="BS_Nadds" value="{!od.PDF_N_Add__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鐢佃瘽 (TEL):</th>
+                    <td><apex:inputField id="BS_Ntel" value="{!od.PDF_N_TEL__c}"/></td>
+                    <th style="text-align: right;">浼犵湡 (FAX):</th>
+                    <td><apex:inputField id="BS_Nfax" value="{!od.PDF_N_FAX__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鑱旂郴浜� (涓枃):</th>
+                    <td><apex:inputField id="Ncontact" value="{!od.PDF_N_CONTACT__c}"/></td>
+                    <th style="text-align: right;">CONTACT PERSON (鑻辨枃):</th>
+                    <td><apex:inputField id="BS_Nconperson" value="{!od.PDF_N_CONTACTPERSON__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+                <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'QWE' , 'true', 'false')}" layout="none">
+                <tr>
+                    <th style="text-align: right;">THE NOTIFY PARTY (鑻辨枃):</th>
+                    <td><apex:inputField id="NotifyPartys" value="{!od.PDF_NOTIFY_PARTY__c}"/></td>
+                    <th style="text-align: right;">閫氱煡浜篈DD (鑻辨枃):</th>
+                    <td><apex:inputField id="Nadds" value="{!od.PDF_N_Add__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鐢佃瘽 (TEL):</th>
+                    <td><apex:inputField id="Ntel" value="{!od.PDF_N_TEL__c}"/></td>
+                    <th style="text-align: right;">浼犵湡 (FAX):</th>
+                    <td><apex:inputField id="Nfax" value="{!od.PDF_N_FAX__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">CONTACT PERSON (鑻辨枃):</th>
+                    <td><apex:inputField id="Nconperson" value="{!od.PDF_N_CONTACTPERSON__c}"/></td>
+                </tr>
+                </apex:outputPanel>
+            </table>
+        </apex:pageBlock>
+        </apex:outputPanel>
+
+        <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+        <apex:pageBlock id="ForwarBlock" tabStyle="Order" title="杞繍鍟�">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: right;">杞繍鍟嗛�夋嫨:</th>
+                    <td><apex:inputField id="ForwarFlag" value="{!od.PDF_ForwarFlag__c}" onchange="setForwarFlag();"/></td></tr>
+                <tr>
+                    <th style="text-align: right;">杞繍鍟� (鑻辨枃):</th>
+                    <td><apex:inputField id="Forwarder" value="{!od.PDF_Forwarder__c}"/></td>
+                    <th style="text-align: right;">鍦板潃 (鑻辨枃):</th>
+                    <td><apex:inputField id="F_Add" value="{!od.PDF_F_Add__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鐢佃瘽 (TEL):</th>
+                    <td><apex:inputField id="F_TEL" value="{!od.PDF_F_TEL__c}"/></td>
+                    <th style="text-align: right;">浼犵湡 (FAX):</th>
+                    <td><apex:inputField id="F_FAX" value="{!od.PDF_F_FAX__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">鑱旂郴浜� (涓枃):</th>
+                    <td><apex:inputField id="F_ContactPerson" value="{!od.PDF_F_ContactPerson__c}"/></td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+        </apex:outputPanel>
+
+        <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+        <apex:pageBlock id="BusyerBlock" tabStyle="Order" title="涔版柟淇℃伅">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: right;">鍏徃鍚嶇О:</th>
+                    <td><apex:inputField id="BusyerCompany" value="{!od.PDF_BusyerCompany__c}"/></td>
+                    <th style="text-align: right;">涔版柟鍦板潃:</th>
+                    <td><apex:inputField id="By_Add" value="{!od.PDF_By_Add__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">涔版柟鐢佃瘽:</th>
+                    <td><apex:inputField id="By_Tel" value="{!od.PDF_By_Tel__c}"/></td>
+                    <th style="text-align: right;">&nbsp;</th>
+                    <td>&nbsp;</td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+        </apex:outputPanel>
+
+        <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+        <apex:pageBlock id="ShipmentBlock" tabStyle="Order" title="鍙戣揣淇℃伅">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <!-- <th style="text-align: right;">Shipment Term:</th>
+                    <td><apex:inputField id="Shipment" value="{!od.PDF_Sp_Shipment_Term__c}"/></td> -->
+                    <th style="text-align: right;">鐩殑鍙e哺:</th>
+                    <td><apex:inputField id="DestinationPort" value="{!od.PDF_Sp_DestinationPort__c}"/></td>
+                    <th style="text-align: right;">Port of Destination(鑻辨枃):</th>
+                    <td><apex:inputField id="DestinationPortE" value="{!od.PDF_Sp_DestinationPort_E__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">瑁呰繍鏉′欢:</th>
+                    <td><apex:inputField id="ShippingTerms" value="{!od.PDF_Sp_ShippingTerms__c}"/></td>
+                    <th style="text-align: right;">Freight:</th>
+                    <td><apex:inputField id="Freight" value="{!od.PDF_Sp_Freight__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">淇濋櫓:</th>
+                    <td><apex:inputField id="insurance" value="{!od.PDF_Sp_insurance__c}"/></td>
+                    <th style="text-align: right;">杩愯緭鏍囪瘑:</th>
+                    <td><apex:inputField id="SHIPPINGMARK" value="{!od.PDF_Sp_SHIPPINGMARK__c}" style="resize:none;width: 167px;"/></td>
+                </tr>
+                <tr>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">璐ㄩ噺淇濊瘉:</th>
+                    <td><apex:inputField id="qa" value="{!od.PDF_QA__c}"/></td>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">鐗逛环鎵瑰缂栧彿:</th>
+                    <td><apex:inputField id="SpecNo" value="{!od.PDF_G_SpecNo__c}"/></td>
+                    </apex:outputPanel>
+                </tr>
+                <tr>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">涓嶈秴杩囧彂璐ф棩鍚庣殑:</th>
+                    <td><apex:inputField id="qa2" value="{!od.PDF_QA2__c}"/></td>
+                    </apex:outputPanel>
+
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI') && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">杩愪繚璐�:</th>
+                    <td><apex:inputField id="TrAndPre1" value="{!od.PDF_G_TrAndPre__c}"/></td>
+                    </apex:outputPanel>
+
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">杩愪繚璐�:</th>
+                    <td><apex:outputField id="TrAndPre2" value="{!od.PDF_G_TrAndPre__c}"/></td>
+                    </apex:outputPanel>
+
+
+                    
+    
+                </tr>
+            </table>
+        </apex:pageBlock>
+        </apex:outputPanel>
+
+        <apex:pageBlock id="SetInfoBlock" tabStyle="Order" title="濂楄淇℃伅">
+        <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' ), 'true', 'false')}" layout="none">
+            <table width="840px" border="1" cellspacing="0" cellpadding="0" style="table-layout:fixed;">
+            <colgroup>
+                <col width="5%"/>
+                <col width="45%"/>
+                <col width="10%"/>
+                <col width="10%"/>
+                <col width="15%"/>
+                <col width="15%"/>
+            </colgroup>
+                <tr>
+                    <td style="text-align: center;">搴忓彿</td>
+                    <td style="text-align: center;">璐х墿鍚嶇О鍙婅鏍�</td>
+                    <td style="text-align: center;">鍗� 浣�</td>
+                    <td style="text-align: center;">鏁� 閲�</td>
+                    <td style="text-align: center;">鍗� 浠�</td>
+                    <td style="text-align: center;">鎬� 浠�</td>
+                </tr>
+                <tr>
+                    <td style="text-align: center;">Item</td>
+                    <td style="text-align: center;">Goods &amp; Specification</td>
+                    <td style="text-align: center;">Unit</td>
+                    <td style="text-align: center;">Qty</td>
+                    <td style="text-align: center;">Unit Price</td>
+                    <td style="text-align: center;">Total Amount</td>
+                </tr>
+
+                <apex:repeat value="{!printSetInfo}" var="set">
+                    <tr>
+                        <td style="text-align: center;"><apex:outputField value="{!set.No__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!set.Goods__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!set.Unit__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!set.Qty__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!set.UnitPrice__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputField value="{!set.Total_Amount__c}" style="width: 95%"/></td>
+                    </tr>
+                </apex:repeat>
+            </table>
+        </apex:outputPanel>
+        <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' ), 'false', 'true')}" layout="none">
+             <table width="840px" border="1" cellspacing="0" cellpadding="0" style="table-layout:fixed;">
+                <colgroup>
+                    <col width="5%"/>
+                    <col width="16%"/>
+                    <col width="20%"/>
+                    <col width="5%"/>
+                    <col width="5%"/>
+                    <col width="10%"/>
+                    <col width="5%"/>
+                    <col width="10%"/>
+                    <col width="10%"/>
+                    <col width="14%"/>
+                   <!--  <col width="12%"/> -->
+
+                </colgroup>
+                 <tr>
+                    <td style="text-align: center;">搴忓彿</td>
+                    <td style="text-align: center;">U8鍙风爜</td>
+                    <td style="text-align: center;">浜у搧鍨嬪彿</td>
+                    <td style="text-align: center;">鍗曚綅</td>
+                    <td style="text-align: center;">鏁伴噺</td>
+                    <td style="text-align: center;">鍗曚环</td>
+                    <td style="text-align: center;">鎶樻墸</td>
+                    <td style="text-align: center;">鎶樺悗鍗曚环</td>
+                    <td style="text-align: center;">鎬讳环</td>
+                    <td style="text-align: center;">澶囨敞</td>
+                   <!--  <td style="text-align: center;">浜у搧鍚嶇О</td> -->
+                </tr>
+                <tr>
+                    <td style="text-align: center;">Item</td>
+                    <td style="text-align: center;">U8</td>
+                    <td style="text-align: center;">Part Number</td>
+                    <td style="text-align: center;">Unit</td>
+                    <td style="text-align: center;">Quantity</td>
+                    <td style="text-align: center;">Unit Price</td>
+                    <td style="text-align: center;">Discount </td>
+                    <td style="text-align: center;">Discounted Price/Unit</td>
+                    <td style="text-align: center;">Total Amount</td>
+                    <td style="text-align: center;">Remark</td>
+                   <!--  <td style="text-align: center;">Name of Goods</td> -->
+                </tr>
+
+                 <apex:repeat value="{!printSetInfo}" var="set">
+                    <tr>
+                        <td style="text-align: center;"><apex:outputField value="{!set.No__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputField value="{!set.U8__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputField value="{!set.Goods__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!set.Unit__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputField value="{!set.Qty__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.UnitPrice__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputField value="{!set.discount__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputField value="{!set.discountprice__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Total_AmountNDT__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!set.Remark__c}" style="width: 95%"/></td>
+                        <!-- <td style="text-align: center;"><apex:inputField value="{!set.NameOfGood__c}" style="width: 95%"/></td> -->
+                        
+                    </tr>
+                </apex:repeat>
+            </table>
+        </apex:outputPanel>
+        </apex:pageBlock>
+
+        <apex:pageBlock id="other" title="闄勪欢淇℃伅" rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' ), 'false', 'true')}">
+
+            <table width="840px" border="1" cellspacing="0" cellpadding="0" style="table-layout:fixed;">
+                 <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <td style="text-align: center;">U8 Code</td>
+                    <td style="text-align: center;">Part Number</td>
+                    <td style="text-align: center;">Quantity</td>
+                    <td style="text-align: center;">Name of Goods</td>
+                </tr>
+                 <apex:repeat value="{!ndtList}" var="ndt">
+                    <tr>
+                        <td style="text-align: center;"><apex:inputField value="{!ndt.U8_Code__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!ndt.Part_Number__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!ndt.Quantity__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:inputField value="{!ndt.Name_of_Goods__c}" style="width: 95%; text-align: left;"/></td>
+                    </tr>
+                </apex:repeat>
+            </table>
+
+        </apex:pageBlock>
+
+
+        <apex:pageBlock id="BillBlock" tabStyle="Order" title="鍗曟嵁">
+            <table style="border-style:none;" border="0" width="840px">
+                <colgroup>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                    <col width="25%"/>
+                </colgroup>
+                <tr>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th style="text-align: right;">鎵�鏈夊崟鎹�:</th>
+                    <td><apex:inputField id="allbill" value="{!od.PDF_Bi_AllBill__c}"/></td>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <th>&nbsp;</th>
+                    <td>&nbsp;</td>
+                    </apex:outputPanel>
+                    <th style="text-align: right;">鐢熶骇鍥藉埆鍙婂埗閫犲巶鍟�:</th>
+                    <td><apex:inputField id="manufacturers" value="{!od.PDF_Bi_manufacturers__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">Total Value:</th>
+                    <td><apex:inputField id="ShipmentTerm2Text" value="{!od.PDF_Shipment_Term2_Text__c}"/></td>
+                    <th style="text-align: right;">鐢熶骇鍥藉埆鍙婂埗閫犲巶鍟�(鑻辨枃):</th>
+                    <td><apex:inputField id="manufacturersEn" value="{!od.PDF_Bi_manufacturersEn__c}"/></td>
+                </tr>
+                <tr>
+                    <th style="text-align: right;">绛惧瓧浜哄鍚�:</th>
+                    <td><apex:inputField id="signName" value="{!od.PDF_Sign_Name__c}"/></td>
+                    <th style="text-align: right;">绛惧瓧浜鸿亴浣�:</th>
+                    <td><apex:inputField id="signTitle" value="{!od.PDF_Sign_Title__c}"/></td>
+                </tr>
+                <tr>
+                    <td>&nbsp;</td>
+                </tr>
+                <tr>
+                    <td colspan ="4" style="padding-left: 50px">
+                        鎵�闇�鐨勬枃浠�: <br/>
+                        <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                        璇峰湪鍙戣揣鍚�<apex:inputField id="q1" value="{!od.PDF_Bi_q1__c}" style="width: 30px"/>涓伐浣滄棩鍐呭皢浠ヤ笅鎵�闇�鐨勬枃浠朵紶鐪�/鐢甸偖缁欎拱鏂�;<br/>
+                        </apex:outputPanel>
+                        1)&nbsp;<apex:inputField id="Quality" value="{!od.PDF_Bi_Quality__c}" style="width: 30px"/>浠界敱鍗栨柟鍑哄叿鐨勮川閲忓拰鏁伴噺璇佹槑;<br/>
+                        2)&nbsp;<apex:inputField id="Origin" value="{!od.PDF_Bi_Origin__c}" style="width: 30px"/>浠藉崠鏂瑰嚭鍏风殑鍘熶骇鍦拌瘉鏄�;鍙�<br/>
+                        3)&nbsp;<apex:inputField id="NonWooden" value="{!od.PDF_Bi_Non_Wooden__c}" style="width: 30px"/>浠介潪鏈ㄨ川鍖呰璇佹槑銆�<br/>
+
+                        <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                        4)&nbsp;绌鸿繍鎻愬崟姝f湰<apex:inputField id="airway" value="{!od.PDF_Bi_airway__c}" style="width: 30px"/>浠斤紝鍓湰<apex:inputField id="copyairway" value="{!od.PDF_Bi_copyairway__c}" style="width: 30px"/>浠姐�傚苟娉ㄦ槑鈥滆繍璐瑰凡浠樷��;<br/>
+                        5)&nbsp;鍙戠エ<apex:inputField id="invoice" value="{!od.PDF_Bi_invoice__c}" style="width: 30px"/>浠�, 娉ㄦ槑鍚堝悓鍙峰拰杩愯緭鏍囪瘑(濡傛湁涓�涓互涓婅繍杈撴爣璇�, 搴斿垎鍒嚭鍏峰彂绁�)鍙婂悎鍚屼腑鍏跺畠缁嗚妭;<br/>
+                        6)&nbsp;濡備繚闄╃敱鍗栨柟璐熻矗鐨勬儏鍐典笅锛屽崠鏂归渶鎻愪緵淇濋櫓鍗�<apex:inputField id="Insurancecount" value="{!od.PDF_Bi_Insurance__c}" style="width: 30px"/>濂楋紝鎶曚竴鍒囬櫓锛� 鎸夊彂绁ㄩ噾棰�110锛呮姇淇濅竴鍒囬櫓;<br/>
+                        7)&nbsp;<apex:inputField id="Packing" value="{!od.PDF_Bi_Packing__c}" style="width: 30px"/>浠界敱鍗栨柟鍑哄叿鐨勮绠卞崟;<br/>
+                        </apex:outputPanel>
+
+                        <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                        姝ゅ悎鍚岀敱涔板崠鍙屾柟绛剧讲姝f湰<apex:inputField id="Contract" value="{!od.PDF_Co_Contract__c}" style="width: 30px"/>銆備拱鏂规寔鏈�<apex:inputField id="BContra" value="{!od.PDF_Co_BContra__c}" style="width: 30px"/>銆傚崠鏂规寔鏈�<apex:inputField id="SContra" value="{!od.PDF_Co_SContra__c}" style="width: 30px"/>銆�<br/>
+                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+                        (鑻�)&nbsp;<apex:inputField id="ContractE" value="{!od.PDF_Co_Contract_E__c}" style="width: 30px"/>
+                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+                        (鑻�)&nbsp;<apex:inputField id="BContraE" value="{!od.PDF_Co_BContra_E__c}" style="width: 30px"/>
+                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+                        (鑻�)&nbsp;<apex:inputField id="SContraE" value="{!od.PDF_Co_SContra_E__c}" style="width: 30px"/>
+                        </apex:outputPanel>
+                    </td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+
+        <table border="0" width="840px">
+            <tr>
+                <th style="text-align: center;"></th>
+                <td><apex:commandButton onclick="savejs();return false;" value="淇濆瓨" rerender="dummy" rendered="true" disabled="{!saveBtnDisabled}"/>
+                <apex:outputText id="saveBtnDisabled" value="{!saveBtnDisabled}" style="display: none;"/></td>
+                <th style="text-align: center;"></th>
+                <td><apex:commandButton onclick="printjs();return false;" value="鎵撳嵃PDF" rendered="true" disabled=""/></td>
+            </tr>
+        </table>
+
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderContract.page-meta.xml b/scr/pages/OrderContract.page-meta.xml
new file mode 100644
index 0000000..d9c33e5
--- /dev/null
+++ b/scr/pages/OrderContract.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderContract</label>
+</ApexPage>
diff --git a/scr/pages/OrderContract2.page b/scr/pages/OrderContract2.page
new file mode 100644
index 0000000..c76a4f4
--- /dev/null
+++ b/scr/pages/OrderContract2.page
@@ -0,0 +1,203 @@
+<apex:page Controller="OrderPdf2Controller" showHeader="false" sidebar="false" id="allPage" action="{!init2}" >
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        function savejs() {
+            blockme();
+            savebtn();
+        }
+        function printjs() {
+            blockme();
+            printbtn();
+        }
+        function setSeller() {
+            var seller = j$(escapeVfId('seller_select')).val();
+            var name = '';
+            var address = '';
+            var city = '';
+            var province = '';
+            var phone = '';
+            if (seller == 'bj') {
+                name = j$(escapeVfId('seller_name1')).val();
+                address = j$(escapeVfId('seller_address1')).val();
+                city = j$(escapeVfId('seller_city1')).val();
+                province = j$(escapeVfId('seller_province1')).val();
+                phone = j$(escapeVfId('seller_phone1')).val();
+            } else if (seller == 'sh') {
+                name = j$(escapeVfId('seller_name2')).val();
+                address = j$(escapeVfId('seller_address2')).val();
+                city = j$(escapeVfId('seller_city2')).val();
+                province = j$(escapeVfId('seller_province2')).val();
+                phone = j$(escapeVfId('seller_phone2')).val();
+            }
+            j$(escapeVfId('allPage:allForm:allBlock:seller_name')).val(name);
+            j$(escapeVfId('allPage:allForm:allBlock:seller_address')).val(address);
+            j$(escapeVfId('allPage:allForm:allBlock:seller_city')).val(city);
+            j$(escapeVfId('allPage:allForm:allBlock:seller_province')).val(province);
+            j$(escapeVfId('allPage:allForm:allBlock:seller_phone')).val(phone);
+        }
+    </script>
+
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" rerender="allForm,message" action="{!saveBtn}" oncomplete="unblockUI();"/>
+        <apex:actionFunction name="printbtn" rerender="allForm,message" action="{!printBtn}" oncomplete="unblockUI();"/>
+        <apex:outputPanel id="message">
+            <apex:pageMessages />
+        </apex:outputPanel>
+
+        <apex:pageBlock id="allBlock">
+
+        <input type="hidden" id="seller_name1" value="{!seller_name1}"/>
+        <input type="hidden" id="seller_address1" value="{!seller_address1}"/>
+        <input type="hidden" id="seller_city1" value="{!seller_city1}"/>
+        <input type="hidden" id="seller_province1" value="{!seller_province1}"/>
+        <input type="hidden" id="seller_phone1" value="{!seller_phone1}"/>
+
+        <input type="hidden" id="seller_name2" value="{!seller_name2}"/>
+        <input type="hidden" id="seller_address2" value="{!seller_address2}"/>
+        <input type="hidden" id="seller_city2" value="{!seller_city2}"/>
+        <input type="hidden" id="seller_province2" value="{!seller_province2}"/>
+        <input type="hidden" id="seller_phone2" value="{!seller_phone2}"/>
+
+        <table border="0" width="600px">
+            <tr>
+                <td style="text-align: center; font-size: 16pt;">瀹岀◣璁㈣揣鍗�</td>
+            </tr>
+        </table>
+        <table style="border:solid 1px black" width="600px">
+            <colgroup>
+                <col width="20%"/>
+                <col width="80%"/>
+            </colgroup>
+            <tr>
+                <td style="text-align: right;">閫夋嫨鍗栨柟锛�</td>
+                <td style="text-align: left;">
+                    <select id="seller_select" onchange="setSeller();">
+                        <option value="none" selected="selected">-鏃�-</option>
+                        <apex:outputpanel layout="none" rendered="{!IF(productSegment == 'NDT'|| productSegment == 'ANI', false, true)}">
+                            <option value="sh">涓婃捣</option>
+                        </apex:outputpanel>
+                        
+                        <apex:outputpanel layout="none" rendered="{!IF(productSegment == 'NDT'|| productSegment == 'ANI', true, false)}">
+                            <option value="bj">鍖椾含</option>
+                        </apex:outputpanel>
+                    </select>
+                </td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">鍗栨柟锛�</td>
+                <td style="text-align: left;"><apex:inputText id="seller_name" value="{!header.seller_name}" /></td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">鍦板潃锛�</td>
+                <td style="text-align: left;"><apex:inputText id="seller_address" value="{!header.seller_address}" /></td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">鍩庡競锛�</td>
+                <td style="text-align: left;"><apex:inputText id="seller_city" value="{!header.seller_city}" /></td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">鐪佷唤锛�</td>
+                <td style="text-align: left;"><apex:inputText id="seller_province" value="{!header.seller_province}" /></td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">鐢佃瘽锛�</td>
+                <td style="text-align: left;"><apex:inputText id="seller_phone" value="{!header.seller_phone}" /></td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">鍚堝悓鍚嶏細</td>
+                <td style="text-align: left;"><apex:inputText value="{!order.Name}" /></td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">璁㈠崟缂栧彿锛�</td>
+                <td style="text-align: left;"><apex:inputText value="{!header.pdf_order_no}" /></td>
+            </tr>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+            <tr>
+                <td style="text-align: right;">鈶AP鎶ュ鍗曞彿锛�</td>
+                <td style="text-align: left;"><apex:inputText value="{!header.order_sap_no}" /></td>
+            </tr>
+            </apex:outputPanel>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'IE', true, false)}">
+            <tr>
+                <td style="text-align: right;">鐢ㄦ埛灞炴��(IE鐢�)锛�</td>
+                <td style="text-align: left;"><apex:inputField value="{!order.PDF_Property__c}" /></td>
+            </tr>
+            </apex:outputPanel>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'IE' || productSegment == 'RVI'|| productSegment == 'NDT'|| productSegment == 'ANI', true, false)}">
+            <tr style="border-bottom: thin solid black;">
+                <td style="text-align: left;">鎶ュ鍗曞彿锛�</td>
+                <td style="text-align: left;"><apex:inputText value="{!header.order_no}" /></td>
+            </tr>
+            </apex:outputPanel>
+        </table>
+
+         <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+        <table style="border-collapse:collapse;" border="1" width="600px">
+            <apex:outputPanel rendered="{!notSpecialDealer}">
+                <colgroup>
+                    <col width="5%"/>
+                    <col width="15%"/>
+                    <col width="15%"/>
+                    <col width="5%"/>
+                    <col width="15%"/>
+                    <col width="15%"/>
+                    <col width="30%"/>
+                </colgroup>
+                <tr>
+                    <td style="text-align: center;" colspan="6">鈶よ璐ф槑缁�</td>
+                    <td style="text-align: center;">BS濉啓</td>
+                </tr>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!!notSpecialDealer}">
+                <colgroup>
+                    <col width="11%"/>
+                    <col width="21%"/>
+                    <col width="21%"/>
+                    <col width="11%"/>
+                    <col width="36%"/>
+                </colgroup>
+                <tr>
+                    <td style="text-align: center;" colspan="4">鈶よ璐ф槑缁�</td>
+                    <td style="text-align: center;">BS濉啓</td>
+                </tr>
+            </apex:outputPanel>
+            <tr>
+                <td style="text-align: center;">NO.</td>
+                <td style="text-align: center;">OT CODE</td>
+                <td style="text-align: center;">EC CODE</td>
+                <td style="text-align: center;">鏁伴噺</td>
+                <apex:outputPanel rendered="{!notSpecialDealer}">
+                    <td style="text-align: center;">鍗曚环(RMB)</td>
+                    <td style="text-align: center;">鎬讳环(RMB)</td>
+                </apex:outputPanel>
+                <td style="text-align: center;">鐢熶骇鍘傚</td>
+            </tr>
+            <apex:repeat value="{!inputDetails}" var="detail">
+            <tr>
+                <td style="text-align: center;"><apex:outputText value="{!detail.lineno}" /></td>
+                <td style="text-align: left;"><apex:outputText value="{!detail.otcode}" /></td>
+                <td style="text-align: left;"><apex:outputText value="{!detail.eccode}" /></td>
+                <td style="text-align: right;"><apex:outputText value="{!detail.quantity}" /></td>
+                <apex:outputPanel rendered="{!notSpecialDealer}">
+                    <td style="text-align: right;"><apex:outputText value="{!detail.price}" /></td>
+                    <td style="text-align: right;"><apex:outputText value="{!detail.totalprice}" /></td>
+                </apex:outputPanel>
+                <td style="text-align: left;"><apex:inputText value="{!detail.factory}" /></td>
+            </tr>
+            </apex:repeat>
+        </table>
+        </apex:outputPanel>
+
+        <table border="0" width="600px">
+            <tr>
+                <td style="text-align: center;"><apex:commandButton value="淇濆瓨" action="{!saveBtn}" /></td>
+                <td style="text-align: center;"><apex:commandButton value="淇濆瓨骞舵墦鍗�" action="{!printBtn}" /></td>
+            </tr>
+        </table>
+        </apex:pageBlock>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderContract2.page-meta.xml b/scr/pages/OrderContract2.page-meta.xml
new file mode 100644
index 0000000..368e8cb
--- /dev/null
+++ b/scr/pages/OrderContract2.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderContract2</label>
+</ApexPage>
diff --git a/scr/pages/OrderDivision.page b/scr/pages/OrderDivision.page
new file mode 100644
index 0000000..55b7f98
--- /dev/null
+++ b/scr/pages/OrderDivision.page
@@ -0,0 +1,110 @@
+<apex:page Controller="OrderDivisionController" sidebar="false" showHeader="false" action="{!init}" id="Page">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+<script type="text/javascript">
+function saveJs() {
+    blockme();
+    saveBtn();
+}
+</script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction name="saveBtn" action="{!saveBtn}" rerender="allBlock" onComplete="unblockUI();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="saveJs();" value="鍒嗗壊淇濆瓨" rerender="dummy" style="width: 70px;"/>
+                    <apex:commandButton action="{!backBtn}" value="杩斿洖" rerender="dummy" style="width: 70px;"/>
+                </apex:pageBlockButtons>
+
+                <input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+                <input type="hidden" id="rtUrl" value="{!rtUrl}"/>
+
+                <apex:outputPanel id="message">
+                    <apex:messages />
+                </apex:outputPanel>
+
+                <apex:outputPanel layout="none" rendered="{!IF(is_IE == true, true, false)}">
+                <table class="linetable" border="0" style="border-collapse: collapse;width:675px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="200"/>
+                        <col width="120"/>
+                        <col width="120"/>
+                        <col width="120"/>
+                        <col width="60"/>
+                        <col width="60"/>
+                        <col width="200"/>
+                    </colgroup>
+                    <tr>
+                        <td>&nbsp;</td>
+                        <td style="text-align:right;">{!$ObjectType.Opportunity.fields.IE_ShippingHandling__c.label}锛�</td>
+                        <td style="text-align:left;"><apex:outputText style="width:90%;" id="sh_o" value="{!sh_o}"></apex:outputText></td>
+                        <td style="text-align:right;">鎷嗗垎{!$ObjectType.Opportunity.fields.IE_ShippingHandling__c.label}锛�</td>
+                        <td style="text-align:left;"><apex:inputText style="width:80%;text-align:right;" id="sh_d" value="{!sh_d}"></apex:inputText></td>
+                        <td colspan="3">&nbsp;</td>
+                    </tr>
+                </table>
+                </apex:outputPanel>
+
+                <table class="linetable" border="1" style="border-collapse: collapse;width:675px;table-layout:fixed;">
+                    <colgroup>
+                        <col width="25"/>
+                        <col width="200"/>
+                        <col width="120"/>
+                        <col width="120"/>
+                        <apex:outputPanel rendered="{!!specialDealer}" layout="none">
+                        <col width="120"/>
+                        </apex:outputPanel>
+                        <col width="60"/>
+                        <col width="60"/>
+                        <col width="200"/>
+                    </colgroup>
+                    <tr>
+                        <td style="text-align:center;">No.</td>
+                        <td style="text-align:center;">{!$ObjectType.Product2.fields.Name.label}</td>
+                        <td style="text-align:center;">{!$ObjectType.Product2.fields.ProductCode.label}</td>
+                        <td style="text-align:center;">{!$ObjectType.Product2.fields.Product_ECCode__c.label}</td>
+                        <apex:outputPanel rendered="{!!specialDealer}" layout="none">
+                        <td style="text-align:center;">{!$ObjectType.OrderItem.fields.UnitPrice.label}</td>
+                        </apex:outputPanel>
+                        <td style="text-align:center;">{!$ObjectType.OrderItem.fields.Quantity.label}</td>
+                        <td style="text-align:center;">鍒嗗壊{!$ObjectType.OrderItem.fields.Quantity.label}</td>
+                        <td style="text-align:center;">{!$ObjectType.OrderItem.fields.Description.label}</td>
+                    </tr>
+                    <apex:repeat value="{!lineinfo}" var="info" id="records">
+                    <tr>
+                        <td style="text-align:center;"><apex:outputText style="width:90%" id="lineNo" value="{!info.lineNo}"></apex:outputText></td>
+                        <td style="text-align:left;"><apex:outputText style="width:90%" id="productCode" value="{!info.productName}"></apex:outputText></td>
+                        <td style="text-align:left;"><apex:outputText style="width:90%" id="productCode1" value="{!info.ProductCode}"></apex:outputText></td>
+                        <td style="text-align:left;"><apex:outputText style="width:90%" id="ECCode" value="{!info.ECCode}"></apex:outputText></td>
+                       
+                        <apex:outputPanel rendered="{!AND(!specialDealer,!info.isSet)}" layout="none">
+                        <td style="text-align:right;"><apex:outputField style="width:90%" id="unitPrice" value="{!info.oi.UnitPrice}"></apex:outputField></td>
+                        </apex:outputPanel>
+                        <apex:outputPanel rendered="{!AND(!specialDealer,info.isSet)}" layout="none">
+                        <td style="text-align:right;"><apex:outputText style="width:90%" id="unitPrice1" value=" "></apex:outputText></td>
+                        </apex:outputPanel>
+                       
+                        <apex:outputPanel rendered="{!!info.isSet}" layout="none">
+                        <td style="text-align:right;"><apex:outputField style="width:90%" id="quantity" value="{!info.oi.Quantity}"></apex:outputField></td>
+                        </apex:outputPanel>
+                        <apex:outputPanel rendered="{!info.isSet}" layout="none">
+                        <td style="text-align:right;"><apex:outputText style="width:90%" id="quantity1" value="{!info.dqps.DecideProductSetCount__c}.00"></apex:outputText></td>
+                        </apex:outputPanel>
+                         
+                        <!-- <td style="text-align:right;"><apex:outputField style="width:90%" id="quantity" value="{!info.oi.Quantity}"></apex:outputField></td> -->
+                        <td style="text-align:center;"><apex:inputText style="width:90%;text-align:right;" id="divideCnt" value="{!info.divideCnt}"></apex:inputText></td>
+                        <td style="text-align:left;"><apex:outputField style="width:90%" id="description" value="{!info.oi.Description}"></apex:outputField></td>
+                    </tr>
+                    </apex:repeat>
+                </table>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderDivision.page-meta.xml b/scr/pages/OrderDivision.page-meta.xml
new file mode 100644
index 0000000..bcf02ec
--- /dev/null
+++ b/scr/pages/OrderDivision.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderDivision</label>
+</ApexPage>
diff --git a/scr/pages/OrderInternalMessage.page b/scr/pages/OrderInternalMessage.page
new file mode 100644
index 0000000..ffe9447
--- /dev/null
+++ b/scr/pages/OrderInternalMessage.page
@@ -0,0 +1,41 @@
+<apex:page standardController="Order" extensions="OrderInternalMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    //blockme();
+    if ('{!usertype}' == 'PowerPartner'){
+    window.open('/production/apex/OppInternalMessagePopup?raid=' + '{!URLENCODE(Order.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    } else{
+    window.open('/apex/OppInternalMessagePopup?raid=' + '{!URLENCODE(Order.Id)}',
+                'VisitNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+    }
+}
+
+function reloadjs() {
+    //blockme();
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="璁板綍" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!ra.InternalMessage__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderInternalMessage.page-meta.xml b/scr/pages/OrderInternalMessage.page-meta.xml
new file mode 100644
index 0000000..ec80150
--- /dev/null
+++ b/scr/pages/OrderInternalMessage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderInternalMessage</label>
+</ApexPage>
diff --git a/scr/pages/OrderInternalMessagePopup.page b/scr/pages/OrderInternalMessagePopup.page
new file mode 100644
index 0000000..8ec3c14
--- /dev/null
+++ b/scr/pages/OrderInternalMessagePopup.page
@@ -0,0 +1,51 @@
+<apex:page Controller="OrderInternalMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.Order.fields.InternalMessage__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="淇濆瓨" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra1.InternalMessage__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderInternalMessagePopup.page-meta.xml b/scr/pages/OrderInternalMessagePopup.page-meta.xml
new file mode 100644
index 0000000..87caec6
--- /dev/null
+++ b/scr/pages/OrderInternalMessagePopup.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderInternalMessagePopup</label>
+</ApexPage>
diff --git a/scr/pages/OrderMessage.page b/scr/pages/OrderMessage.page
new file mode 100644
index 0000000..420bb54
--- /dev/null
+++ b/scr/pages/OrderMessage.page
@@ -0,0 +1,35 @@
+<apex:page standardController="Order" extensions="OrderMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function leavemessage() {
+    //blockme();
+    window.open('/apex/OrderMessagePopUp?raid=' + '{!URLENCODE(Order.Id)}',
+                'OrderNotes',
+                'height=400,width=600,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+}
+
+function reloadjs() {
+    //blockme();
+    init();
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="init" action="{!init}" rerender="allPanel,message">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="leavemessage(); return false;" value="鐣欒█" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:inputField id="response" value="{!ra.OCN_Internal_Notes__c
+                }" style="width:100%; height:120px; resize:none;"/>
+                <script>
+                    j$(escapeVfId('allPage:allForm:allBlock:response')).attr('readonly', true);
+                </script>
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderMessage.page-meta.xml b/scr/pages/OrderMessage.page-meta.xml
new file mode 100644
index 0000000..3e55232
--- /dev/null
+++ b/scr/pages/OrderMessage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderMessage</label>
+</ApexPage>
diff --git a/scr/pages/OrderMessagePopUp.page b/scr/pages/OrderMessagePopUp.page
new file mode 100644
index 0000000..a34874e
--- /dev/null
+++ b/scr/pages/OrderMessagePopUp.page
@@ -0,0 +1,51 @@
+<apex:page Controller="OrderMessageController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.Order.fields.OCN_Internal_Notes__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="鐣欒█" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+                <table>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra1.OCN_Internal_Notes__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderMessagePopUp.page-meta.xml b/scr/pages/OrderMessagePopUp.page-meta.xml
new file mode 100644
index 0000000..e2bf113
--- /dev/null
+++ b/scr/pages/OrderMessagePopUp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderMessagePopUp</label>
+</ApexPage>
diff --git a/scr/pages/OrderOpenAlert.page b/scr/pages/OrderOpenAlert.page
new file mode 100644
index 0000000..24db2f4
--- /dev/null
+++ b/scr/pages/OrderOpenAlert.page
@@ -0,0 +1,176 @@
+<apex:page standardController="Order" showHeader="false" sidebar="false">
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        var is_new = '{!Order.IsNew__c}' == 'true';
+        var is_upload = '{!Order.IsUpload__c}' == 'true';
+        var approval_status = '{!Order.ApproveStatus__c}';
+
+        var isUpdate =  '{!Order.isUpdate__c}' == 'true';
+        if(!isUpdate){
+            var rac = new sforce.SObject("Order");
+            rac.Id = "{!Order.Id}";
+            rac.isUpdate__c = '1';
+            var result = sforce.connection.update([rac]);
+            var messages = getConnectDMLErrorMessages(result);
+            if (messages.length > 0) { 
+                alert(messages.join("\n")); 
+            } else {
+                window.top.location.reload();
+            }
+        }
+
+        //if (approval_status == 'OrderPass' && '{!Order.OpportunityOwnerId__c}' != '{!Order.OwnerId}') {
+        // var oppowner = '{!Order.OpportunityOwnerId__c}';
+        // var odrowner = '{!Order.OwnerId}';
+        // if (oppowner != odrowner.substring(0, 15)) {
+        //     var rac = new sforce.SObject("Order"); 
+        //     rac.Id = "{!Order.Id}";
+        //     //rac.OwnerId = '{!Order.OpportunityOwnerId__c}';
+        //     var result = sforce.connection.update([rac]);
+        //     var messages = getConnectDMLErrorMessages(result);
+        //     if (messages.length > 0) { 
+        //         alert(messages.join("\n")); 
+        //     } else {
+        //         window.top.location.reload();
+        //     }
+        // }
+        
+        var now_status = '{!Order.SP_11__c}' != '{!Order.SP_11D__c}' || 
+                         '{!Order.SP_101__c}' != '{!Order.SP_101D__c}' || 
+                         '{!Order.SP_102__c}' != '{!Order.SP_102D__c}' || 
+                         '{!Order.SP_103__c}' != '{!Order.SP_103D__c}' || 
+                         '{!Order.SP_106__c}' != '{!Order.SP_106D__c}' || 
+                         '{!Order.SP_107__c}' != '{!Order.SP_107D__c}' || 
+                         '{!Order.SP_111__c}' != '{!Order.SP_111D__c}' || 
+                         '{!Order.SP_121__c}' != '{!Order.SP_121D__c}' || 
+                         '{!Order.SP_131__c}' != '{!Order.SP_131D__c}' || 
+                         '{!Order.SP_141__c}' != '{!Order.SP_141D__c}' || 
+                         '{!Order.SP_151__c}' != '{!Order.SP_151D__c}' || 
+                         '{!Order.SP_161__c}' != '{!Order.SP_161D__c}' || 
+                         '{!Order.SP_171__c}' != '{!Order.SP_171D__c}' || 
+                         '{!Order.SP_181__c}' != '{!Order.SP_181D__c}' || 
+                         '{!Order.SP_191__c}' != '{!Order.SP_191D__c}' ||
+                         '{!Order.SP_201__c}' != '{!Order.SP_201D__c}' || 
+                         '{!Order.SP_202__c}' != '{!Order.SP_202D__c}' ||  
+                         '{!Order.SP_21__c}' != '{!Order.SP_21D__c}' || 
+                         '{!Order.SP_22__c}' != '{!Order.SP_22D__c}' || 
+                         '{!Order.SP_31__c}' != '{!Order.SP_31D__c}' || 
+                         '{!Order.SP_32__c}' != '{!Order.SP_32D__c}' || 
+                         '{!Order.SP_33__c}' != '{!Order.SP_33D__c}' || 
+                         '{!Order.SP_41__c}' != '{!Order.SP_41D__c}' || 
+                         '{!Order.SP_51__c}' != '{!Order.SP_51D__c}' || 
+                         '{!Order.SP_52__c}' != '{!Order.SP_52D__c}' || 
+                         '{!Order.SP_61__c}' != '{!Order.SP_61D__c}' || 
+                         '{!Order.SP_62__c}' != '{!Order.SP_62D__c}' || 
+                         '{!Order.SP_71__c}' != '{!Order.SP_71D__c}' || 
+                         '{!Order.SP_81__c}' != '{!Order.SP_81D__c}' || 
+                         '{!Order.SP_91__c}' != '{!Order.SP_91D__c}' || 
+                         '{!Order.Contract_Status__c}' != '{!Order.Contract_StatusD__c}' || 
+                         '{!Order.CustomerContractPrice__c}' != '{!Order.CustomerContractPriceD__c}' || 
+                         '{!Order.EndUser__c}' != '{!Order.EndUserD__c}' || 
+                         '{!Order.OlympusContractPrices__c}' != '{!Order.OlympusContractPricesD__c}' || 
+                         '{!Order.Upload_IsChanged__c}' != 'false' || 
+                         '{!Order.IE_SP1_D__c}' != '{!Order.IE_SP1__c}' || 
+                         '{!Order.IE_SP2_D__c}' != '{!Order.IE_SP2__c}' || 
+                         '{!Order.IE_SP3_D__c}' != '{!Order.IE_SP3__c}' || 
+                         '{!Order.IE_SP4_D__c}' != '{!Order.IE_SP4__c}' || 
+                         '{!Order.IE_SP5_D__c}' != '{!Order.IE_SP5__c}' || 
+                         '{!Order.IE_SP6_D__c}' != '{!Order.IE_SP6__c}' || 
+                         '{!Order.IE_SP7_D__c}' != '{!Order.IE_SP7__c}' || 
+                         '{!Order.RVI_SP1_D__c}' != '{!Order.RVI_SP1__c}' || 
+                         '{!Order.RVI_SP2_D__c}' != '{!Order.RVI_SP2__c}' || 
+                         '{!Order.RVI_SP3_D__c}' != '{!Order.RVI_SP3__c}' || 
+                         '{!Order.RVI_SP4_D__c}' != '{!Order.RVI_SP4__c}' || 
+                         '{!Order.RVI_SP5_D__c}' != '{!Order.RVI_SP5__c}' || 
+                         '{!Order.RVI_SP6_D__c}' != '{!Order.RVI_SP6__c}' || 
+                         '{!Order.NDT_SP1_D__c}' != '{!Order.NDT_SP1__c}' || 
+                         '{!Order.NDT_SP2_D__c}' != '{!Order.NDT_SP2__c}' || 
+                         '{!Order.NDT_SP3_D__c}' != '{!Order.NDT_SP3__c}' || 
+                         '{!Order.NDT_SP4_D__c}' != '{!Order.NDT_SP4__c}' || 
+                         '{!Order.NDT_SP5_D__c}' != '{!Order.NDT_SP5__c}' || 
+                         '{!Order.NDT_SP6_D__c}' != '{!Order.NDT_SP6__c}' || 
+                         '{!Order.NDT_SP7_D__c}' != '{!Order.NDT_SP7__c}' || 
+                         '{!Order.NDT_SP8_D__c}' != '{!Order.NDT_SP8__c}' || 
+                         '{!Order.NDT_SP9_D__c}' != '{!Order.NDT_SP9__c}' ||
+                         '{!Order.NDT_SP10_D__c}' != '{!Order.NDT_SP10__c}' || 
+                         '{!Order.NDT_SP11_D__c}' != '{!Order.NDT_SP11__c}' || 
+                         '{!Order.ANI_SP1_D__c}' != '{!Order.ANI_SP1__c}' || 
+                         '{!Order.ANI_SP2_D__c}' != '{!Order.ANI_SP2__c}' || 
+                         '{!Order.ANI_SP3_D__c}' != '{!Order.ANI_SP3__c}' || 
+                         '{!Order.ANI_SP4_D__c}' != '{!Order.ANI_SP4__c}' || 
+                         '{!Order.ANI_SP5_D__c}' != '{!Order.ANI_SP5__c}' || 
+                         '{!Order.ANI_SP6_D__c}' != '{!Order.ANI_SP6__c}' ||
+                         '{!Order.NormalDis_SerContractCondition_D__c}' != '{!Order.NormalDis_SerContractCondition__c}' || 
+                         '{!Order.HighDis_SerContractCondition_D__c}' != '{!Order.HighDis_SerContractCondition__c}' || 
+                         '{!Order.SpecialDis_SerContractCondition_D__c}' != '{!Order.SpecialDis_SerContractCondition__c}' || 
+                         '{!Order.Warranty_SerContractCondition_D__c}' != '{!Order.Warranty_SerContractCondition__c}' ||
+                         '{!Order.Discount_D__c}' != '{!Order.Discount__c}' || 
+                         '{!Order.Olympus_Price_BeforeDiscount_D__c}' != '{!Order.Olympus_Price_BeforeDiscount__c}' || 
+                         '{!Order.PaymentCondition_D__c}' != '{!Order.PaymentCondition__c}' || 
+                         '{!Order.SpecialDelivery_D__c}' != '{!Order.SpecialDelivery__c}' || 
+                         '{!Order.SpecialDeliveryContact_D__c}' != '{!Order.SpecialDeliveryContact__c}' || 
+                         '{!Order.SpecialDeliveryPhone_D__c}' != '{!Order.SpecialDeliveryPhone__c}' || 
+                         '{!Order.SpecialDeliveryAddress_D__c}' != '{!Order.SpecialDeliveryAddress__c}' || 
+                         '{!Order.SpecialParkage_D__c}' != '{!Order.SpecialParkage__c}' || 
+                         '{!Order.SpecialWarranty_D__c}' != '{!Order.SpecialWarranty__c}' || 
+                         '{!Order.OtherApply_D__c}' != '{!Order.OtherApply__c}' || 
+                         '{!Order.Andor_D__c}' != '{!Order.Andor__c}' || 
+                         '{!Order.Bitplane_D__c}' != '{!Order.Bitplane__c}' || 
+                         '{!Order.CoolLED_D__c}' != '{!Order.CoolLED__c}' || 
+                         '{!Order.Lumen_D__c}' != '{!Order.Lumen__c}' || 
+                         '{!Order.Lumenera_D__c}' != '{!Order.Lumenera__c}' || 
+                         '{!Order.Media_Cybernetics_D__c}' != '{!Order.Media_Cybernetics__c}' || 
+                         '{!Order.Narishige_D__c}' != '{!Order.Narishige__c}' || 
+                         '{!Order.Newport_D__c}' != '{!Order.Newport__c}' || 
+                         '{!Order.OSIS_Germany_D__c}' != '{!Order.OSIS_Germany__c}' || 
+                         '{!Order.OSIS_Singapore_D__c}' != '{!Order.OSIS_Singapore__c}' || 
+                         '{!Order.Photometrics_D__c}' != '{!Order.Photometrics__c}' || 
+                         '{!Order.Prior_Scientific_D__c}' != '{!Order.Prior_Scientific__c}' || 
+                         '{!Order.Q_Imaging_D__c}' != '{!Order.Q_Imaging__c}' || 
+                         '{!Order.Tokai_Hit_D__c}' != '{!Order.Tokai_Hit__c}' || 
+                         '{!Order.Other_Third_D__c}' != '{!Order.Other_Third__c}' || 
+                         '{!Order.ServiceFee_D__c}' != '{!Order.ServiceFee__c}' || 
+                         '{!Order.AlongProduct_D__c}' != '{!Order.AlongProduct__c}' || 
+                         '{!Order.ForeignTradeCompany_D__c}' != '{!Order.ForeignTradeCompany__c}' || 
+                         '{!Order.SpecialDeliveryAccount_D__c}' != '{!Order.SpecialDeliveryAccount__c}' || 
+                         '{!Order.SpecialDeliveryContact2_D__c}' != '{!Order.SpecialDeliveryContact2__c}';
+        //if ((is_new || now_status) && approval_status != 'Submit') {
+        //    alert("鏂板缓鎴栦慨鏀瑰悎鍚屼俊鎭悗锛岃鍙婃椂鎻愪氦瀹℃壒銆�");
+        //}
+
+function getConnectDMLErrorMessages(results) { 
+var messages = [], 
+i = 0, 
+len = results.length, 
+r; 
+for (; i < len; i++) { 
+r = results[i]; 
+if (! r.getBoolean("success")) { 
+messages = messages.concat(getConnectDMLMessagesOfAResult(r)); 
+} 
+} 
+return messages; 
+}; 
+function getConnectDMLMessagesOfAResult(res) { 
+var messages = [], 
+errors = res.getArray("errors"), 
+i = 0, 
+len = errors.length, 
+e; 
+for (; i < len; i++) { 
+e = errors[i]; 
+messages.push(e.message + " " + getConnectDMLErrorFields(e)); 
+} 
+return messages; 
+}; 
+function getConnectDMLErrorFields(error) { 
+var fields = error.getArray('fields'); 
+if (fields.length > 0) { 
+return "[" + fields.join(",") + "]" 
+} else { 
+return ""; 
+} 
+}; 
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderOpenAlert.page-meta.xml b/scr/pages/OrderOpenAlert.page-meta.xml
new file mode 100644
index 0000000..39b5f24
--- /dev/null
+++ b/scr/pages/OrderOpenAlert.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderOpenAlert</label>
+</ApexPage>
diff --git a/scr/pages/OrderPDF.page b/scr/pages/OrderPDF.page
new file mode 100644
index 0000000..fd677eb
--- /dev/null
+++ b/scr/pages/OrderPDF.page
@@ -0,0 +1,1111 @@
+<apex:page Controller="OrderPdfController" showHeader="false" sidebar="false" id="allPage" action="{!init2}" renderAs="pdf">
+<html>
+    <head>
+        <style>
+        @page {
+            size: A4 landscape;
+            margin: 12mm 12mm 5mm 12mm;
+
+            @bottom-center {
+                content: counter(page) " / " counter(pages);
+            }
+        }
+
+        table { border-collapse: collapse; }
+
+        td.border-thick-title { border-width: 1pt 0pt 1pt 0pt; border-style: solid; border-color: black; text-align: center;}
+        td.border-thick-bottom { border-width: 0pt 0pt 1pt 0pt; border-style: solid; border-color: black; text-align: center;}
+        td.detail { text-align: center; }
+
+        </style>
+    </head>
+    <body style="font-family: Arial Unicode MS; page-break-inside: auto">
+        <table style="border-style:none;">
+            <tr style="font-size: 8pt;">
+                <td>
+                    <div>鍚堝悓鍙�</div>
+                    <div>Contract No</div>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'  && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                    <div>鎶ュ鍗曞彿</div>
+                    <div>浠g悊鍟嗗叏绉�</div>
+                    </apex:outputPanel>
+                </td>
+                <td>
+                    <div>:&nbsp;</div>
+                    <div>:&nbsp;</div>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                    <div>:&nbsp;</div>
+                    <div>:&nbsp;</div>
+                    </apex:outputPanel>
+                </td>
+                <td>
+                    <div>&nbsp;{!contra.order.PDF_Order_No__c}</div>
+                    <div>&nbsp;{!contra.order.PDF_Order_No__c}</div>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                    <div>&nbsp;{!contra.order.PDF_I_Report__c}</div>
+                    <div>&nbsp;{!contra.order.Dealer__c}</div>
+                    </apex:outputPanel>
+                </td>
+            </tr>
+        </table>
+        <table style="border-style:none; top:0px; right:0px; position:absolute;">
+            <tr style="font-size: 8pt;">
+                <td>
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <div>绛捐鏃ユ湡</div>
+                    <div>Signature Date</div>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' ||Opp.ProductSegment__c = 'ANI' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <div>绛捐鍦扮偣</div>
+                    <div>Signature Place</div>
+                    </apex:outputPanel>
+                </td>
+                <td>
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <div>:&nbsp;</div>
+                    <div>:&nbsp;</div>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT' ||Opp.ProductSegment__c = 'ANI' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <div>:&nbsp;</div>
+                    <div>:&nbsp;</div>
+                    </apex:outputPanel>
+                </td>
+                <td>
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <div>&nbsp;{!contra.SignatureDate}</div>
+                    <div>&nbsp;{!contra.SignatureDates}</div>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT' ||Opp.ProductSegment__c = 'ANI'&& Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <div>&nbsp;{!contra.order.PDF_SignaturePlace__c}</div>
+                    <div>&nbsp;{!contra.order.PDF_SignaturePlaces__c}</div>
+                    </apex:outputPanel>
+                </td>
+            </tr>
+        </table>
+        <table width="100%" cellspacing="0" cellpadding="0">
+            <colgroup>
+                <col width="25%"/>
+                <col width="25%"/>
+                <col width="25%"/>
+                <col width="25%"/>
+            </colgroup>
+            <tr><td colspan = "4" height="5px"></td></tr>
+            <tr>
+                <td colspan = "4" style="text-align: center;font-size: 14pt;">鍚堝悓</td>
+            </tr>
+            <tr>
+                <td colspan = "4" style="text-align: center;font-size: 14pt;">CONTRACT</td>
+            </tr>
+
+            <tr>
+                <td style="font-size: 9pt;">涔版柟:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!specialDeliveryAddress.Name}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">THE BUYER:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!specialDeliveryAddress.EnglishName__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!specialDeliveryAddress.Address1__c}</td>
+            </tr>
+            <apex:outputPanel rendered="{!IF(Opp.TradeType__c != 'Taxation', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_B_Add__c}</td>
+            </tr>
+            </apex:outputPanel>
+            <tr>
+                <td style="font-size: 8pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!specialDeliveryAddress.Phone}</td>
+            </tr>
+            <apex:outputPanel rendered="{!IF(Opp.TradeType__c != 'Taxation', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 8pt;">浼犵湡锛團ax锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!specialDeliveryAddress.Fax}</td>
+            </tr>
+            </apex:outputPanel>
+            <tr>
+                <td style="font-size: 9pt;">鑱旂郴浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!specialDeliveryContact.Name}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">CONTACT PERSON:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_B_contactperson__c}</td>
+            </tr>
+
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none" >
+            <tr>
+                <td style="font-size: 9pt;">E-Mail:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!specialDeliveryContact.Email}</td>
+            </tr>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">鐢ㄦ埛灞炴��:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_B_Attri__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢ㄦ埛浜у搧:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.account.Sub_Use__c}</td>
+            </tr>
+            </apex:outputPanel>
+
+            <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'RVI', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">甯傚満:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.account.Sub_Use__c}</td>
+            </tr>
+            </apex:outputPanel>
+
+            <tr><td height="1px">&nbsp;</td></tr>
+
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'BC' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">鍗栨柟:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_SELLER__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">THE SELLER:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_THE_SELLER__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Adds__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_S_Address__c}</td>
+            </tr>
+
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) &&Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">鍗栨柟:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_SELLER__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Adds__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽 (TEL):&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_TEL__c}</td>
+            </tr>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI')&& Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">鍗栨柟:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_SELLER__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">THE SELLER:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_THE_SELLER__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Adds__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_S_Address__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">鐢佃瘽(Tel):&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_S_TEL__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">浼犵湡(FAX):&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_S_FAX__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">Bank Name:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Bank_Name__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">Branch:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Branch__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">Address:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_S_Bank_Address__c}</td>
+            </tr>
+            <!-- <tr>
+                <td style="font-size: 9pt;">Address:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Address__c}</td>
+            </tr> -->
+            <tr>
+                <td style="font-size: 9pt;">Account no:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Account_No__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">Swift code:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Swift_Code__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">Account name:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_S_Account_Name__c}</td>
+            </tr>
+            </apex:outputPanel>
+
+            <tr style="line-height: 4px"><td height="1px">&nbsp;</td></tr>
+
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">鏀惰揣浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_Consignee__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">THE CONSIGNEE:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_THECONSIGNE__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_Address__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_C_Add__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_TEL__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">浼犵湡锛團ax锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_FAX__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鑱旂郴浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_CONTACT__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">CONTACT PERSON:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_contactperson__c}</td>
+            </tr>
+            </apex:outputPanel>
+<!--             <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI') && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">THE CONSIGNEE:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_THECONSIGNE__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_C_Add__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.pdf_c_tel}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">浼犵湡锛團ax锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.pdf_c_fax}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">CONTACT PERSON:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_C_contactperson__c}</td>
+            </tr>
+            </apex:outputPanel> -->
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">鏀惰揣浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.pdf_c_consignee}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.pdf_c_address}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.pdf_c_tel}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鑱旂郴浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.pdf_c_contact}</td>
+            </tr>
+            </apex:outputPanel>
+
+            <tr height="1px"><td height="1px">&nbsp;</td></tr>
+
+            <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption' && (Opp.ProductSegment__c = 'BS'||Opp.ProductSegment__c = 'NDT'||Opp.ProductSegment__c = 'ANI'||Opp.ProductSegment__c = 'IE'||Opp.ProductSegment__c = 'RVI'), 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">閫氱煡浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_NotifyParty__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">THE NOTIFY PARTY:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_NOTIFY_PARTY__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_Address__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_N_Add__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_N_TEL__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">浼犵湡锛團ax锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_N_FAX__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鑱旂郴浜�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_CONTACT__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">CONTACT PERSON:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_CONTACTPERSON__c}</td>
+            </tr>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption' && (Opp.ProductSegment__c = 'ABC'), 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">THE NOTIFY PARTY:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_NOTIFY_PARTY__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_N_Add__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_TEL__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">浼犵湡锛團ax锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_FAX__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">CONTACT PERSON:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_N_CONTACTPERSON__c}</td>
+            </tr>
+            </apex:outputPanel>
+
+            <tr><td height="1px">&nbsp;</td></tr>
+            
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' ) && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">杞繍鍟� (鑻辨枃):&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_Forwarder__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 8pt;">ADD:&nbsp;</td>
+                <td colspan = "3" style="font-size: 8pt;">{!contra.order.PDF_F_Add__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽锛圱el锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_F_TEL__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">浼犵湡锛團ax锛�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_F_FAX__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鑱旂郴浜� (涓枃):&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_F_ContactPerson__c}</td>
+            </tr>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT'|| Opp.ProductSegment__c = 'ANI' ) && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+            <tr>
+                <td style="font-size: 9pt;">涓棿鍟嗗叕鍙�:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!Opp.SubDealer__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍏徃鍚嶇О:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_F_Add__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鍦板潃:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_F_TEL__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">鐢佃瘽:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.PDF_F_FAX__c}</td>
+            </tr>
+            <tr>
+                <td style="font-size: 9pt;">绯荤粺缂栧彿:&nbsp;</td>
+                <td colspan = "3" style="font-size: 9pt;">{!contra.order.Id}</td>
+            </tr>
+            </apex:outputPanel>
+        </table>
+
+        <apex:outputPanel layout="none">
+            <div style="page-break-after: always;"/>
+        </apex:outputPanel>
+
+        <table style="font-size: 9pt;">
+            <tr>
+                <td style="text-align:left">
+                1. 鍏圭粡涔板崠鍙屾柟鍚屾剰, 缂旂粨鏈悎鍚屽苟鎸夋湰鍚堝悓涓嬭堪鏉℃,涔版柟鍚屾剰璐叆鍙婂崠鏂瑰悓鎰忓嚭鍞互涓嬭揣鐗�:<br/>
+                1. This Contract is made by and between the Buyer and the Seller锛寃hereby the Buyer agrees to buy and the Seller<br/>
+                agrees to sell the under-mentioned goods subject to the terms and conditions stipulated below:</td>
+            </tr>
+            <tr><td style="text-align: right;">(USD)</td></tr>
+        </table>
+        <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'true', 'false')}" layout="none" >
+            <table width="100%" border="1" cellspacing="0" cellpadding="0" style="table-layout:auto;font-size: 9pt;">
+                <tr>
+                    <td width="5%" style="text-align: center;">搴忓彿</td>
+                    <td style="text-align: center;">璐х墿鍚嶇О鍙婅鏍�</td>
+                    <td width="10%" style="text-align: center;">鍗� 浣�</td>
+                    <td width="10%" style="text-align: center;">鏁�  閲�</td>
+                    <td width="15%" style="text-align: center;">鍗�  浠�</td>
+                    <td width="15%" style="text-align: center;">鎬�    浠�</td>
+                </tr>
+                <tr>
+                    <td width="5%" style="text-align: center;">Item</td>
+                    <td style="text-align: center;">Goods &amp; Specification</td>
+                    <td width="10%" style="text-align: center;">Unit</td>
+                    <td width="10%" style="text-align: center;">Qty</td>
+                    <td width="15%" style="text-align: center;">Unit Price</td>
+                    <td width="15%" style="text-align: center;">Total Amount</td>
+                </tr>
+
+                <apex:repeat value="{!printSetInfo}" var="set">
+                    <tr>
+                        <td style="text-align: center;"><apex:outputText value="{!set.No__c}" /></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Goods__c}" /></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Unit__c}" /></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Qty__c}" /></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.UnitPrice__c}" /></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Total_Amount__c}" /></td>
+                    </tr>
+                </apex:repeat>
+            </table>
+        </apex:outputPanel>
+
+        <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'false', 'true')}" layout="none" >
+            
+             <table width="100%" border="1" cellspacing="0" cellpadding="0" style="table-layout:auto;font-size: 9pt;">
+                <colgroup>
+                    <col width="5%"/>
+                    <col width="10%"/>
+                    <col width="23%"/>
+                    <col width="5%"/>
+                    <col width="8%"/>
+                    <col width="10%"/>
+                    <col width="8%"/>
+                    <col width="11%"/>
+                    <col width="10%"/>
+                    <col width="10%"/>
+                </colgroup>
+                 <tr>
+                    <td style="text-align: center;">搴忓彿</td>
+                    <td style="text-align: center;">U8鍙风爜</td>
+                    <td style="text-align: center;">浜у搧鍨嬪彿</td>
+                    <td style="text-align: center;">鍗曚綅</td>
+                    <td style="text-align: center;">鏁伴噺</td>
+                    <td style="text-align: center;">鍗曚环</td>
+                    <td style="text-align: center;">鎶樻墸</td>
+                    <td style="text-align: center;">鎶樺悗鍗曚环</td>
+                    <td style="text-align: center;">鎬讳环</td>
+                    <td style="text-align: center;">澶囨敞</td>
+                </tr>
+                <tr>
+                    <td style="text-align: center;">Item</td>
+                    <td style="text-align: center;">U8</td>
+                    <td style="text-align: center;">Part Number</td>
+                    <td style="text-align: center;">Unit</td>
+                    <td style="text-align: center;">Quantity</td>
+                    <td style="text-align: center;">Unit Price</td>
+                    <td style="text-align: center;">Discount </td>
+                    <td style="text-align: center;">Discounted Price/Unit</td>
+                    <td style="text-align: center;">Total Amount</td>
+                    <td style="text-align: center;">Remark</td>
+                </tr>
+
+                 <apex:repeat value="{!printSetInfo}" var="set">
+                    <tr>
+                        <td style="text-align: center;"><apex:outputText value="{!set.No__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.U8__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><!-- <apex:outputText value="{!set.Goods__c}" style="width: 95%"/> --><c:PDFWbr targetStr="{!set.Goods__c}"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Unit__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Qty__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.UnitPrice__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.discount__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.discountprice__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!set.Total_AmountNDT__c}" style="width: 95%; text-align: right;"/></td>
+                        <td style="text-align: center;"><!-- <apex:outputText value="{!set.Remark__c}" style="width: 95%"/> --><c:PDFWbr targetStr="{!set.Remark__c}"/></td>
+                    </tr>
+                </apex:repeat>
+            </table>
+        </apex:outputPanel>
+
+        <table style="font-size: 9pt;" width="100%">
+            <colgroup>
+                <col width="30%" />
+                <col width="60%" />
+                <col width="10%" />
+            </colgroup>
+            <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'true', 'false')}" layout="none" >
+                <tr>
+                    <td>鎬婚噾棰濓細&nbsp;</td>
+                    <!-- <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none"> -->
+                    <td>US$&nbsp;
+                        <apex:outputText value="{0, number, ##0.00}">
+                            <apex:param value="{!TotalMoney}" />
+                        </apex:outputText>
+                    </td>
+                    <!-- </apex:outputPanel> -->
+                    <!-- <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS') &&Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <td>{!contra.order.CustomerContractPrice__c}</td>
+                    </apex:outputPanel> -->
+                </tr> 
+                <tr>
+                    <td>Total Value:&nbsp;</td>
+                    <td>{!contra.order.Shipment_Term_D__c} <u>&nbsp;&nbsp;&nbsp;&nbsp;{!contra.order.PDF_Shipment_Term2_Text__c}&nbsp;&nbsp;&nbsp;&nbsp;</u> </td>
+                </tr>
+            </apex:outputPanel>
+            <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'false', 'true')}" layout="none" >
+                <tr>
+                    <td>杩愪繚璐�/Shipping Charge锛�&nbsp;</td>
+                    <td style="text-indent: 45px">US$&nbsp;
+                        <apex:outputText value="{0,number,##0.00}">
+                            <apex:param value="{!TrAndPre}"/>
+                        </apex:outputText>
+                    </td>   
+                </tr>
+                <tr>
+                    <td>鎬婚噾棰濓細&nbsp;</td>
+                    <!-- <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none"> -->
+                    <td style="text-indent: 45px;">US$&nbsp;
+                        <apex:outputText value="{0, number, ##0.00}">
+                            <apex:param value="{!TotalMoney}" />
+                        </apex:outputText>
+                    </td>
+                    <!-- </apex:outputPanel> -->
+                    <!-- <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS') &&Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    <td>{!contra.order.CustomerContractPrice__c}</td>
+                    </apex:outputPanel> -->
+                </tr> 
+                <tr>
+                    <td>Total Value:&nbsp;</td>
+                    <td>{!contra.order.Shipment_Term_D__c} <u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u>{!contra.order.PDF_Shipment_Term2_Text__c}&nbsp;&nbsp;&nbsp;&nbsp; </td>
+                </tr>
+            </apex:outputPanel>
+            <tr>
+                <td>Say: U.S. DOLLARS:&nbsp;</td>
+                <!-- <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' && Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none"> -->
+                <td>{!contra.order.Total_price_E__c}</td>
+                <!-- </apex:outputPanel> -->
+                <!-- <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS') &&Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                <td>{!contra.order.CustomerContractPrice__c}</td>
+                </apex:outputPanel> -->
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    2. 鐢熶骇鍥藉埆鍙婂埗閫犲巶鍟�:&nbsp;{!contra.order.PDF_Bi_manufacturers__c}<br/>
+                    2. COUNTRY OF ORIGIN OF GOODS AND MANUFACTURERS:&nbsp;{!contra.order.PDF_Bi_manufacturersEn__c}<br/>
+                </td>
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    3. 鍖呰: <br/>
+                    鍟嗗搧鎳変互鍧氬浐鐨勫嚭鍙g焊鐨鎴栨湪绠卞寘瑁咃紝閫備簬闀块�旂┖杩愩�佸ぉ姘旀垨姘斿�欏彉鍖栥�侀槻娼�佹姉闇囥�侀槻閿堝強澶氭鎼繍銆傜敱浜庡寘瑁呬笉鑹�屼骇鐢熺殑<br/>
+                    鐩存帴鎹熷け, 鐢卞崠鏂硅礋璐c��<br/>
+                    3. PACKING: <br/>
+                    The goods should be packed in strong export carton box or wooden box, which is suitable for long haul air transportation and <br/>
+                    change of weather or climate, well protected against moisture, shocks, rust and withstand numerous transits. All direct losses <br/>
+                    incurred on account of improper packing shall be borne by the Seller.<br/>
+                </td>
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    4.杩愯緭鏍囪瘑锛� <br/>
+                    鍗栨柟椤诲湪姣忎欢璐х墿鐨勫寘瑁呭琛ㄤ笂浠ヤ笉瑜壊鐨勯鏂欐爣鏄庝欢鍙枫�佹瘺閲嶃�佸昂鐮佸強涓嬪垪瀛楀彞: <br/>
+                    鈥濆嬁浣垮彈娼�� 銆佲�滃皬蹇冭交鏀锯�濄�� 鈥滄闈㈠悜涓娾�濈瓑瀛楁牱鍙婁笅鍒楀敍澶达細<br/>
+                    4. SHIPPING MARK:  <br/>
+                    The Seller shall mark on the surface of each package with fadeless paint, the package number锛実ross weight锛宮easurement<br/>
+                     and the following wordings锛�<br/>
+                    鈥淜EEP AWAY FROM MOISTURE鈥濓紝鈥淗ANDLE WITH CARE鈥� 锛屸�淭HIS SIDE UP鈥� etc. And the below shipping mark: <br/>
+                    <div><apex:outputField value="{!contra.order.PDF_Sp_SHIPPINGMARK__c}" /></div>
+                </td>
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    5.瑁呰繍鏉℃: {!contra.order.PDF_Sp_ShippingTerms__c}<br/>
+                    5.TERMS OF SHIPMENT: {!contra.ShippingTerms}<br/>
+                </td>
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    6.浜よ揣鏈�:  <apex:outputField value="{!contra.order.DeliveryTimeText__c}" /><br/>
+                    6.THE DELIVERY TIME: <apex:outputField value="{!contra.order.DeliveryTimeTextEn__c}" /><br/>
+                </td>
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    7.鍗栨柟搴斾繚鐣欒揣鐗╁拰闆堕儴浠剁殑浜ф潈鍜屾墍鏈夋潈锛岃绛夋潈鍒╁彧鏈夊湪鍏ㄩ鏀跺埌璐ф鏃舵柟鑷姩杞Щ鍒颁拱鏂广��<br/>
+                    7.The Seller shall maintain title and ownership of the goods and spare parts thereof which shall automatically pass to the Buyer<br/>
+                      only on receipt of the full payment.<br/>
+                </td>
+            </tr>
+
+            <tr>
+                <td colspan = "3">
+                    8. 瑁呰繍鍙e哺锛�&nbsp;棣欐腐<br/>
+                    8.  PORT OF LOADING:&nbsp;Hong Kong <br/>
+                </td>
+            </tr>
+            <tr>
+                <td colspan = "3">
+                    9. 鐩殑鍙e哺锛�&nbsp;{!contra.order.PDF_Sp_DestinationPort__c}<br/>
+                    9.  PORT OF DESTINATION:&nbsp;{!contra.order.PDF_Sp_DestinationPort_E__c}<br/>
+                </td>
+            </tr>
+
+            <tr>
+                <td colspan = "3">
+                    10. 淇濋櫓锛�<br/>
+                    鐢卞崠鏂规寜鍙戠エ閲戦鐨�110%鎶曚繚鍏ㄩ櫓鍙婃垬浜夐櫓锛屽苟璇存槑鍙互鍦ㄤ腑鍥藉鍐呯储璧旓紝绌虹櫧鑳屼功銆�<br/>
+                    10.  INSURANCE: <br/>
+                    To be covered by the Seller for 110% of the invoice value covering all risks and war risk, indicating claims payable in China, <br/>
+                    in currency of the draft, blank endorsed. 
+                </td>
+            </tr>
+
+            <tr>
+                <td colspan = "3">
+                    11. 浠樻鏂瑰紡: {!contra.order.PDF_PaymentTerms__c}锛�<br/>
+                    鎵�鏈夊洜浠樻鑰屽湪姹囨鏂归摱琛屽彂鐢熺殑鎵嬬画璐瑰強鍏跺畠璐圭敤锛屽潎鐢变拱鏂规壙鎷呫��<br/>
+                    11.  TERMS OF PAYMENT: {!contra.order.PDF_PaymentTerms_E__c}锛�<br/>
+                    All the bank charges and other expenses arising from the payment at the remitting bank shall be borne by the Buyer.<br/>
+                </td>
+            </tr>
+            </table>
+            <!--<apex:outputPanel layout="none">
+                <div style="page-break-after: always;"/>
+            </apex:outputPanel>-->
+            <table style="font-size: 9pt;">
+            <tr>
+                <td>
+                    12. 鎵�闇�鐨勬枃浠�: <br/>
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS'|| Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI') && Opp.TradeType__c = 'Taxation', 'true', 'false')}" layout="none">
+                    1)聽{!contra.order.PDF_Bi_Quality__c}浠界敱鍗栨柟鍑哄叿鐨勮川閲忓拰鏁伴噺璇佹槑;<br/>
+                    2) {!contra.order.PDF_Bi_Origin__c}浠藉崠鏂瑰嚭鍏风殑鍘熶骇鍦拌瘉鏄�;鍙�<br/>
+                    3) {!contra.order.PDF_Bi_Non_Wooden__c}浠介潪鏈ㄨ川鍖呰璇佹槑銆�<br/>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.TradeType__c = 'Tax Exemption', 'true', 'false')}" layout="none">
+                    璇峰湪鍙戣揣鍚巤!contra.order.PDF_Bi_q1__c}涓伐浣滄棩鍐呭皢浠ヤ笅鎵�闇�鐨勬枃浠朵紶鐪�/鐢甸偖缁欎拱鏂�;<br/>
+                    1) 绌鸿繍鎻愬崟姝f湰{!contra.order.PDF_Bi_airway__c}浠斤紝鍓湰{!contra.order.PDF_Bi_copyairway__c}浠姐�傚苟娉ㄦ槑鈥滆繍璐瑰凡浠樷��;<br/>
+                    2) 鍙戠エ{!contra.order.PDF_Bi_invoice__c}浠�, 娉ㄦ槑鍚堝悓鍙峰拰杩愯緭鏍囪瘑(濡傛湁涓�涓互涓婅繍杈撴爣璇�, 搴斿垎鍒嚭鍏峰彂绁�)鍙婂悎鍚屼腑鍏跺畠缁嗚妭;<br/>
+                    3) 濡備繚闄╃敱鍗栨柟璐熻矗鐨勬儏鍐典笅锛屽崠鏂归渶鎻愪緵淇濋櫓鍗晎!contra.order.PDF_Bi_Insurance__c}濂楋紝鎶曚竴鍒囬櫓锛� 鎸夊彂绁ㄩ噾棰�110锛呮姇淇濅竴鍒囬櫓;<br/>
+                    4) {!contra.order.PDF_Bi_Packing__c}浠界敱鍗栨柟鍑哄叿鐨勮绠卞崟;<br/>
+                    5)聽{!contra.order.PDF_Bi_Quality__c}浠界敱鍗栨柟鍑哄叿鐨勮川閲忓拰鏁伴噺璇佹槑;<br/>
+                    6) {!contra.order.PDF_Bi_Origin__c}浠藉崠鏂瑰嚭鍏风殑鍘熶骇鍦拌瘉鏄�;鍙�<br/>
+                    7) {!contra.order.PDF_Bi_Non_Wooden__c}浠介潪鏈ㄨ川鍖呰璇佹槑銆�<br/>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS' || Opp.ProductSegment__c = 'ANI' ||Opp.ProductSegment__c = 'NDT', 'true', 'false')}" layout="none">
+                    8) 鎵�鏈夊崟鎹� {!contra.order.PDF_Bi_AllBill__c}<br/>
+                    </apex:outputPanel>
+                    12. DOCUMENTS REQUIRED (please don鈥檛 attach any documents of contract value with the shipment):<br/>
+                    Please fax/e-mail the below required documents to the Buyer within {!contra.order.PDF_Bi_q1__c} working days after shipment;<br/>
+                    1) {!contra.order.PDF_Bi_airway__c} original and {!contra.order.PDF_Bi_copyairway__c} copy of clean air waybills marked 鈥渇reight prepaid鈥�;<br/>
+                    2) Invoice in {!contra.order.PDF_Bi_invoice__c} copies indicating contract number and shipping mark (in case of more than one shipping mark,the invoice shall be<br/>
+                     issued separately), made out in details as per relative contract;<br/>
+                    3) Insurance Policy/Certificate in one original and {!contra.order.PDF_Bi_Insurance__c} copies for 110% of the invoice value if the insurance is bought by the Seller;<br/>
+                    4) Packing list in {!contra.order.PDF_Bi_Packing__c} copies issued by the Seller;<br/>
+                    5)聽Certificate of Quality and Quantity in {!contra.order.PDF_Bi_Quality__c} copies issued by the Seller; <br/>
+                    6) Certificate of Origin in {!contra.order.PDF_Bi_Origin__c} copies issued by the Seller; and<br/>
+                    7) {!contra.order.PDF_Bi_Non_Wooden__c} Certificate of Non-wood material packing.<br/>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'BS', 'true', 'false')}" layout="none">
+                    8) All the documents  {!contra.AllBills}    cargo<br/>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI', 'true', 'false')}" layout="none">
+                    8) All the documents not with cargo
+                    </apex:outputPanel>
+                    </apex:outputPanel>
+                </td>
+            </tr>
+
+            <tr>
+                <td>
+                    13. 瑁呰繍閫氱煡锛�<br/>
+                    鍗栨柟搴斾簬鍙戣揣鍥涘崄鍏紙48锛夊皬鏃跺唴浠ヤ紶鐪熸垨鐢甸偖褰㈠紡鎻愪緵鍙戣揣閫氱煡鍛婄煡涔版柟鍚堝悓鍙枫�佽揣鐗╁悕绉般�佸疄瑁呮暟閲忋�侀噸閲忋�佷欢鏁般�佸彂绁ㄤ环<br/>
+                    鍊笺�佽埅鐝彿鍙婃棩鏈熴�佺┖杩愬崟鍙风瓑<br/>
+                    13. SHIPPING ADVICE: <br/>
+                    The Seller, within forty eight (48) hours after shipment is made, shall notify the Buyer of the contract no., name ofgoods, <br/>
+                    quantity,  weight loaded, number of packages, invoice value, flight number and date, air waybill number etc. by fax or email.<br/>
+                </td>
+            </tr>
+            <tr>
+                <td>
+                    14. 璐ㄩ噺淇濊瘉锛�<br/>
+                    A. 鍗栨柟淇濊瘉鏈悎鍚屼箣璐х墿鏄敤鏈�濂界殑鏉愭枡浠ヤ笂绛夌殑宸ヨ壓鍒堕�狅紝宕柊鍙婃湭鐢ㄨ繃鐨勶紝鍏惰川閲忎笌瑙勬牸涓�鍒囨柟闈笌鏈悎鍚岀殑瑙勫畾鐩哥銆�<br/>
+                    淇濊瘉鏈熶负鏈�缁堥獙鏀舵姤鍛婄缃蹭箣鏃ヨ捣鐨� {!contra.order.PDF_QA__c} 浣嗕笉瓒呰繃鍙戣揣鏃ュ悗鐨� {!contra.order.PDF_QA2__c} <br/>
+                    鍦ㄤ繚璇佹湡鍐咃紝濡備拱鏂规寜鐓ц揣鐗╀娇鐢ㄨ鏄庝功鍦ㄦ甯告潯浠朵笅浣跨敤锛岀敱浜庡崠鏂硅璁℃垨鍒堕�犱笂鐨勭己闄疯�屽彂鐢熺殑鎹熷潖锛岀敱鍗栨柟璐熻矗銆�<br/>
+                    鍦ㄤ繚璇佹湡鍐呭鏋滆揣鐗╃殑閲嶈闆堕儴浠堕渶瑕佹洿鎹紝鍒欒闆堕儴浠剁殑淇濊瘉鏈熶粠鏇存崲涔嬫棩璧烽噸鏂拌绠楋紝澶栬喘浠朵互鍘熶緵搴斿晢鐨勪繚璇佹湡涓哄噯銆�<br/>
+                    B. 濡傛灉鍙屾柟鍏卞悓鍟嗗畾骞剁‘璁ょ殑渚涜揣鑼冨洿涓湁閬楁紡鐨勯儴浠跺拰璁惧骞舵湁鍙兘瀵艰嚧鏁村璐х墿涓嶈兘鎸夋椂楠屾敹鎶曚骇鎴栧奖鍝嶇敓浜э紝鍗栨柟<br/>
+                    鏈変箟鍔″拰璐d换鍦ㄥ埗閫犺繃绋嬩腑涓庝拱鏂瑰晢閲忓仛鍑虹浉搴旂殑璋冩暣鍜岃ˉ鏁戯紝骞朵繚璇佹暣濂椾互涓婅揣鐗╄兘閫氳繃楠屾敹銆�<br/>
+                    C. 鏈悎鍚屼腑鎵�杩扮殑淇濊瘉鏄�傜敤浜庢牴鎹悎鍚岃揣鐗╂彁渚涚殑鐨勫敮涓�淇濊瘉銆傛湰淇濊瘉鏉℃鍙栦唬骞舵帓闄ゆ硶寰嬨�佹儻渚嬨�佹硶浠ゆ垨鍏朵粬瑙勫畾鏂藉姞<br/>
+                    鎴栭粯绀虹殑浠讳綍鍏朵粬鎷呬繚銆佷繚璇佸拰/鎴栨潯浠跺拰/鎴栧洜姝よ�屼骇鐢熺殑璐d换銆傚浜庝换浣曟湁缂洪櫡鐨勬垨涓嶇鍚堟爣鍑嗙殑璐х墿锛屼拱鏂规墍閫傜敤鐨勫彧鏈�<br/>
+                    鏈潯鐗瑰埆瑙勫畾鐨勬晳娴庛��<br/>
+                    14. WARRANTY锛�<br/>
+                    A锛嶵he Seller warrant that the goods hereof is made of the best materials with first class workmanship, brand new and unused and<br/>
+                     complies in all respects with the quality and specification stipulated in this Contract. <br/>
+                    The warranty period shall be  {!contra.QAeng} <br/>
+                    counting from the date on which the goods have been accepted by the end user but limited to a maximum of<br/>
+                      {!contra.QAeng2} from the date of shipment. <br/>
+                    Within the warranty period, the Seller shall be liable for the damage incurred on account of the defects attributable to the design<br/>
+                     and emerging during the course of manufacturing of the Seller鈥檚 side if the Buyer operate under regular conditions in accordance<br/>
+                     with the instruction to the equipments or the machines. Within the warranty period, if some important units and parts of the goods<br/>
+                     need to change, the warranty period of the new units and parts should be counted from the changing date. If the new units and<br/>
+                      parts are bought from the third party, the warranty period of the new units and parts should be counted according to the original suppliers.<br/>
+                    B锛嶪n case there鈥檚 any missing parts &amp; machines which are out of the agreed scope of supply and most possibly would influence <br/>
+                    the commissioning or production on time, the Seller has the obligation and responsibility to discuss with Buyer to make concerned <br/>
+                    adjustments and amendments to warrant the acceptance of the goods.<br/>
+                    C. The warranty set out in this Contract is the only warranty applicable to the goods supplied pursuant to this Contract. This<br/>
+                    warranty replaces and excludes any other guarantee, warranty and/or condition imposed or implied by law, custom, statute or <br/>
+                    otherwise and/or resulting liabilities. Only those remedies specifically set out in this clause are available to the Buyer<br/>
+                    in respect of any defective or non-conforming goods.<br/>
+                </td>
+            </tr>
+        </table>
+        <!--<apex:outputPanel layout="none">
+            <div style="page-break-after: always;"/>
+        </apex:outputPanel>-->
+        <table style="font-size: 9pt;">
+            <tr>
+                <td>
+                    15. 妫�楠屼笌绱㈣禂锛�<br/>
+                    锛�1锛変氦璐т箣鍓嶏紝鍒堕�犲巶搴斿璐х墿鐨勮川閲忚鏍笺�佹�ц兘鍜屾暟閲忚繘琛岀簿纭拰鍏ㄩ潰鐨勬鏌ュ苟鍑哄叿璇佹槑璐х墿涓庢湰鍚堝悓瑙勫畾鐩哥鐨勮瘉鏄庝功銆�<br/>
+                    锛�2锛夎揣鐗╁埌鐩殑娓垨鐩殑鍦板悗90澶╁唴锛屼互杈冩棭鑰呬负鍑嗭紝涔版柟鎳夊悜涓浗鍑哄叆澧冩楠屾鐤眬鐢宠瀵规湁鍏宠揣鐗╃殑璐ㄩ噺銆佽鏍煎拰鏁伴噺杩�<br/>
+                    琛屽垵姝ユ楠屽苟鐢卞叾鍑哄叿妫�楠屾姤鍛娿�傚涓浗鍑哄叆澧冩楠屾鐤眬鍙戠幇鍒拌揣鐗╃殑瑙勬牸鎴�/鍜屾暟閲忎笌鏈悎鍚岃瀹氫笉绗︼紝闄ゅ簲鐢变繚闄╁叕鍙告垨<br/>
+                    鑸硅繍鍏徃璐熻矗澶栵紝涔版柟鏈夋潈鎷掓敹璐х墿鎴栧悜鍗栨柟鎻愬嚭璧斿伩銆�<br/>
+                    锛�3锛夊璐х墿鐨勮川閲忓拰瑙勬牸涓庢湰鍚堝悓涓嶇锛屾垨鍦ㄦ湰鍚堝悓绗�13鏉¤瀹氱殑淇濊瘉鏈熷唴璇佹槑璐х墿鏈夌己闄凤紝涔版柟搴旂敵璇蜂腑鍥藉嚭鍏ュ妫�楠屾鐤�<br/>
+                    灞�妫�楠岋紝骞舵湁鏉冩牴鎹妫�楠屾姤鍛婂悜鍗栨柟鎻愬嚭绱㈣禂銆�<br/>
+                    锛�4锛夊崠鏂瑰涓庢湰鍚堝悓涓嶇閮ㄥ垎锛屽簲鍦ㄥ悎鐞嗙殑鏈熼檺鍐呮棤鍋挎崲璐ф垨琛ュ彂鐭己鎴栬船浣庤揣浠凤紝骞惰礋鎷呯敱姝や骇鐢熺殑涓�鍒囪垂鐢ㄥ拰鎹熷け锛屽寘鎷細<br/>
+                    鍒╂伅銆侀摱琛岃垂鐢ㄣ�佽繍璐广�佷繚闄╄垂銆佹楠岃垂銆佷粨鍌ㄣ�佺爜澶磋鍗歌垂浠ュ強鍏朵粬涓�鍒囧繀瑕佽垂鐢ㄣ��<br/>
+                    15. INSPECTION AND CLAIMS:<br/>
+                    锛�1锛塗he manufacturer shall锛宐efore making delivery锛宮ake a precise and comprehensive inspection of the goods with regard<br/>
+                     to the quality, specification and quantity and issue certificates certifying that the goods are in conformity with the stipulations of<br/>
+                      the Contract. <br/>
+                    锛�2锛塛ithin ninety (90) days after arrival of the goods at the port of destination or the place of destination, whichever is the earlier,<br/>
+                      the Buyer shall apply to the China Entry &amp; Exit Inspection &amp; Quarantine Bureau (CIQ) for a preliminary inspection in respect of the<br/>
+                      quality, specification and quantity of the goods and a survey report shall be issued thereof. If discrepancies are found by the CIQ<br/>
+                      regarding specifications or the quantity or both, except when the responsibilities lie with Insurance Company or Shipping Company,<br/>
+                      the Buyer has the right to reject the goods or to claim against the Seller.<br/>
+                    锛�3锛塖hould the quality and specification of the goods not in conformity with the Contract or should the goods be proved defective <br/>
+                    during the warranty period stipulated in Clause 13, the Buyer shall arrange for a survey to be carried out by the CIQ and have the<br/>
+                     right to claim against the Seller on the strength of the survey report.<br/>
+                    锛�4锛塅or any goods which are not in conformity with the Contract, the Seller锛寃ithin a reasonable time锛宻hall make replacement <br/>free of charge锛宒eliver the short ones or devalue the goods and bear all the charges and losing incurred thereof. The charges <br/>include interest, banking charges, freight, premium, inspecting charges, storing charges, discharging charges and other charges <br/>incurred since the goods are not in conformity with the contract.  
+                </td>
+            </tr>
+            <!-- </table>
+            <apex:outputPanel layout="none">
+                <div style="page-break-after: always;"/>
+            </apex:outputPanel> 
+            <table style="font-size: 9pt;">-->
+                <tr>
+                    <td>
+                        16. 浜哄姏涓嶅彲鎶楁嫆浜嬫晠锛�<br/>
+                        鐢变簬鍦ㄧ敓浜с�佽杩愯繃绋嬩腑鍙戠敓鐨勪汉鍔涗笉鍙姉鎷掍簨鏁咃紙濡傦細鎴樹簤銆佷弗閲嶇伀鐏俱�佹按鐏俱�佸彴椋庛�佸湴闇囦互鍙婂弻鏂瑰潎璁や负灞炰簬浜轰笉鍙姉鎷掍簨鏁咃級<br/>
+                        鑰屼娇寰楀崠鏂瑰欢鏈熻鑸规垨涓嶈兘浜よ揣锛屽崠鏂瑰彲涓嶈礋鎷呰矗浠汇�備絾鏄崠鏂瑰簲鍦ㄤ笂杩颁簨鏁呭彂鐢熷悗绔嬪嵆浼犵湡閫氱煡涔版柟锛屽苟鍦ㄤ紶鐪熷悗14澶╁唴锛屾彁渚�<br/>
+                        涓嶅彲鎶楁嫆浜嬫晠鍙戠敓鍦板煙鐨勪富绠℃斂搴滃綋灞�鎴栧晢浼氬嚭鍏风殑璇佷欢锛岀┖閭氦涔版柟浠ヨ祫璇佹槑銆傚湪姝ゆ儏鍐典笅锛屽崠鏂逛粛椤婚噰鍙栦竴鍒囧繀瑕佹帾鏂藉姞閫熻揣<br/>
+                        鐗╃殑鍙戣繍銆傚涓嶅彲鎶楁嫆浜嬫晠寤剁画90澶╀互涓婏紝浠讳綍涓�鏂规湁鏉冨悜鍙︿竴鏂瑰彂鍑轰功闈㈤�氱煡涓鏈悎鍚屻��<br/>
+                        16. FORCE MAJEURE:<br/>
+                        The Seller shall not be held responsible for the delay in shipment or non-delivery of the goods due to force majeure, such as war,<br/>
+                         serious fire, flood, typhoon and earthquake occur during the process of manufacturing or in the course of loading or transit. The<br/>
+                         Seller shall immediately advise the Buyer by fax of the occurrence mentioned above and within fourteen (14) days thereafter, the<br/>
+                         Seller shall send by airmail to the Buyer for their acceptance a certificate of the accident issued by the competent government<br/>
+                         authorities or the Chamber of Commerce where the accident occurs as evidence thereof. Under such circumstance the Seller, <br/>
+                         however, are still under the obligation to take all necessary measures to hasten the delivery of the goods. In case the accident lasts <br/>
+                         for more than ninety (90) days, both parties shall have the right to terminate this Contract by written notice to the other party.
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        17. 杩熶氦璐х墿鍙婅繚绾﹂噾锛�<br/>
+                        闄ゆ湰鍚堝悓绗�15鏉℃墍瑙勫畾鐨勪笉鍙姉鎷掍簨鏁呭師鍥犲锛屽鍗栨柟涓嶈兘鎸夊悎鍚岃瀹氬噯鏃朵氦璐э紝鍦ㄥ崠鏂瑰悓鎰忔壙鎷�<br/>
+                        杩熶氦杩濈害閲戝苟鐢变粯娆鹃妧琛屽湪鏀粯璐ф鏃舵墸闄ょ殑鏉′欢涓嬶紝涔版柟搴斿悓鎰忓欢鏈熶氦璐с�備絾杩熶氦杩濈害閲戞�婚涓�<br/>
+                        鎳夎秴杩囧悎鍚屾�婚鐨�5%銆傝繜浜よ繚绾﹂噾鐜囦负姣忎竷(7)澶╁崈鍒嗕箣浜旓紝涓嶈冻涓�(7)澶╄�呭簲鎸変竷(7)澶╄绠椼��<br/>濡傚欢鏈熶氦璐ц秴杩囨湰鍚堝悓鎵�瑙勫畾鐨勮杩愭湡鍗�(10)鍛紝涔版柟鏈夋潈鍚戝崠鏂瑰彂鍑轰功闈㈤�氱煡涓鏈悎鍚屻��<br/>
+                        17. LATE DELIVERY AND LIQUIDATED DAMAGES: <br/>
+                        Should the Seller fail to make delivery on time as stipulated in the Contract with the exception of force majeure causes specified in <br/>
+                        Clause 15 of this Contract, the Buyer shall agree to postpone the delivery on the condition that the Seller agree to pay a liquidated <br/>
+                        damages which shall be deducted by the paying bank from the payment under negotiation. The liquidated damages, however, shall<br/>
+                         not exceed five percent (5%) of the total value of the goods involved in the late delivery. The rate of liquidated damages is charge <br/>
+                         at one half percent (0.5%) for every seven (7) days, odd days less than seven (7) days should count as seven (7) days. In case the<br/> 
+                         late delivery exceed ten (10) weeks of the time of shipment stipulated in the Contract, the Buyer shall have the right to terminate<br/> 
+                         this Contract by written notice to the Seller.<br/>
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        18. 涓撳埄鏉冿細<br/>
+                        鍗栨柟蹇呴』淇濋殰涔版柟鍦ㄤ腑鍥戒娇鐢ㄥ叾璐х墿鍙婂叾浠讳綍閮ㄥ垎涓嶅彈鍒扮涓夋柟鍏充簬渚电姱涓撳埄鏉冦�佸晢鏍囨潈鎴栧伐涓氳璁℃潈鐨勬寚鎺с�備换浣曠涓夋柟濡傛灉鎻愬嚭渚�<br/>
+                        鏉冩寚鎺э紝鍗栨柟椤讳笌绗笁鏂逛氦娑夊苟鎵挎媴鐢辨寮曡捣鐨勪竴鍒囨硶寰嬭矗浠诲拰璐圭敤銆�<br/>
+                        18. PATENT RIGHTS<br/>
+                        The Seller shall indemnify the Buyer against all third-party claims of infringement of patent, trademark, or industrial design rights <br/>
+                        arising from use of the goods or any part thereof in China. In case any third party brings a charge of infringement, the Seller shall<br/>
+                         negotiate with the third-party and be liable for any legal duty and expenses.<br/>
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        19. 鍚堝悓鏂囦欢鍙婅祫鏂欑殑浣跨敤: <br/>
+                        锛�1锛夊湪鏈粡涔版柟涔﹂潰鍚屾剰鐨勬儏鍐典笅锛屽崠鏂逛笉寰楀皢鐢变拱鏂规垨浠h〃涔版柟鎻愪緵鐨勬湁鍏冲悎鍚屾潯鏂囥�佽鏍笺�佽鍒掋�佸浘绾搞�佹ā鍨嬨�佹牱鍝佹垨璧勬枡鎻愪緵<br/>
+                        缁欎笌灞ヨ鏈悎鍚屾棤鍏崇殑浠讳綍浜恒�傚嵆浣垮悜涓庡饱琛屾湰鍚堝悓鏈夊叧鐨勪汉鍛樻彁渚涳紝涔熷簲娉ㄦ剰淇濆瘑骞朵粎闄愪簬灞ヨ鍚堝悓蹇呴』鐨勮寖鍥淬��<br/>
+                        锛�2锛夐櫎闈炴墽琛屽悎鍚岄渶瑕侊紝鍦ㄤ簨鍏堟湭寰楀埌涔版柟涔﹂潰鍚屾剰鐨勬儏鍐典笅锛屽崠鏂逛笉寰椾娇鐢ㄦ潯娆撅紙1锛変腑鎵�鍒椾妇鐨勪换浣曟枃浠跺拰璧勬枡銆�<br/>
+                        锛�3锛夐櫎鍚堝悓鏈韩澶栵紝鏉℃锛�1锛夊垪鏄庣殑鎵�鏈夋枃浠跺缁堜负涔版柟鐨勮储浜э紝鑻ヤ拱鏂硅姹傦紝鍗栨柟搴斾簬鍏跺悎鍚屼箟鍔″饱琛屽畬姣曚互鍚庡皢杩欎簺鏂囦欢鍙婂叏<br/>
+                        閮ㄥ鍒朵欢閫�杩樼粰涔版柟銆�<br/>
+                        19. USE OF CONTRACT鈥橲 DOCUMENTS AND INFORMATION: <br/>
+                        (1) The Seller shall not, without the Buyer鈥檚 prior written consent, disclose this Contract, or any provision hereof, or any<br/>
+                         specification, plan, drawing, pattern, sample, or information furnished by or on behalf of the Buyer in connection therewith, to any <br/>
+                         person other than the person employed by the Seller in the performance of this Contract. Disclosure to any such employed person<br/> 
+                         shall be made in confidence and shall extend only so far as may be necessary for purposes of such performance. <br/>
+                        (2) The Seller shall not, without the Buyer鈥檚 prior written consent, make use of any document or information enumerated in<br/>
+                         Clause (1) except for purposes of performing this Contract.<br/>
+                        (3) Any document, other than this Contract itself, enumerated in Clause (1) shall remain the property of the Buyer and shall be<br/>
+                         returned (including all copies) to the Buyer on completion of the Seller鈥檚 performance under this Contract if so required by the Buyer. <br/>
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        20. 浠茶锛�<br/>
+                        涓庢湰鍚堝悓鏈夊叧鐨勬垨鍥犳墽琛屾湰鍚堝悓鎵�鍙戠敓鐨勪竴鍒囦簤鎵э紝鐢辩璁㈠悎鍚岀殑鍙屾柟鍙嬪ソ鍗忓晢瑙e喅銆傝嫢涓嶈兘瑙e喅鏃讹紝妗堜欢鍙彁浜や腑鍥藉浗闄呯粡娴庤锤鏄�<br/>
+                        浠茶濮斿憳浼氫徊瑁併�備徊瑁佹寜鍘熷悎鍚岃繘琛屻�備徊瑁佸鍛樹細鐨勮鍐充负鏈�缁堝喅瀹氾紝绛剧害鍙屾柟閮藉簲鏈嶄粠锛涗换浣曚竴鏂瑰潎涓嶅緱鍚戞硶闄㈡垨鍏朵粬褰撳眬姹傚姪鐢�<br/>
+                        璇蜂慨鏀硅瑁佸喅銆傛垨鑰呭湪鍙屾柟鍚屾剰鐨勭涓夊浗鎴栧湴鍖鸿繘琛屼徊瑁併�備徊瑁佽垂鐢ㄧ敱鍙屾柟鏂硅礋鎷呫�傚湪浠茶鏈熼棿锛岄櫎浜嗗湪浠茶杩囩▼涓繘琛屼徊瑁佺殑閮ㄥ垎<br/>
+                        澶栵紝鏈悎鍚屽簲缁х画鎵ц銆�<br/>
+                        20. ARBITRA<br/>                        
+                        All disputes in connection with this Contract or the execution thereof shall be settled friendly through negotiation by the parties hereof.<br/> 
+                        In case no settlement can be reached, the case may then be submitted for arbitration to the China International Economic and Trade<br/> 
+                        Arbitration Commission, in accordance with the Rulers of Procedures promulgated by they said Arbitration Commission. The <br/>
+                        arbitration shall take place in China and the decision of the Arbitration Commission shall be final and binding upon both parties, <br/>
+                        neither party shall seek recourse to a law court or other authorities to appeal to revision of the decision. Or the  arbitration may be <br/>
+                        taken place in a third country or place mutually agreed by both parties. Arbitration fee shall be borne by continue to execute<br/>
+                         this Contract except those under arbitration. <br/>
+                    </td>
+                </tr>
+            </table>
+            <!-- <apex:outputPanel layout="none">
+                <div style="page-break-after: always;"/>
+            </apex:outputPanel> -->
+            <table style="font-size: 9pt;">
+                <colgroup>
+                    <col width="50%"/>
+                    <col width="50%"/>
+                </colgroup>
+                <tr>
+                    <td colspan = "2">
+                        21. 杩涘嚭鍙h鍙瘉锛�<br/>
+                        杩涘彛鏈悎鍚岄」涓嬭揣鐗╂墍闇�鐨勪腑鍥芥斂搴滃強娴峰叧瑕佹眰鐨勮繘鍙h鍙瘉鍜屽叾浠栬繘鍙f枃浠剁敱涔版柟璐熻矗鍔炵悊銆傚嚭鍙f湰鍚堝悓椤逛笅璐х墿鎵�闇�鐨勫嚭鍙e浗鏀�<br/>
+                        搴滃強娴峰叧瑕佹眰鐨勫嚭鍙h鍙瘉鍜屽叾浠栧嚭鍙f枃浠剁敱鍗栨柟璐熻矗鍔炵悊銆�<br/>
+                        21. IMPORT AND EXPORT LICENCES: <br/>
+                        It is the responsibility of the Buyer to arrange import licenses or other import documents, if required for the goods covered by this <br/>
+                        Contract from the Chinese Government and Custom at the Buyer鈥檚 expense. It is the responsibility of the Seller to arrange export<br/>
+                         licenses or other export documents, if required for the Goods covered by this Contract from its country Government and Custom at<br/>
+                          the Seller鈥檚 expense.<br/>
+                    </td>
+                </tr>
+                <tr>
+                    <td colspan = "2">
+                        22. 绋庤垂锛�<br/>
+                        涓浗鏀垮簻鏍规嵁鐜拌绋庢硶鍚戜拱鏂瑰緛鏀剁殑涓庡饱琛屾湰鍚堝悓鏈夊叧鐨勪竴鍒囩◣璐圭敱涔版柟鏀粯銆�<br/>
+                        涓浗鏀垮簻鏍规嵁鐜拌绋庢硶鍚戝崠鏂瑰緛鏀剁殑涓庡饱琛屾湰鍚堝悓鏈夊叧鐨勪竴鍒囩◣璐圭敱鍗栨柟鏀粯銆�<br/>
+                        鍙戠敓鍦ㄤ腑鍥藉澶栫殑锛屼笌灞ヨ鏈悎鍚屾湁鍏崇殑涓�鍒囩◣璐癸紝搴旂敱鍗栨柟鎵挎媴銆�<br/>
+                        22. TAX AND DUTIES锛�<br/>
+                        All taxes in connection with the execution of this Contract levied by the Chinese Government on the Buyer in accordance with the<br/>
+                         tax laws in effect shall be borne by the Buyer.All taxes in connection with the execution of this Contract levied by the Chinese<br/>
+                         Government on the Seller in accordance with the tax laws in effect shall be borne by the Seller. All taxes arising outside China in<br/>
+                         connection with the execution of this Contract shall be borne by the Seller. <br/>
+                    </td>
+                </tr>
+                <tr>
+                    <td colspan = "2">
+                        23.閫傜敤娉曞緥锛�<br/>
+                        鏈悎鍚屽簲鎸夌収涓崕浜烘皯鍏卞拰鍥界殑娉曞緥绠¤緰鍙婅В閲娿��<br/>
+                        23. APPLICABLE LAW锛�<br/>
+                        This Contract shall be governed and construed in accordance with the laws of People鈥檚 Republic of China.<br/> 
+                    </td>
+                </tr>
+                <tr>
+                    <td colspan = "2">
+                        24.鍏朵粬:<br/>
+                        锛�1锛夋湰鍚堝悓搴斾互涓枃鍜岃嫳鏂囦功鍐欙紝濡備腑鏂囧拰鑻辨枃鐗堟湰涔嬮棿鏈変换浣曚笉涓�鑷达紝鍒欎互鑻辨枃鏈负涓汇�傛妧鏈浘绾革紝涔板崠鍙屾柟鐨勬墍鏈夊嚱鐢典互鍙婁笌鍚�<br/>
+                        鍚屾湁鍏崇殑鏂囦欢鍧囧簲浠ヤ腑鏂囨垨鑻辨枃涔﹀啓銆�<br/>
+                        锛�2锛夐櫎鎶�鏈鏍间腑鍙︽湁瑙勫畾澶栵紝璁¢噺鍗曚綅鍧囦娇鐢ㄥ叕鍒躲��<br/>
+                        锛�3锛夋瀵瑰悎鍚屾潯娆惧仛鍑轰换浣曚慨鏀癸紝鍧囬』鐢变拱鍗栧弻鏂圭缃蹭功闈㈢殑鍚堝悓淇敼涔︺��<br/>
+                        锛�4锛夋湰鍚堝悓鎵�鏈夐檮浠跺皢鏄湰鍚堝悓涓嶅彲鍒嗗壊鐨勭粍鎴愰儴鍒嗗苟鍏锋湁鍚岀瓑鏁堝姏銆�<br/>
+                        锛�5锛夋湭鍦ㄦ湰鍚堝悓涓鏄庣殑鍟嗗姟鎯緥搴旂鍚圛NCOTERMS 2000鏉℃鐨勮瀹氥��<br/>
+                        锛�6锛夋湰鍚堝悓鐢变拱鍗栧弻鏂圭璁㈠悗绔嬪嵆鐢熸晥銆�<br/>
+                        &nbsp;&nbsp;姝ゅ悎鍚岀敱涔板崠鍙屾柟绛剧讲姝f湰 {!contra.order.PDF_Co_Contract__c}浠姐�� 涔版柟鎸佹湁 {!contra.order.PDF_Co_BContra__c}浠姐�� 鍗栨柟鎸佹湁 {!contra.order.PDF_Co_SContra__c}浠姐��<br/>
+                        24. OTHERS:<br/>
+                        锛�1锛塗his Contract shall be written in both Chinese and English, in case there is any inconsistency between the Chinese version <br/>
+                        and the English version, the English version shall prevail. The technical drawings, all correspondence and other documents <br/>pertaining to this Contract exchanged by the parties shall be written in Chinese or English.<br/>
+                        锛�2锛堿ll measurement shall be in SI unit, unless otherwise specified in the Technical Specifications.<br/>
+                        锛�3锛塏o variation in or modification of the terms of this Contract shall be valid except by written amendment signed by the parties.<br/>
+                        锛�4锛堿ll appendixes to this Contract shall be formed as an integral part of this Contract and shall be equally effective.<br/>
+                        锛�5锛� The commercial customs not described in this Contract shall be in accordance with the terms and conditions of INCOTERMS <br/>
+                        2000.<br/>
+                        锛�6锛塗his Contract shall become effective upon execution by the Buyer and the Seller. <br/>
+                        Both parties sign this Contract in {!contra.order.PDF_Co_Contract_E__c} .The buyer holds {!contra.order.PDF_Co_BContra_E__c} .The seller holds {!contra.order.PDF_Co_SContra_E__c} .<br/>
+                    </td>
+                </tr>
+                <tr>
+                    <td style="vertical-align: top;">
+                        鍗栨柟锛�&nbsp;&nbsp;浠櫙閫氬厜瀛︾鎶�锛堜笂娴凤級鏈夐檺鍏徃
+                    </td>
+                    <td style="vertical-align: top;">
+                        涔版柟锛�&nbsp;&nbsp;{!specialDeliveryAddress.Name}
+                    </td>
+                </tr>
+                <tr>
+                    <td style="vertical-align: top;">
+                        THE SELLER:&nbsp;&nbsp;Evident Corporation
+                    </td>
+                    <td style="vertical-align: top;">
+                        THE BUYER:&nbsp;&nbsp;{!specialDeliveryAddress.EnglishName__c}
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        For and on behalf of&nbsp;&nbsp;
+                    </td>
+                    <td>
+                        For and on behalf of&nbsp;&nbsp;
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        [*]&nbsp;&nbsp;
+                    </td>
+                    <td>
+                        [*]&nbsp;&nbsp;
+                    </td>
+                </tr>
+                <tr><td colspan = "2" height="100px"></td></tr>
+                <tr>
+                    <td>
+                        绛惧悕锛�&nbsp;&nbsp;
+                    </td>
+                    <td>
+                        绛惧悕锛�&nbsp;&nbsp;
+                    </td>
+                </tr>
+                <tr>
+                    <!-- <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'false', 'true')}" layout="none">
+                        <td>
+                        Name: &nbsp;&nbsp;Mitsuyuki Shirakawa
+                        </td>
+                    </apex:outputPanel>
+                    <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'true', 'true')}" layout="none"> -->
+                    <td>
+                    Name: &nbsp;&nbsp;Wei Liu
+                    </td>
+                    <!-- </apex:outputPanel> -->
+                    <td>
+                        Name: &nbsp;&nbsp;{!contra.order.PDF_Sign_Name__c}
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        Title: &nbsp;&nbsp;Division Manager
+                    </td>
+                    <td>
+                        Title: &nbsp;&nbsp;{!contra.order.PDF_Sign_Title__c}
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        鏃ユ湡锛�&nbsp;&nbsp;
+                    </td>
+                    <td>
+                        鏃ユ湡锛�&nbsp;&nbsp;
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        Signed on&nbsp;&nbsp;
+                    </td>
+                    <td>
+                        Signed on&nbsp;&nbsp;
+                    </td>
+                </tr>
+            </table>
+            <apex:outputPanel layout="none">
+                <div style="page-break-after: always;"/>
+            </apex:outputPanel>
+            <table width="100%">
+                <tr>
+                    <td style="text-align: center;">闄勪欢</td>
+                </tr>
+                <tr>
+                    <td style="text-align: center;">Appendix</td>
+                </tr>
+            </table>
+            <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'false', 'true')}" layout="none">
+            <apex:variable value="{!1}" var="cnt1" />
+            <apex:repeat value="{!printRecords}" var="set">
+                <apex:repeat value="{!set.setPage}" var="sp">
+
+                    <table width="100%" border="1" cellspacing="0" cellpadding="0" style="table-layout:auto;font-size: 9pt;">
+                        <tr>
+                            <!-- <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'false', 'true')}" layout="none"> -->
+                                <td width="50%" style="text-align: center;">EC Code</td>
+                                <td style="text-align: center;">Quantity</td>
+                         <!--    </apex:outputPanel> -->
+                          <!--   <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'true', 'false')}" layout="none">
+                                <td width="25%" style="text-align: center;">U8 Code</td>
+                                <td width="25%" style="text-align: center;">Part Number</td>
+                                <td width="25%" style="text-align: center;">Quantity</td>
+                                <td style="text-align: center;">Name of Goods</td>
+                            </apex:outputPanel> -->
+                        </tr>
+                       <!--  <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'false', 'true')}" layout="none"> -->
+                            <tr>
+                                <td width="50%" style="text-align: center;">EC缂栫爜</td>
+                                <td style="text-align: center;">鏁伴噺</td>
+                            </tr>
+                       <!--  </apex:outputPanel> -->
+                        <apex:repeat value="{!sp}" var="line">
+                        <tr>
+                            <!-- <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'false', 'true')}" layout="none"> -->
+                                <td style="text-align: center;"><apex:outputText value="{!line.productEC}" /></td>
+                                <td style="text-align: center;"><apex:outputText value="{!line.quantity}" /></td>
+                            <!-- </apex:outputPanel> -->
+                           <!--  <apex:outputPanel rendered="{!IF((Opp.ProductSegment__c = 'NDT' || Opp.ProductSegment__c = 'ANI' ), 'true', 'false')}" layout="none">
+                                <td width="25%" style="text-align: center;"><apex:outputText value="{!line.U8Code}" /></td>
+                                <td width="25%" style="text-align: center;"><apex:outputText value="{!line.productEC}" /></td>
+                                <td width="25%" style="text-align: center;"><apex:outputText value="{!line.quantity}" /></td>
+                                <td style="text-align: center;"><apex:outputText value="{!line.productName}" /></td>
+                            </apex:outputPanel> -->
+                        </tr>
+                        </apex:repeat>
+                    </table>
+
+                <!-- <apex:outputPanel rendered="{!cnt1 < pageCnt - 1}" layout="none">
+                    <div style="page-break-after: always;"/>
+                </apex:outputPanel> -->
+                <apex:variable value="{!cnt1 + 1}" var="cnt1" />
+
+                </apex:repeat>
+            </apex:repeat>
+        </apex:outputPanel>
+        
+         <apex:outputPanel rendered="{!IF(Opp.ProductSegment__c = 'IE' || Opp.ProductSegment__c = 'RVI' || Opp.ProductSegment__c = 'BS' , 'false', 'true')}" layout="none" >
+            
+             <table width="100%" border="1" cellspacing="0" cellpadding="0" style="table-layout:auto;font-size: 9pt;">
+                <tr>
+                    <td width="25%" style="text-align: center;">U8 Code</td>
+                    <td width="25%" style="text-align: center;">Part Number</td>
+                    <td width="25%" style="text-align: center;">Quantity</td>
+                    <td style="text-align: center;">Name of Goods</td>
+                </tr>
+                <apex:repeat value="{!ndtList}" var="ndt">
+                    <tr>
+                        
+                        <td style="text-align: center;"><apex:outputText value="{!ndt.U8_Code__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!ndt.Part_Number__c}" style="width: 95%"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!ndt.Quantity__c}" style="width: 95%; text-align: center;"/></td>
+                        <td style="text-align: center;"><apex:outputText value="{!ndt.Name_of_Goods__c}" style="width: 95%"/></td>
+                    </tr>
+                </apex:repeat>
+            </table>
+        </apex:outputPanel> 
+
+    </body> 
+</html>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderPDF.page-meta.xml b/scr/pages/OrderPDF.page-meta.xml
new file mode 100644
index 0000000..7a27b68
--- /dev/null
+++ b/scr/pages/OrderPDF.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderPDF</label>
+</ApexPage>
diff --git a/scr/pages/OrderPdf2.page b/scr/pages/OrderPdf2.page
new file mode 100644
index 0000000..682afbf
--- /dev/null
+++ b/scr/pages/OrderPdf2.page
@@ -0,0 +1,527 @@
+<apex:page Controller="OrderPdf2Controller" showHeader="false" sidebar="false" id="allPage" action="{!init}" renderAs="pdf" > <!-- renderAs="pdf" -->
+<head>
+    <style>
+        @page {
+            size: A4 landscape;
+            margin: 12mm 12mm 5mm 12mm;
+
+            @bottom-center {
+                content: counter(page) " / " counter(pages);
+            }
+        }
+
+        table { border-collapse: collapse; }
+
+        td.border-thick-title { border-width: 1pt 0pt 1pt 0pt; border-style: solid; border-color: black; text-align: center;}
+        td.border-thick-bottom { border-width: 0pt 0pt 1pt 0pt; border-style: solid; border-color: black; text-align: center;}
+        td.detail { text-align: center; }
+    </style>
+</head>
+<body style="font-family: Arial Unicode MS; page-break-inside: auto; font-size: 8pt;">
+    <table border="0" width="100%">
+        <tr>
+            <td style="text-align: center; font-size: 16pt;">瀹岀◣璁㈣揣鍗�</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="35%"/>
+            <col width="10%"/>
+            <col width="40%"/>
+        </colgroup>
+        <tr>
+            <apex:outputPanel rendered="{!IF(productSegment == 'BS', false, true)}" layout="none">
+                <td style="text-align: right;">涔版柟锛�</td>
+                <td style="text-align: left;">{!header.buyer_name}</td>
+                <td style="text-align: right;">鍗栨柟锛�</td>
+                <td style="text-align: left;">{!header.seller_name}</td>
+            </apex:outputPanel>
+             <apex:outputPanel rendered="{!IF(productSegment == 'BS', true, false)}" layout="none">
+                <td style="text-align: right;">璐揣鑰咃細</td>
+                <td style="text-align: left;">{!header.buyer_name}</td>
+                <td style="text-align: right;">渚涜揣鑰咃細</td>
+                <td style="text-align: left;">{!header.seller_name}</td>
+            </apex:outputPanel>
+        </tr>
+
+        <apex:outputPanel rendered="{!IF(productSegment == 'BS', true, false)}" layout="none">
+            <tr>
+                <td style="text-align: right;" >浜岀被缁忚惀澶囨鍑瘉锛�</td>
+                <td style="text-align: left;">{!header.buyer_code}</td>
+                <td style="text-align: right;">浜岀被缁忚惀澶囨鍑瘉锛�</td>
+                <td style="text-align: left;">娌緪椋熻嵂鐩戞缁忚惀澶�20160318鍙�</td>
+            </tr>
+        </apex:outputPanel>
+        <apex:outputPanel rendered="{!IF(productSegment == 'BS' , false, true)}" layout="none">
+            <tr>
+                <td style="text-align: right;">鍦板潃锛�</td>
+                <td style="text-align: left;">{!header.buyer_address}</td>
+                <td style="text-align: right;">鍦板潃锛�</td>
+                <td style="text-align: left;">涓婃捣甯傚緪姹囧尯娣捣涓矾1010鍙�1001-1006銆�</td>
+            </tr>
+            <tr>
+                <td style="text-align: right;">&nbsp;</td>
+                <td style="text-align: left;">&nbsp;</td>
+                <td style="text-align: right;">&nbsp;</td>
+                <td style="text-align: left;">1101銆�1102銆�1104-1106銆�1601瀹�</td>
+            </tr>
+        </apex:outputPanel>
+        <tr>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.buyer_city}</td>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.seller_city}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;">{!header.buyer_province}</td>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;">{!header.seller_province}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐢佃瘽锛�</td>
+            <td style="text-align: left;">{!header.buyer_phone}</td>
+            <td style="text-align: right;">鐢佃瘽锛�</td>
+            <td style="text-align: left;">{!header.seller_phone}</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="35%"/>
+            <col width="10%"/>
+            <col width="40%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: right;">鈶犺鍗曠紪鍙凤細</td>
+            <td style="text-align: left;">{!header.pdf_order_no}</td>
+            <td style="text-align: right;">瑕佹眰浜ゆ湡锛�</td>
+            <td style="text-align: left;">{!header.order_require_date}</td>
+        </tr>
+        <tr>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+            <td style="text-align: right;">鈶AP鎶ュ鍗曞彿锛�</td>
+            <td style="text-align: left;">{!header.order_sap_no}</td>
+            </apex:outputPanel>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', false, true)}">
+            <td style="text-align: right;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            </apex:outputPanel>
+            <td style="text-align: right;">CRM鎶ュ鍙凤細</td>
+            <td style="text-align: left;">{!header.order_crm_no}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: right;">涓棿鍟嗭細</td>
+            <td style="text-align: left;">{!header.order_subdealer}</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="25%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: center;">鈶㈡敹璐т俊鎭�</td>
+            <td style="text-align: left;" colspan="5">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鏀惰揣鍏徃锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.delivery_name}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">绉戝锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.delivery_department}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鑱旂郴鍦板潃锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.delivery_address}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.delivery_city}</td>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.delivery_province}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鏀惰揣浜哄鍚嶏細</td>
+            <td style="text-align: left;">{!header.delivery_user}</td>
+            <td style="text-align: right;">鍥鸿瘽锛�</td>
+            <td style="text-align: left;">{!header.delivery_phone}</td>
+            <td style="text-align: right;">鎵嬫満锛�</td>
+            <td style="text-align: left;">{!header.delivery_tel}</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="25%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: center;">鈶g敤鎴蜂俊鎭�</td>
+            <td style="text-align: left;" colspan="5">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐢ㄦ埛鍚嶇О锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.user_name}</td>
+            <td style="text-align: right;">CRM瀹㈡埛缂栧彿锛�</td>
+            <td style="text-align: left;">{!header.user_no}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">绉戝锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.user_department}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鑱旂郴鍦板潃锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.user_address}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.user_city}</td>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.user_province}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐢ㄦ埛濮撳悕锛�</td>
+            <td style="text-align: left;">{!header.user_name2}</td>
+            <td style="text-align: right;">鍥鸿瘽锛�</td>
+            <td style="text-align: left;">{!header.user_phone}</td>
+            <td style="text-align: right;">鎵嬫満锛�</td>
+            <td style="text-align: left;">{!header.user_tel}</td>
+        </tr>
+        <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'IE', true, false)}">
+        <tr>
+            <td style="text-align: right;">鐢ㄦ埛灞炴��(IE鐢�)锛�</td>
+            <td style="text-align: left;">{!header.user_property_IE}</td>
+            <td style="text-align: right;">鐢ㄦ埛浜у搧(IE鐢�)锛�</td>
+            <td style="text-align: left;">{!header.user_product_IE}</td>
+        </tr>
+        </apex:outputPanel>
+        <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'RVI', true, false)}">
+        <tr>
+            <td style="text-align: right;">甯傚満(RVI鐢�)锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.user_market_RVI}</td>
+        </tr>
+        </apex:outputPanel>
+    </table>
+
+<apex:variable var="count" value="{!0}"/>
+
+<apex:repeat value="{!pageDetails}" var="details">
+
+    <apex:variable var="count" value="{!count + 1}"/>
+    <apex:outputPanel rendered="{!notSpecialDealer}">
+    <table style="border-collapse:collapse;" border="1" width="100%">
+       
+            <colgroup>
+                <col width="{!IF(is_parts_direct, IF(productSegment == 'BS', '10%', '15%'), IF(productSegment == 'BS', '3%', '10%'))}"/>
+                <col width="{!IF(is_parts_direct, IF(productSegment == 'BS', '15%', '20%'),  IF(productSegment == 'BS', '8%', '15%'))}"/>
+                <col width="{!IF(is_parts_direct, IF(productSegment == 'BS', '15%', '20%'),  IF(productSegment == 'BS', '12%', '15%'))}"/>
+                <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+                    <col width= "12%" />
+                    <col width= "15%" />  
+                    <col width= "17%" />        
+                </apex:outputPanel>
+                <col width="{!IF(is_parts_direct, IF(productSegment == 'BS', '10%', '15%'), IF(productSegment == 'BS', '3%', '10%'))}"/>
+                
+                <apex:outputPanel layout="none" rendered="{!!is_parts_direct}">
+                    <col width="{!IF(productSegment == 'BS', '8%', '25%')}"/>
+                    <col width="{!IF(productSegment == 'BS', '8%', '25%')}"/>
+                </apex:outputPanel>
+                <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+                    <col width="13%"/>
+                </apex:outputPanel>
+            </colgroup>
+            <tr>
+                <td style="text-align: center;" colspan="{!IF(is_parts_direct, '4', '9')}">鈶よ璐ф槑缁�</td>
+                <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+                <td style="text-align: center;">BS濉啓</td>
+                </apex:outputPanel>
+            </tr>
+            <tr>
+            <td style="text-align: center;">NO.</td>
+            <td style="text-align: center;">OT CODE</td>
+            <td style="text-align: center;">EC CODE</td>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+                <td style="text-align: center;">娉ㄥ唽鍨嬪彿</td>
+                <td style="text-align: center;">浜у搧鍚嶇О</td>
+                <td style="text-align: center;">娉ㄥ唽璇佸彿</td>
+            </apex:outputPanel>
+            <td style="text-align: center;">鏁伴噺</td>
+            <apex:outputPanel layout="none" rendered="{!!is_parts_direct}">
+            <td style="text-align: center;">鍗曚环(RMB)</td>
+            <td style="text-align: center;">鎬讳环(RMB)</td>
+            </apex:outputPanel>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+            <td style="text-align: center;">鐢熶骇鍘傚</td>
+            </apex:outputPanel>
+        </tr>
+        <apex:repeat value="{!details}" var="detail">
+        <tr>
+            <td style="text-align: center;"><apex:outputText value="{!detail.lineno}" /></td>
+            <td style="text-align: left;"><apex:outputText value="{!detail.otcode}" /></td>
+            <td style="text-align: left;"><!-- <apex:outputText value="{!detail.eccode}" /> --> <c:PDFWbr targetStr="{!detail.eccode}"/></td>
+            
+            <apex:outputPanel rendered="{!IF(productSegment == 'BS', true, false)}" layout="none">
+                <td style="text-align: left;"><apex:outputText value="{!detail.ccode}" /></td>
+                <td style="text-align: left;"><!-- <apex:outputText value="{!detail.name}" /> --> <c:PDFWbr targetStr="{!detail.name}"/></td>
+                <td style="text-align: left;"><!-- <apex:outputText value="{!detail.ccode}" /> --><c:PDFWbr targetStr="{!detail.registrationCode}"/></td>
+            </apex:outputPanel>
+            
+            <td style="text-align: right;"><apex:outputText value="{!detail.quantity}" /></td>
+            <apex:outputPanel layout="none" rendered="{!!is_parts_direct}">
+            <td style="text-align: right;"><apex:outputText value="{!detail.price}" /></td>
+            <td style="text-align: right;"><apex:outputText value="{!detail.totalprice}" /></td>
+            </apex:outputPanel>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+            <td style="text-align: left;"><!-- <apex:outputText value="{!detail.factory}" /> --><c:PDFWbr targetStr="{!detail.factory}"/></td>
+            </apex:outputPanel>
+        </tr>
+        </apex:repeat>
+        </table>
+        </apex:outputPanel>
+
+
+
+        <apex:outputPanel rendered="{!!notSpecialDealer}">
+        <table style="border-collapse:collapse;" border="1" width="100%">
+            <colgroup>
+                <col width="5%"/>
+                <col width="15%"/>
+                <col width="15%"/>
+                <col width="15%"/>
+                <col width="15%"/>
+                <col width="16%"/>
+                <col width="4%"/>
+                <col width="15%"/>
+            </colgroup>
+            <tr>
+                <td style="text-align: center;" colspan="7">鈶よ璐ф槑缁�</td>
+                <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+                    <td style="text-align: center;">BS濉啓</td>
+                </apex:outputPanel>
+        </tr>
+         <tr>
+            <td style="text-align: center;">NO.</td>
+            <td style="text-align: center;">OT CODE</td>
+            <td style="text-align: center;">EC CODE</td>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+                <td style="text-align: center;">娉ㄥ唽鍨嬪彿</td>
+                <td style="text-align: center;">浜у搧鍚嶇О</td>
+                <td style="text-align: center;">娉ㄥ唽璇佸彿</td>
+            </apex:outputPanel>
+            <td style="text-align: center;">鏁伴噺</td>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+            <td style="text-align: center;">鐢熶骇鍘傚</td>
+            </apex:outputPanel>
+        </tr>
+        <apex:repeat value="{!details}" var="detail">
+        <tr>
+            <td style="text-align: center;"><apex:outputText value="{!detail.lineno}" /></td>
+            <td style="text-align: left;"><apex:outputText value="{!detail.otcode}" /></td>
+            <td style="text-align: left;"><!-- <apex:outputText value="{!detail.eccode}" /> --> <c:PDFWbr targetStr="{!detail.eccode}"/></td>
+            
+            <apex:outputPanel rendered="{!IF(productSegment == 'BS', true, false)}" layout="none">
+                <td style="text-align: left;"><apex:outputText value="{!detail.ccode}" /></td>
+                <td style="text-align: left;"><!-- <apex:outputText value="{!detail.name}" /> --> <c:PDFWbr targetStr="{!detail.name}"/></td>
+                <td style="text-align: left;"><!-- <apex:outputText value="{!detail.ccode}" /> --><c:PDFWbr targetStr="{!detail.registrationCode}"/></td>
+            </apex:outputPanel>
+            
+            <td style="text-align: right;"><apex:outputText value="{!detail.quantity}" /></td>
+            <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'BS', true, false)}">
+            <td style="text-align: left;"><!-- <apex:outputText value="{!detail.factory}" /> --><c:PDFWbr targetStr="{!detail.factory}"/></td>
+            </apex:outputPanel>
+        </tr>
+        </apex:repeat>
+
+           </table>
+        </apex:outputPanel>
+        
+       
+ 
+
+    <apex:outputpanel rendered="{!count < pageCnt}">
+        <div style="page-break-after: always;"/>
+    </apex:outputpanel> 
+
+</apex:repeat>
+     <apex:outputPanel rendered="{!notSpecialDealer}">
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="70%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+        </colgroup>
+    <apex:outputPanel layout="none" rendered="{!if((!is_parts_direct && is_ie_direct),true,false)}">
+        <tr>
+            <td style="text-align: right;">鍚堣锛�</td>
+            <td style="text-align: right;">{!header.order_subtotal}</td>
+            <td style="text-align: center;">&nbsp;</td>
+
+        </tr>
+        <tr>
+            <td style="text-align: right;">鎶樻墸鐜囷細</td>
+            <td style="text-align: right;">{!header.order_discount_rate}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鎶樻墸鍊硷細</td>
+            <td style="text-align: right;">{!header.order_discount_value}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">OCSM鎶樻墸鍚庡悎璁� (OCSM->鐢ㄦ埛)锛�</td>
+            <td style="text-align: right;">{!header.order_totalprice}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+<!--         <apex:outputPanel layout="none" rendered="{!header.order_print_dealer}">
+        <tr>
+            <td style="text-align: right;">鍏朵粬浜у搧閿�鍞噾棰� and/or 浠g悊鍟�(涓棿鍟�)鍒╂鼎锛�</td>
+            <td style="text-align: right;">{!header.order_dealer_profit}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        </apex:outputPanel> -->
+    </apex:outputPanel>
+    <apex:outputPanel layout="none" rendered="{!if((!is_parts_direct && !is_ie_direct),true,false)}">
+        <tr>
+            <td style="text-align: right;">鍚堣锛�</td>
+            <td style="text-align: right;">{!header.order_subtotal}</td>
+            <td style="text-align: center;">&nbsp;</td>
+
+        </tr>
+        <tr>
+            <td style="text-align: right;">鎶樻墸鐜囷細</td>
+            <td style="text-align: right;">{!header.order_discount_rate}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鎶樻墸鍊硷細</td>
+            <td style="text-align: right;">{!header.order_discount_value}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">OCSM鎶樻墸鍚庡悎璁� (OCSM->浠g悊鍟�)锛�</td>
+            <td style="text-align: right;">{!header.order_totalprice}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+    </apex:outputPanel>
+<!--         <apex:outputPanel layout="none" rendered="{!header.order_print_dealer}">
+        <tr>
+            <td style="text-align: right;">浠g悊鍟嗛攢鍞�婚噾棰�(浠g悊鍟�->鐢ㄦ埛/涓棿鍟�)锛�</td>
+            <td style="text-align: right;">{!header.order_dealer_price}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        </apex:outputPanel> -->
+    </table>
+    </apex:outputPanel>
+
+    <apex:outputPanel rendered="{!!notSpecialDealer}">
+        <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="70%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+        </colgroup>
+         <tr>
+            <td style="text-align: right;">鍚堝悓鎬婚噾棰濓細</td>
+            <td style="text-align: right;">{!header.order_totalprice}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        </table>
+    </apex:outputPanel>
+
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="10%"/>
+            <col width="90%"/>
+        </colgroup>
+        <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'IE' || productSegment == 'RVI', true, false)}">
+        <tr>
+            <td style="text-align: left;">IE/RVI濉啓</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">INQUIRY NO.锛�</td>
+            <td style="text-align: left;">{!header.order_inquiry_no}</td>
+        </tr>
+        <tr style="border-bottom: thin solid black;">
+            <td style="text-align: left;">鎶ュ鍗曞彿锛�</td>
+            <td style="text-align: left;">{!header.order_no}</td>
+        </tr>
+        </apex:outputPanel>
+        <apex:outputPanel rendered="{!IF(productSegment == 'BS', false, true)}" layout="none">
+            <tr>
+                <td style="text-align: left;vertical-align: top;" height="40px">澶囨敞锛�</td>
+                <td style="text-align: left;"><apex:outputText value="{!header.order_comment}" escape="false"/></td>
+            </tr>
+        </apex:outputPanel>
+        <apex:outputPanel rendered="{!IF(productSegment == 'BS', true, false)}" layout="none">
+            <tr>
+                <td style="text-align: left;vertical-align: top;">澶囨敞锛�</td>
+                <td style="text-align: left;"> 1銆佺敱浜庢樉寰暅浜у搧鐨勭壒娈婃�э紝鑻ュ皢鎴戝徃浜у搧浣滀负鍖荤枟鍣ㄦ鐢熺墿鏄惧井闀滈攢鍞嚦涓村簥甯傚満鏃讹紝闇�鏄庣‘鍚戠敤鎴峰憡鐭ュ苟鍖哄垎鑾疯瘉鍖荤枟鍣ㄦ涓�</td>
+            </tr>
+            <tr>
+                <td style="text-align: left;vertical-align: top;">&nbsp;</td>
+                <td style="text-align: left;">闈炲尰鐤楀櫒姊颁骇鍝併��</td>
+            </tr>
+             <tr>
+                <td style="text-align: left;vertical-align: top;" height="40px">&nbsp;</td>
+                <td style="text-align: left;"><apex:outputText value="{!header.order_comment}" escape="false"/></td>
+            </tr>
+        </apex:outputPanel>
+    </table>
+    <table border="0" width="100%">
+        <colgroup>
+            <col width="60%"/>
+            <col width="30%"/>
+            <col width="10%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: left;">鍗曚綅鍚嶇О锛氬ゥ鏋楀反鏂紙鍖椾含锛夐攢鍞湇鍔℃湁闄愬叕鍙镐笂娴峰垎鍏徃</td>
+            <td style="text-align: right;">鏃ユ湡:</td>
+            <td style="text-align: left;">{!strToday}</td>
+            <td style="text-align: left;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">寮� 鎴� 琛岋細鎷涘晢閾惰涓婃捣鍒嗚娣捣鏀</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">閾惰璐﹀彿锛�121913911110902003锛堜粎闄愮綉閾跺鎴锋搷浣滀娇鐢級</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;121913911110902  </td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">锛堜粎闄愮焊璐ㄧエ鎹鎴锋搷浣滀娇鐢紝绾歌川绁ㄦ嵁鍖呮嫭鏀エ銆佽捶璁板嚟璇併��</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: center; border-top: thin solid black;">涔版柟鐩栫珷</td>
+            <td style="text-align: left;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">缁撶畻涓氬姟濮旀墭涔︺�侀摱琛屾眹绁ㄣ�佸晢涓氭眹绁ㄣ�侀摱琛屾壙鍏戞眹绁ㄣ�佸晢涓氭壙鍏戞眹绁ㄧ瓑锛�</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+        </tr>
+    </table>
+</body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderPdf2.page-meta.xml b/scr/pages/OrderPdf2.page-meta.xml
new file mode 100644
index 0000000..e19f2aa
--- /dev/null
+++ b/scr/pages/OrderPdf2.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderPdf2</label>
+</ApexPage>
diff --git a/scr/pages/OrderPdf3.page b/scr/pages/OrderPdf3.page
new file mode 100644
index 0000000..f6bff27
--- /dev/null
+++ b/scr/pages/OrderPdf3.page
@@ -0,0 +1,326 @@
+<apex:page Controller="OrderPdf2Controller" showHeader="false" sidebar="false" id="allPage" action="{!init}" renderAs="pdf"><!-- renderAs="pdf" -->
+
+<head>
+    <style>
+        @page {
+            size: A4 landscape;
+            margin: 12mm 12mm 5mm 12mm;
+
+            @bottom-center {
+                content: counter(page) " / " counter(pages);
+            }
+        }
+
+        table { border-collapse: collapse; }
+
+        td.border-thick-title { border-width: 1pt 0pt 1pt 0pt; border-style: solid; border-color: black; text-align: center;}
+        td.border-thick-bottom { border-width: 0pt 0pt 1pt 0pt; border-style: solid; border-color: black; text-align: center;}
+        td.detail { text-align: center; }
+    </style>
+</head>
+
+
+<body style="font-family: Arial Unicode MS; page-break-inside: auto; font-size: 8pt;">
+    
+    <table border="0" width="100%">
+        <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'NDT', true, false)}">
+            <tr>
+                <td style="text-align: center; font-size: 16pt;">SSBG-NDT鍐呰锤璁㈣揣鍗�</td>
+            </tr>
+        </apex:outputPanel>
+        <apex:outputPanel layout="none" rendered="{!IF(productSegment == 'NDT', false, true)}">
+            <tr>
+                <td style="text-align: center; font-size: 16pt;">SSBG-ANI鍐呰锤璁㈣揣鍗�</td>
+            </tr>
+        </apex:outputPanel>
+    </table>
+
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="35%"/>
+            <col width="10%"/>
+            <col width="40%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: right;">涔版柟锛�</td>
+            <td style="text-align: left;">{!header.buyer_name}</td>
+            <td style="text-align: right;">鍗栨柟锛�</td>
+            <td style="text-align: left;">{!header.seller_name}</td>
+        </tr>
+
+        <tr>
+            <td style="text-align: right;">鍦板潃锛�</td>
+            <td style="text-align: left;">{!header.buyer_address}</td>
+            <td style="text-align: right;">鍦板潃锛�</td>
+            <td style="text-align: left;">涓婃捣甯傚緪姹囧尯娣捣涓矾1010鍙�1001-1006銆�</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">&nbsp;</td>
+            <td style="text-align: left;">&nbsp;</td>
+            <td style="text-align: right;">&nbsp;</td>
+            <td style="text-align: left;">1101銆�1102銆�1104-1106銆�1601瀹�</td>
+        </tr>
+        
+        <tr>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.buyer_city}</td>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.seller_city}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;">{!header.buyer_province}</td>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;">{!header.seller_province}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐢佃瘽锛�</td>
+            <td style="text-align: left;">{!header.buyer_phone}</td>
+            <td style="text-align: right;">鐢佃瘽锛�</td>
+            <td style="text-align: left;">{!header.seller_phone}</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="35%"/>
+            <col width="10%"/>
+            <col width="40%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: right;">鈶犺鍗曠紪鍙凤細</td>
+            <td style="text-align: left;">{!header.pdf_order_no}</td>
+            <!-- <td style="text-align: right;">瑕佹眰浜ゆ湡锛�</td>
+            <td style="text-align: left;">{!header.order_require_date}</td> -->
+        </tr>
+        <tr>
+            <td style="text-align: right;">CRM鎶ュ鍙凤細</td>
+            <td style="text-align: left;">{!header.order_crm_no}</td>
+            <td style="text-align: right;">涓棿鍟嗭細</td>
+            <td style="text-align: left;">{!header.order_subdealer}</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="25%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: center;">鈶㈡敹璐т俊鎭�</td>
+            <td style="text-align: left;" colspan="5">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鏀惰揣鍏徃锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.delivery_name}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">绉戝锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.delivery_department}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鑱旂郴鍦板潃锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.delivery_address}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.delivery_city}</td>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.delivery_province}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鏀惰揣浜哄鍚嶏細</td>
+            <td style="text-align: left;">{!header.delivery_user}</td>
+            <td style="text-align: right;">鍥鸿瘽锛�</td>
+            <td style="text-align: left;">{!header.delivery_phone}</td>
+            <td style="text-align: right;">鎵嬫満锛�</td>
+            <td style="text-align: left;">{!header.delivery_tel}</td>
+        </tr>
+    </table>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="15%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+            <col width="25%"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: center;">鈶g敤鎴蜂俊鎭�</td>
+            <td style="text-align: left;" colspan="5">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐢ㄦ埛鍚嶇О锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.user_name}</td>
+            <td style="text-align: right;">CRM瀹㈡埛缂栧彿锛�</td>
+            <td style="text-align: left;">{!header.user_no}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">绉戝锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.user_department}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鑱旂郴鍦板潃锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.user_address}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鍩庡競锛�</td>
+            <td style="text-align: left;">{!header.user_city}</td>
+            <td style="text-align: right;">鐪佷唤锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.user_province}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鐢ㄦ埛濮撳悕锛�</td>
+            <td style="text-align: left;">{!header.user_name2}</td>
+            <td style="text-align: right;">鍥鸿瘽锛�</td>
+            <td style="text-align: left;">{!header.user_phone}</td>
+            <td style="text-align: right;">鎵嬫満锛�</td>
+            <td style="text-align: left;">{!header.user_tel}</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">Sub Use锛�</td>
+            <td style="text-align: left;" colspan="5">{!header.user_product_IE}</td>
+        </tr>
+    </table>
+
+    <apex:variable var="count" value="{!0}"/>
+
+    <apex:repeat value="{!pageDetails}" var="details">
+
+        <apex:variable var="count" value="{!count + 1}"/>
+
+        <table style="border-collapse:collapse;" border="1" width="100%">
+            <colgroup>
+                <col width= "5%" />
+                <col width= "12%" />  
+                <col width= "27%" /> 
+                <col width= "20%" />
+                <col width= "8%" />  
+                <col width= "13%" /> 
+                <col width= "15%" />
+            </colgroup>
+            <tr>
+                <td style="text-align: center;" colspan="9">鈶よ璐ф槑缁�</td>
+            </tr>
+            <tr>
+                <td style="text-align: center;">NO.</td>
+                <td style="text-align: center;">U8</td>
+                <td style="text-align: center;">UPC CODE</td>
+                <td style="text-align: center;">浜у搧鎻忚堪</td>
+                <td style="text-align: center;">鏁伴噺</td>
+                <td style="text-align: center;">鍗曚环(RMB锛�</td>
+                <td style="text-align: center;">鎬讳环(RMB)</td>
+                
+            </tr>
+            <apex:repeat value="{!details}" var="detail">
+            <tr>
+                <td style="text-align: center;"><apex:outputText value="{!detail.lineno}" /></td>
+                <td style="text-align: left;"><apex:outputText value="{!detail.otcode}" /></td>
+                <td style="text-align: left;"><c:PDFWbr targetStr="{!detail.eccode}"/></td>
+                <td style="text-align: left;"> <c:PDFWbr targetStr="{!detail.name}"/></td>
+                <td style="text-align: center;"><apex:outputText value="{!detail.quantity}" /></td>
+                <td style="text-align: right;"><apex:outputText value="{!detail.price}" /></td>
+                <td style="text-align: right;"><apex:outputText value="{!detail.price_d}" /></td>
+
+            </tr>
+            </apex:repeat>
+        </table>
+
+        <apex:outputpanel rendered="{!count < pageCnt}">
+            <div style="page-break-after: always;"/>
+        </apex:outputpanel> 
+
+    </apex:repeat>
+    <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="70%"/>
+            <col width="20%"/>
+            <col width="10%"/>
+        </colgroup>
+
+        <tr>
+            <td style="text-align: right;">鍚堣锛�</td>
+            <td style="text-align: right;">{!header.order_subtotal}</td>
+            <td style="text-align: center;">&nbsp;</td>
+
+        </tr>
+        <tr>
+            <td style="text-align: right;">鎶樻墸鐜囷細</td>
+            <td style="text-align: right;">{!header.order_discount_rate}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">鎶樻墸鍊硷細</td>
+            <td style="text-align: right;">{!header.order_discount_value}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: right;">OCN鎶樻墸鍚庡悎璁� (OCN->浠g悊鍟�)锛�</td>
+            <td style="text-align: right;">{!header.order_totalprice}</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+    </table>
+
+     <table style="border:solid 1px black" width="100%">
+        <colgroup>
+            <col width="12%"/>
+            <col width="48%"/>
+            <col width="10"/>
+            <col width="30"/>
+        </colgroup>
+        <tr>
+            <td style="text-align: left;">IE/RVI濉啓</td>
+            <td style="text-align: center;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align: left;">INQUIRY NO.锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.order_inquiry_no}</td>
+        </tr>
+        <tr style="border-bottom: thin solid black;">
+            <td style="text-align: left;">鎶ュ鍗曞彿锛�</td>
+            <td style="text-align: left;" colspan="3">{!header.order_no}</td>
+        </tr>
+        <tr style="border-bottom: thin solid black;">
+            <td style="text-align: left;">澶囨敞锛�</td>
+            <td style="text-align: left;" ><c:PDFWbr targetStr="{!order.Description}"/><!-- <apex:outputText id="Description" value="{!order.Description}"></apex:outputText> --></td>
+        </tr>
+        <tr><td style="text-align-last: left;" colspan="4">&nbsp;</td></tr>
+        <tr><td style="text-align-last: left;" colspan="4">&nbsp;</td></tr>
+        
+        <tr>
+            <td style="text-align: left;" colspan="3">&nbsp;</td>
+            <td style="text-align: center; border-top: thin solid black;">涔版柟鐩栫珷</td>
+            
+            
+        </tr>
+    </table>
+     <table border="0" width="100%">
+        
+        <tr>
+            <td style="text-align: left;">鍏徃鍚嶇О锛氬ゥ鏋楀反鏂�(鍖椾含)閿�鍞湇鍔℃湁闄愬叕鍙�</td>
+            
+        </tr>
+        <tr>
+            <td style="text-align: left;">鏁存満璐︽埛锛圢DT/ANI 鍐呰锤涓氬姟锛�</td>
+            
+        </tr>
+        <tr>
+            <td style="text-align: left;">閾惰璐﹀彿锛�610809142 </td>
+            
+        </tr>
+        <tr>
+            <td style="text-align: left;">寮�鎴疯锛氫腑鍥芥皯鐢熼摱琛屽寳浜笁鍏冩敮琛� </td>
+            
+        </tr>
+    </table>
+
+</body>
+
+
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderPdf3.page-meta.xml b/scr/pages/OrderPdf3.page-meta.xml
new file mode 100644
index 0000000..11b5bb3
--- /dev/null
+++ b/scr/pages/OrderPdf3.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderPdf3</label>
+</ApexPage>
diff --git a/scr/pages/OrderShippingNotification.page b/scr/pages/OrderShippingNotification.page
new file mode 100644
index 0000000..1022d31
--- /dev/null
+++ b/scr/pages/OrderShippingNotification.page
@@ -0,0 +1,57 @@
+<apex:page standardController="Order" extensions="OrderShippingNotificationController" showHeader="false" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('hasError')).val();
+    if (hasError == 'false') {
+        //top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allForm,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+            <apex:pageBlock title="{!$ObjectType.Order.fields.ShippingNotes__c.label}" id="allBlock">
+                <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="鍙戦��" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+                </apex:pageBlockButtons>
+
+                <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <input type="hidden" id="hasError" value="{!hasError}" />
+
+                <table>
+                    <tr>
+                        <td>To锛�</td>
+                        <td>
+                            <apex:inputField value="{!ra.ShippingRecieverEmailAdr__c}"/>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
+                        <td>
+                            <apex:inputField value="{!ra.ShippingNotes__c}" style="resize:none; width:500px; height:150px;"/>
+                        </td>
+                    </tr>
+                </table>
+
+            </apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderShippingNotification.page-meta.xml b/scr/pages/OrderShippingNotification.page-meta.xml
new file mode 100644
index 0000000..107e945
--- /dev/null
+++ b/scr/pages/OrderShippingNotification.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>38.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderShippingNotification</label>
+</ApexPage>
diff --git a/scr/pages/OrderSplitRatio.page b/scr/pages/OrderSplitRatio.page
new file mode 100644
index 0000000..9b0fb87
--- /dev/null
+++ b/scr/pages/OrderSplitRatio.page
@@ -0,0 +1,44 @@
+<apex:page standardController="Order" extensions="OrderSplitRatioController" sidebar="false" id="allPage" action="{!init}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script type="text/javascript">
+	var UsId = '{!UsId}';
+	var AppSta = '{!AppSta}';
+	var BsAgm = '{!BsAgm}';
+	var new_profileId = '{!new_profileId}';
+	function leavemessage() {
+    //blockme();
+    window.open('/apex/OrderSplitRatioPopUp?raid=' + '{!URLENCODE(Order.Id)}',
+                'OrderNotes',
+                'height=180,width=400,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
+	}
+	function reloadjs() {
+    //blockme();
+    init();
+	}
+</script>
+<apex:form id="allForm">
+	<apex:actionFunction name="init" action="{!init}" reRender="allPanel,message"></apex:actionFunction>
+	<apex:outputPanel id="allPanel">
+	<table style="width: 90%">
+		<tr>
+			<th style="width: 17.3%;text-align: right;"><apex:outputLabel value="鎷嗗垎姣斾緥" for="hehe"></apex:outputLabel></th>
+			<td style="width: 1.8%;"></td>
+
+			<apex:outputPanel layout="none" rendered="{!IF((BsAgm == UsId && AppSta == '1') || new_profileId == '00e28000000eN67' || new_profileId == '00e28000000wAuN', true, false)}">
+			<td onclick="leavemessage();" style="border: 1px; border-style: solid; float: left;width: 56%"><apex:inputField value="{!ord.SplitRatioFormule__c}" id="hehe"></apex:inputField>&nbsp;</td>
+			</apex:outputPanel>
+
+			<apex:outputPanel layout="none" rendered="{!IF(((BsAgm == UsId && AppSta != '1') || BsAgm != UsId) && new_profileId != '00e28000000eN67' && new_profileId != '00e28000000wAuN', true, false)}">
+			<td><apex:inputField value="{!ord.SplitRatioFormule__c}" style="width: 50%;"></apex:inputField></td>
+			</apex:outputPanel>
+		</tr>
+		
+		
+		
+	</table>
+	</apex:outputPanel>
+</apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderSplitRatio.page-meta.xml b/scr/pages/OrderSplitRatio.page-meta.xml
new file mode 100644
index 0000000..05a62d7
--- /dev/null
+++ b/scr/pages/OrderSplitRatio.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderSplitRatio</label>
+</ApexPage>
diff --git a/scr/pages/OrderSplitRatioPopUp.page b/scr/pages/OrderSplitRatioPopUp.page
new file mode 100644
index 0000000..3f8ce28
--- /dev/null
+++ b/scr/pages/OrderSplitRatioPopUp.page
@@ -0,0 +1,44 @@
+<apex:page Controller="OrderSplitRatioController" showHeader="false" sidebar="false" id="allPage" action="{!init1}">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<script>
+function savejs() {
+    savebtn();
+}
+
+function canceljs() {
+    top.window.close();
+}
+
+function refreshparent() {
+    var hasError = j$(escapeVfId('allPage:allForm:allBlock:hasError')).text();
+    if (hasError == 'false') {
+        top.window.opener.reloadjs();
+        top.window.close();
+    }
+}
+</script>
+    <apex:form id="allForm">
+        <apex:actionFunction name="savebtn" action="{!saveBtn}" rerender="allPanel,message" onComplete="refreshparent();">
+        </apex:actionFunction>
+        <apex:outputPanel id="allPanel">
+        	<apex:pageBlock title="鎷嗗垎姣斾緥" id="allBlock">
+		        <apex:pageBlockButtons location="top">
+                    <apex:commandButton onclick="savejs(); return false;" value="淇濆瓨" rerender="dummy"/>
+                    <apex:commandButton onclick="canceljs(); return false;" value="鍙栨秷" rerender="dummy"/>
+		        </apex:pageBlockButtons>
+
+		        <apex:outputPanel id="message">
+                    <apex:pageMessages />
+                </apex:outputPanel>
+
+                <apex:outputText id="raid" value="{!raid}" style="display:none"/>
+                <apex:outputText id="hasError" value="{!hasError}" style="display:none"/>
+
+		        <apex:outputLabel value="鎷嗗垎姣斾緥锛�"></apex:outputLabel>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+				<apex:inputField onclick="leavemessage();" value="{!ra1.SplitRatio__c}"></apex:inputField>
+			</apex:pageBlock>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/OrderSplitRatioPopUp.page-meta.xml b/scr/pages/OrderSplitRatioPopUp.page-meta.xml
new file mode 100644
index 0000000..8c648c7
--- /dev/null
+++ b/scr/pages/OrderSplitRatioPopUp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>OrderSplitRatioPopUp</label>
+</ApexPage>
diff --git a/scr/pages/PersonalProcessInstance.page b/scr/pages/PersonalProcessInstance.page
new file mode 100644
index 0000000..a73c104
--- /dev/null
+++ b/scr/pages/PersonalProcessInstance.page
@@ -0,0 +1,158 @@
+<apex:page controller="PersonalProcessInstanceController" showHeader="false" sidebar="false" action="{!init}" id="allPage">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+
+    <apex:form id="allForm">
+        <apex:pageBlock id="accountBlock" title="瀹㈡埛瀹℃壒">
+            <table style="border-style:none;" border="0" width="750px">
+                <colgroup>
+                    <col width="20%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: left;">鎿嶄綔</th>
+                    <th style="text-align: left;">鐩稿叧椤�</th>
+                    <th style="text-align: left;">鎻愪氦浜哄鍚�</th>
+                    <th style="text-align: left;">鎻愪氦鏃ユ湡</th>
+                    <th style="text-align: left;">缁忚繃澶╂暟</th>
+                    <th style="text-align: left;">鍘熷鎵逛汉</th>
+                </tr>
+                <apex:repeat value="{!accPIList}" var="pi">
+                <tr>
+                    <td style="text-align: left;"><a href="/{!URLENCODE(pi.piw.id)}/e?et=REASSIGN&retURL=%2Fhome%2Fhome.jsp">閲嶆柊鍒嗛厤</a> | <a href="/p/process/ProcessInstanceWorkitemWizardStageManager?id={!URLENCODE(pi.piw.id)}">鎵瑰噯/鎷掔粷</a></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.TargetObjectId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.SubmittedbyId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.CreatedDate}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputText value="{!pi.elapsedTimeInDays}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.OriginalActorId}" style="width: 95%"/></td>
+                </tr>
+            </apex:repeat>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="contactBlock" title="鑱旂郴浜哄鎵�">
+            <table style="border-style:none;" border="0" width="750px">
+                <colgroup>
+                    <col width="20%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: left;">鎿嶄綔</th>
+                    <th style="text-align: left;">鐩稿叧椤�</th>
+                    <th style="text-align: left;">鎻愪氦浜哄鍚�</th>
+                    <th style="text-align: left;">鎻愪氦鏃ユ湡</th>
+                    <th style="text-align: left;">缁忚繃澶╂暟</th>
+                    <th style="text-align: left;">鍘熷鎵逛汉</th>
+                </tr>
+                <apex:repeat value="{!conPIList}" var="pi">
+                <tr>
+                    <td style="text-align: left;"><a href="/{!URLENCODE(pi.piw.id)}/e?et=REASSIGN&retURL=%2Fhome%2Fhome.jsp">閲嶆柊鍒嗛厤</a> | <a href="/p/process/ProcessInstanceWorkitemWizardStageManager?id={!URLENCODE(pi.piw.id)}">鎵瑰噯/鎷掔粷</a></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.TargetObjectId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.SubmittedbyId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.CreatedDate}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputText value="{!pi.elapsedTimeInDays}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.OriginalActorId}" style="width: 95%"/></td>
+                </tr>
+            </apex:repeat>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="opportuntyBlock" title="璇环瀹℃壒">
+            <table style="border-style:none;" border="0" width="750px">
+                <colgroup>
+                    <col width="20%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: left;">鎿嶄綔</th>
+                    <th style="text-align: left;">鐩稿叧椤�</th>
+                    <th style="text-align: left;">鎻愪氦浜哄鍚�</th>
+                    <th style="text-align: left;">鎻愪氦鏃ユ湡</th>
+                    <th style="text-align: left;">缁忚繃澶╂暟</th>
+                    <th style="text-align: left;">鍘熷鎵逛汉</th>
+                </tr>
+                <apex:repeat value="{!oppPIList}" var="pi">
+                <tr>
+                    <td style="text-align: left;"><a href="/{!URLENCODE(pi.piw.id)}/e?et=REASSIGN&retURL=%2Fhome%2Fhome.jsp">閲嶆柊鍒嗛厤</a> | <a href="/p/process/ProcessInstanceWorkitemWizardStageManager?id={!URLENCODE(pi.piw.id)}">鎵瑰噯/鎷掔粷</a></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.TargetObjectId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.SubmittedbyId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.CreatedDate}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputText value="{!pi.elapsedTimeInDays}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.OriginalActorId}" style="width: 95%"/></td>
+                </tr>
+            </apex:repeat>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="orderBlock" title="鍚堝悓瀹℃壒">
+            <table style="border-style:none;" border="0" width="750px">
+                <colgroup>
+                    <col width="20%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: left;">鎿嶄綔</th>
+                    <th style="text-align: left;">鐩稿叧椤�</th>
+                    <th style="text-align: left;">鎻愪氦浜哄鍚�</th>
+                    <th style="text-align: left;">鎻愪氦鏃ユ湡</th>
+                    <th style="text-align: left;">缁忚繃澶╂暟</th>
+                    <th style="text-align: left;">鍘熷鎵逛汉</th>
+                </tr>
+                <apex:repeat value="{!odrPIList}" var="pi">
+                <tr>
+                    <td style="text-align: left;"><a href="/{!URLENCODE(pi.piw.id)}/e?et=REASSIGN&retURL=%2Fhome%2Fhome.jsp">閲嶆柊鍒嗛厤</a> | <a href="/p/process/ProcessInstanceWorkitemWizardStageManager?id={!URLENCODE(pi.piw.id)}">鎵瑰噯/鎷掔粷</a></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.TargetObjectId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.SubmittedbyId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.CreatedDate}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputText value="{!pi.elapsedTimeInDays}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.OriginalActorId}" style="width: 95%"/></td>
+                </tr>
+            </apex:repeat>
+            </table>
+        </apex:pageBlock>
+        <apex:pageBlock id="othersBlock" title="鍏朵粬瀹℃壒">
+            <table style="border-style:none;" border="0" width="750px">
+                <colgroup>
+                    <col width="20%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                    <col width="16%"/>
+                </colgroup>
+                <tr>
+                    <th style="text-align: left;">鎿嶄綔</th>
+                    <th style="text-align: left;">鐩稿叧椤�</th>
+                    <th style="text-align: left;">鎻愪氦浜哄鍚�</th>
+                    <th style="text-align: left;">鎻愪氦鏃ユ湡</th>
+                    <th style="text-align: left;">缁忚繃澶╂暟</th>
+                    <th style="text-align: left;">鍘熷鎵逛汉</th>
+                </tr>
+                <apex:repeat value="{!othPIList}" var="pi">
+                <tr>
+                    <td style="text-align: left;"><a href="/{!URLENCODE(pi.piw.id)}/e?et=REASSIGN&retURL=%2Fhome%2Fhome.jsp">閲嶆柊鍒嗛厤</a> | <a href="/p/process/ProcessInstanceWorkitemWizardStageManager?id={!URLENCODE(pi.piw.id)}">鎵瑰噯/鎷掔粷</a></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.TargetObjectId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.ProcessInstance.SubmittedbyId}" style="width: 95%"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.CreatedDate}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputText value="{!pi.elapsedTimeInDays}" style="width: 95%;"/></td>
+                    <td style="text-align: left;"><apex:outputField value="{!pi.piw.OriginalActorId}" style="width: 95%"/></td>
+                </tr>
+            </apex:repeat>
+            </table>
+        </apex:pageBlock>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/PersonalProcessInstance.page-meta.xml b/scr/pages/PersonalProcessInstance.page-meta.xml
new file mode 100644
index 0000000..a187e60
--- /dev/null
+++ b/scr/pages/PersonalProcessInstance.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>PersonalProcessInstance</label>
+</ApexPage>
diff --git a/scr/pages/QuoteCSVExport.page b/scr/pages/QuoteCSVExport.page
new file mode 100644
index 0000000..61c9c18
--- /dev/null
+++ b/scr/pages/QuoteCSVExport.page
@@ -0,0 +1,7 @@
+<apex:page standardController="Quote" extensions="NewQuoteEntryController" cache="true" contentType="text/csv;charset=utf-8;#{!fileName}.csv" language="zh-CN">"濂楄","浜у搧code","浜у搧鍚嶇О","鏁伴噺","OCSM鎶樻墸"
+    <apex:variable value="{!1}" var="line" />
+    <apex:repeat value="{!csv_activities}" var="item">
+"{!item.pageObject.Set__c}","{!item.pageObject.Product2.ProductCode}","{!item.pageObject.Product2.Name}","{!item.pageObject.Quantity}","{!item.pageObject.Discount}"
+    <apex:variable value="{!line + 1}" var="line" />
+    </apex:repeat>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/QuoteCSVExport.page-meta.xml b/scr/pages/QuoteCSVExport.page-meta.xml
new file mode 100644
index 0000000..7fb6654
--- /dev/null
+++ b/scr/pages/QuoteCSVExport.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>QuoteCSVExport</label>
+</ApexPage>
diff --git a/scr/pages/QuoteExcelImport.page b/scr/pages/QuoteExcelImport.page
new file mode 100644
index 0000000..aade75f
--- /dev/null
+++ b/scr/pages/QuoteExcelImport.page
@@ -0,0 +1,40 @@
+<apex:page standardController="Quote" showHeader="false" sidebar="false" pageStyle="Quote" >
+    <script type="text/javascript">
+        function closeMe() {
+            top.window.close();
+        }
+        function sendText(str) {
+            str = document.forms['{!$Component.mainForm}']['{!$Component.mainForm.page1.exceltext}'].value;
+            //top.window.opener.excelImport(str);
+            top.window.opener.excelImportGateway(str);
+            top.window.close();
+        }
+		function setCB() {
+			 //txt = document.forms['{!$Component.mainForm}']['{!$Component.mainForm.page1.exceltext}'].value;
+			 txt = window.clipboardData.getData("text");
+			 document.forms['{!$Component.mainForm}']['{!$Component.mainForm.page1.exceltext}'].value = txt;
+		}
+    </script>
+    <apex:form id="mainForm">
+        <apex:pageBlock id="page1">
+            <table>
+                <tr>
+                    <td><u><apex:outputLabel value="{!$Label.ImportText}"/></u></td>
+                    <td colspan="2">&nbsp;</td>
+                </tr>
+                <tr>
+                    <td colspan="2"><apex:outputLabel value="{!$Label.Tab_Text}"/></td>
+                    <td>&nbsp;<!-- <apex:commandButton onclick="setCB()" style="width:100px" value="{!$Label.Paste_IE}" /> --></td>
+                </tr>
+                <tr>
+                    <td colspan="3"><apex:inputTextarea style="width:350px;height:100px" id="exceltext"/></td>
+                </tr>
+                <tr>
+                    <td>&nbsp;</td>
+                    <td><apex:commandButton onclick="closeMe()" style="width:100px" value="{!$Label.Cancel}"/></td>
+                    <td><apex:commandButton onclick="sendText('dummy');return false;" style="width:100px" value="{!$Label.Registration}"/></td>
+                </tr>
+            </table>
+        </apex:pageBlock>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/QuoteExcelImport.page-meta.xml b/scr/pages/QuoteExcelImport.page-meta.xml
new file mode 100644
index 0000000..50029c5
--- /dev/null
+++ b/scr/pages/QuoteExcelImport.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>QuoteExcelImport</label>
+</ApexPage>
diff --git a/scr/pages/QuotePDF.page b/scr/pages/QuotePDF.page
new file mode 100644
index 0000000..0248eda
--- /dev/null
+++ b/scr/pages/QuotePDF.page
@@ -0,0 +1,163 @@
+<apex:page Controller="QuotePDFController" showHeader="false" sidebar="false" id="allPage" action="{!init}" renderAs="pdf">
+<head>
+    <style>
+        @page {
+            size: A4;
+            margin: 1mm 1mm 1mm 1mm;
+        }
+    </style>
+</head>
+<body style="font-family: Arial Unicode MS; page-break-inside: auto">
+    <table border="0" width="100%" style="border-collapse: collapse;">
+        <tr>
+            <td style="text-align:right;">{!quoteInfo.quoteDate}</td>
+        </tr>
+        <tr>
+            <td style="text-align:right;">{!$ObjectType.Quote.label}#{!quoteInfo.quoteNo}</td>
+        </tr>
+        <tr>
+            <td style="text-align:right;">{!$Label.Label_Total_pages}锛歿!pageCnt}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$Label.Label_From}锛歿!quoteInfo.dealerName}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$ObjectType.Contact.label}锛歿!quoteInfo.dealerContactName}&nbsp;&nbsp;&nbsp;&nbsp;{!$ObjectType.Contact.fields.MobilePhone.label}锛歿!quoteInfo.dealerContactPhone}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$ObjectType.Account.fields.Address1__c.label}锛歿!quoteInfo.dealerAddress}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$ObjectType.Contact.fields.Phone.label}锛歿!quoteInfo.dealerPhone}&nbsp;&nbsp;&nbsp;&nbsp;{!$ObjectType.Contact.fields.Fax.label}锛歿!quoteInfo.dealerFax}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$ObjectType.Contact.fields.Email.label}锛歿!quoteInfo.dealerEmail}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">&nbsp;</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$Label.Label_To}锛歿!quoteInfo.accountName}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!quoteInfo.accountContactName}</td>
+        </tr>
+        <tr>
+            <td style="text-align:left;">{!$ObjectType.Contact.fields.Phone.label}锛歿!quoteInfo.accountContactPhone}&nbsp;&nbsp;&nbsp;&nbsp;{!$ObjectType.Contact.fields.Email.label}锛歿!quoteInfo.accountContactEmail}</td>
+        </tr>
+    </table>
+
+    <br/>
+    Quotation Sheet(Quotation #{!quoteInfo.quoteNo})<br/>
+
+    <table border="1" width="100%" style="border-collapse: collapse;table-layout: fixed;">
+        <colgroup>
+            <col width="10%" />
+            <col width="60%" />
+            <col width="10%" />
+            <col width="20%" />
+        </colgroup>
+        <tr style="text-align: center;">
+            <th>{!$Label.Label_Units}</th>
+            <th>{!$Label.Label_Description}</th>
+            <th>{!$ObjectType.QuoteLineItem.fields.Quantity.label}</th>
+            <th>{!$ObjectType.QuoteLineItem.fields.TotalPrice.label}{!currencyIsoCode}</th>
+        </tr>
+        <apex:repeat value="{!printRecords}" var="set">
+        <tr>
+            <td style="text-align: center;"><apex:outputText value="{!set.units}" /></td>
+            <td><apex:outputText value="{!set.description}" /></td>
+            <td style="text-align: right;"><apex:outputText value="{!set.qty}" /></td>
+            <td style="text-align: right;"><apex:outputText value="{!set.total}" /></td>
+        </tr>
+        </apex:repeat>
+    </table>
+
+    <br/>
+
+    Note:<br/>
+<!--     1)  The payment terms are {!quoteInfo.note1} .<br/>
+    浠樻鏂瑰紡 {!quoteInfo.note2} 銆�<br/>
+    2)  Quoation valid until {!quoteInfo.note3} .<br/>
+    鎶ヤ环鏈夋晥鏈熷埌 {!quoteInfo.note3} 銆�<br/>
+    3)  All the commodoties come with {!quoteInfo.note4} year's manufacturer warranty.<br/>
+    鎵�鏈夊晢鍝佸惈 {!quoteInfo.note4} 骞村巶瀹朵繚淇��<br/>
+    4)  The above quotations are {!quoteInfo.note5} prices, Commodoties shipped to the clien's requirements.<br/>
+    涓婅堪鎶ヤ环涓� {!quoteInfo.note5} 浠凤紝鍟嗗搧閫佽嚦瀹㈡埛鎸囧畾鍦扮偣銆�<br/>
+    5)  The above quotations are all {!quoteInfo.note6}.<br/>
+    涓婅堪鎶ヤ环鍧囦负 {!quoteInfo.note7} 浠枫��<br/>
+    6)  Configuration as per attached.<br/>
+    閰嶇疆娓呭崟璇﹁闄勪欢銆�<br/> -->
+    <apex:outputText value="{!quoteInfo.comment}" escape="false"/>
+<!--     1)  The above quotations are CIP prices, Commodities shipped to the client鈥檚 requirements.<br/>
+    2)  The above quotations are all tax {!quoteInfo.note2}.<br/>
+    3)  The payment terms are {!quoteInfo.note3}.<br/>
+    4)  Quotation valid until {!quoteInfo.note4}.<br/>
+    5)  All the commodities come with {!quoteInfo.note5} year鈥檚 manufacturer warranty.<br/>
+    6)  Configuration as per attached.<br/>
+    7)  Delivery lead time is {!quoteInfo.note7} days after receipt of payment.<br/> -->
+
+    <apex:outputPanel rendered="{!pageCnt > 1}" layout="none">
+        <div style="page-break-after: always;"/>
+    </apex:outputPanel>
+
+<apex:variable value="{!1}" var="cnt1" />
+<apex:repeat value="{!printRecords}" var="set">
+    <!-- <apex:variable value="{!1}" var="cnt2" /> -->
+    <apex:repeat value="{!set.setPage}" var="sp">
+    <table border="1" width="100%" style="border-collapse: collapse;table-layout: fixed; font-size: 12px;">
+        <colgroup>
+            <col width="3%" />
+            <col width="10%" />
+            <col width="15%" />
+            <col width="{!IF(isPrintPrice=='true', 23, 33)}%" />
+            <col width="{!IF(isPrintPrice=='true', 20, 33)}%" />
+            <col width="5%" />
+            <apex:outputPanel rendered="{!isPrintPrice=='true'}" layout="none">
+            <col width="12%" />
+            <col width="12%" />
+            </apex:outputPanel>
+        </colgroup>
+        <!-- <apex:outputPanel rendered="{!cnt2 == 1}" layout="none"> -->
+        <tr style="text-align: center;">
+            <td colspan="{!IF(isPrintPrice=='true', 8, 6)}">{!set.description}{!$Label.Label_Set_detail}</td>
+        </tr>
+        <!-- </apex:outputPanel> -->
+        <tr style="text-align: center;">
+            <td>{!$Label.Label_No}</td>
+            <td>{!$ObjectType.Product2.fields.ProductCode.label}</td>
+            <td>{!$ObjectType.Product2.fields.Product_ECCode__c.label}</td>
+            <td>{!$ObjectType.Product2.fields.Description.label}</td>
+            <td>{!$ObjectType.QuoteLineItem.fields.Description.label}</td>
+            <td>{!$ObjectType.QuoteLineItem.fields.Quantity.label}</td>
+            <apex:outputPanel rendered="{!isPrintPrice=='true'}" layout="none">
+            <td>{!$ObjectType.QuoteLineItem.fields.UnitPrice.label}{!currencyIsoCode}</td>
+            <td>{!$ObjectType.QuoteLineItem.fields.TotalPrice.label}{!currencyIsoCode}</td>
+            </apex:outputPanel>
+        </tr>
+        <apex:repeat value="{!sp}" var="line">
+        <tr>
+            <td style="text-align: center;"><apex:outputText value="{!line.lineNo}" /></td>
+            <td><apex:outputText escape="false" value="{!line.productCode}" /></td>
+            <td><apex:outputText escape="false" value="{!line.productEC}" /></td>
+            <td><apex:outputText escape="false" value="{!line.description}" /></td>
+            <td><apex:outputText escape="false" value="{!line.comment}" /></td>
+            <td style="text-align: right;"><apex:outputText value="{!line.quantity}" /></td>
+            <apex:outputPanel rendered="{!isPrintPrice=='true'}" layout="none">
+            <td style="text-align: right;"><apex:outputText value="{!line.price}" /></td>
+            <td style="text-align: right;"><apex:outputText value="{!line.totalPrice}" /></td>
+            </apex:outputPanel>
+        </tr>
+        </apex:repeat>
+    </table>
+
+    <apex:outputPanel rendered="{!cnt1 < pageCnt - 1}" layout="none">
+        <div style="page-break-after: always;"/>
+    </apex:outputPanel>
+
+    <!-- <apex:variable value="{!cnt2 + 1}" var="cnt2" /> -->
+    <apex:variable value="{!cnt1 + 1}" var="cnt1" />
+    </apex:repeat>
+</apex:repeat>
+</body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/QuotePDF.page-meta.xml b/scr/pages/QuotePDF.page-meta.xml
new file mode 100644
index 0000000..cd99ee9
--- /dev/null
+++ b/scr/pages/QuotePDF.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>QuotePDF</label>
+</ApexPage>
diff --git a/scr/pages/QuotesPDF.page b/scr/pages/QuotesPDF.page
new file mode 100644
index 0000000..bafe58d
--- /dev/null
+++ b/scr/pages/QuotesPDF.page
@@ -0,0 +1,305 @@
+<apex:page controller="QuotesPDFController" showHeader="false" sidebar="false"  id="allPage" action="{!init}" renderAs="pdf">
+<!-- renderAs="pdf" -->
+
+      <html>
+            <head>
+                   <style>
+                    @page {
+                        size: A4 landscape;
+                        margin: 12mm 12mm 5mm 12mm;
+                    }
+
+            </style>
+            </head>
+
+            <body>
+                  <table border="0" style="font-family: Arial Unicode MS; page-break-inside: auto" width="100%">
+                        <colgroup>
+                      <col width="60%"/>
+                      <col width="10%"/>
+                      <col width="30%"/>
+                  </colgroup>
+                        <tr style="font-size: 12px;">
+                              <td rowspan="4"> <apex:image value="{!URLFOR($Resource.SWO)}" style="width: 50%;height: 50%"/></td>
+                              <td>鎶ヤ环鍗曞彿</td>
+                              <td>{!quo.ESTIMATE__c}</td>
+                        </tr>
+                        <tr style="font-size: 12px;">
+                              
+                              <td>鏃ユ湡</td>
+                              <td><apex:outputField value="{!quo.DATE__c}" /></td>
+                        </tr>
+                        <tr>
+                              
+                              <td>&nbsp;</td>
+                              <td></td>
+                        </tr>
+                        <tr style="font-size: 18px">
+                              
+                              <td>鎶ヤ环鍗�</td>
+                              <td></td>
+                        </tr>
+                  </table>
+                  <br/>
+                  <table border="0" style="font-family: Arial Unicode MS; page-break-inside: auto;font-size:12px;line-height: 10px" width="100%">
+                        <colgroup>
+                      <col width="60%"/>
+                      <col width="40%"/>
+                  </colgroup>
+                        <tr style="font-weight: bolder;font-size: 14px;">
+                              <th>鏀跺崟鏂�</th>
+                              <th>鏀惰揣鏂�</th>
+                        </tr>
+                        <tr rowspan="3">
+                              <td>
+                                  <!-- <c:PDFWbr targetStr="{!conName}"/><br/>
+                                  <c:PDFWbr targetStr="{!quo.COMPANYName__c}"/><br/> -->
+                                  <p style="line-height:15px;"><apex:outputField value="{!quo.BILL_TO__c}"/><br/>
+                                  CHINA
+                                  </p>
+                              </td>
+                              <td>
+                                  <!-- <c:PDFWbr targetStr="{!conName}"/><br/>
+                                  <c:PDFWbr targetStr="{!quo.COMPANYName__c}"/><br/> -->
+                                  <p style="line-height:15px;"><apex:outputField value="{!quo.SHIP_TO__c}"/><br/>
+                                  CHINA
+                                  </p>
+                              </td>
+                        </tr>
+                  </table>
+                  <br/>
+                  <br/>
+
+                  <table border="1" style="font-family: Arial Unicode MS; page-break-inside: auto;font-size:10px;line-height: 14px;border-style: solid; border-width: 1px; border-color: #ACACAC; border-collapse: collapse; " width="100%" cellpadding="0">
+                        <colgroup>
+                      <col width="20%"/>
+                      <col width="20%"/>
+                      <col width="20%"/>
+                      <col width="20%"/>
+                      <col width="20%"/>
+                  </colgroup>
+                  <tr style="background-color: #ACACAC;color: #fff">
+                        <td>澶辨晥</td>
+                        <td>璐у竵</td>
+                        <td>Incoterm</td>
+                        <td>璐︽湡</td>
+                        <td style="border-right-width: 0px;">Lead Time</td>
+                  </tr>
+                  <tr >
+                        <td><apex:outputField value="{!quo.EXPIRES__c}" /></td>
+                        <td>{!quo.CURRENCY__c}</td>
+                        <td>{!quo.INCOTERM__c}</td>
+                        <td>{!quo.TERMS__c}</td>
+                        <td style="border-right-width: 0px;">{!quo.LEAD_TIME__c}</td>
+                  </tr>
+                  <tr style="background-color: #ACACAC;color: #fff">
+                        <td>PO 缂栧彿</td>
+                        <td>Contact Name</td>
+                        <td>Contact Phone</td>
+                        <td colspan="2" style="border-right-width: 0px;">Contact Email</td>
+                        <!-- <td style="border-right-width: 0px;"></td> -->
+                  </tr>
+                  <tr>
+                        <apex:outputPanel layout="none" rendered="{!IF(quo.PO__c != null, true, false)}">
+                            <td style="border-bottom-width: 0;">{!quo.PO__c}&nbsp;</td>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(quo.PO__c != null, false, true)}">
+                              <td style="border-bottom-width: 0;">&nbsp;</td>
+                        </apex:outputPanel>
+
+                        <apex:outputPanel layout="none" rendered="{!IF(conName != null, true, false)}">
+                              <td style="border-bottom-width: 0;">{!conName}&nbsp;</td>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(conName != null, false, true)}">
+                              <td style="border-bottom-width: 0;">&nbsp;</td>
+                        </apex:outputPanel>
+
+                        <apex:outputPanel layout="none" rendered="{!IF(quo.CONTACT_PHONE__c != null, true, false)}">
+                              <td style="border-bottom-width: 0;">{!quo.CONTACT_PHONE__c}&nbsp;</td>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(quo.CONTACT_PHONE__c != null, false, true)}">
+                              <td style="border-bottom-width: 0;">&nbsp;</td>
+                        </apex:outputPanel>
+
+                        <apex:outputPanel layout="none" rendered="{!IF(quo.CONTACT_EMAIL__c != null, true, false)}">
+                              <td colspan="2" style="border-right-width: 0px;">{!quo.CONTACT_EMAIL__c}&nbsp;</td>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(quo.CONTACT_EMAIL__c != null, false, true)}">
+                              <td colspan="2" style="border-right-width: 0px;">&nbsp;</td>
+                        </apex:outputPanel>
+                        
+                  </tr>
+                  </table>
+                  <table border="1" style="font-family: Arial Unicode MS;font-size:10px;line-height: 10px;border-style: solid; border-width: 1px; border-color: #ACACAC; border-collapse: collapse;  " width="100%" cellpadding="0">
+                        <colgroup>
+                      <col width="10%"/>
+                      <col width="15%"/>
+                      <col width="5%"/>
+                      <col width="30%"/>
+                      <col width="8%"/>
+                      <col width="8%"/>
+                      <col width="8%"/>
+                      <col width="8%"/>
+                      <col width="8%"/>
+                  </colgroup>
+                  <tr style="background-color: #ACACAC;color: #fff;border-bottom-width: 1px;line-height: 14px;">
+                        <th style="vertical-align:middle;">璐у搧</th>
+                        <th style="vertical-align:middle;">Part Number</th>
+                        <th style="vertical-align:middle;">鏁伴噺</th>
+                        <th style="vertical-align:middle;">璇存槑</th>
+                        <th style="vertical-align:middle;">鍗曚环</th>
+                        <th style="vertical-align:middle;">涓嶅惈绋庡悎璁�...</th>
+                        <th style="vertical-align:middle;">绋庣巼</th>
+                        <th style="vertical-align:middle;">绋庨</th>
+                        <th style="vertical-align:middle;border-right-width: 0;border-bottom-width: 1px">鎬婚噾棰�</th>
+
+                  </tr>
+                  <apex:repeat id="quoteList" value="{!lineList}" var="item">
+                        <apex:outputPanel layout="none" rendered="{!IF(item.description != '绌虹櫧琛�', true, false)}">
+                        <tr>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><c:PDFWbr targetStr="{!item.productName}"/></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><c:PDFWbr targetStr="{!item.qi.PART_NUMBERNew__c}"/></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.QUANTITY__c}</td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><c:PDFWbr targetStr="{!item.description}"/></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!item.qi.RATE__c}"/>
+                              </apex:outputText></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!item.qi.AMOUNT__c}"/>
+                              </apex:outputText></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!item.qi.TAX_RATE__c}"/>
+                              </apex:outputText></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!item.qi.TAX_AMT__c}"/>
+                              </apex:outputText></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">
+                                <apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!item.qi.GROSS_AMT__c}"/>
+                              </apex:outputText></td>
+                        </tr>
+                        </apex:outputPanel>
+                        <apex:outputPanel layout="none" rendered="{!IF(item.description == '绌虹櫧琛�', true, false)}">
+                        <tr>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">&nbsp;</td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                              <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                        </tr>  
+                        </apex:outputPanel>    
+                  </apex:repeat>
+                  
+                  </table>
+
+                  <apex:outputPanel rendered="{!pageNum==2}">
+                        <table border="1" style="font-family: Arial Unicode MS;font-size:9px;line-height: 10px;border-style: solid; border-width: 1px; border-color: #ACACAC; border-collapse: collapse;  " width="100%" cellpadding="0">
+                              <colgroup>
+                                  <col width="10%"/>
+                                  <col width="15%"/>
+                                  <col width="5%"/>
+                                  <col width="30%"/>
+                                  <col width="8%"/>
+                                  <col width="8%"/>
+                                  <col width="8%"/>
+                                  <col width="8%"/>
+                                  <col width="8%"/>
+                              </colgroup>
+                              <tr style="background-color: #ACACAC;color: #fff">
+                                    <th>璐у搧</th>
+                                    <th>Part Number</th>
+                                    <th>鏁伴噺</th>
+                                    <th>璇存槑</th>
+                                    <th>鍗曚环</th>
+                                    <th>涓嶅惈绋庡悎璁�...</th>
+                                    <th>绋庣巼</th>
+                                    <th >绋庨</th>
+                                    <th style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">鎬婚噾棰�</th>
+                              </tr>
+                              <apex:repeat id="quoteList2" value="{!lineList2}" var="item">
+                                    <apex:outputPanel layout="none" rendered="{!IF(item.description != '绌虹櫧琛�', true, false)}">
+                                    <tr>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><c:PDFWbr targetStr="{!item.productName}"/></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><c:PDFWbr targetStr="{!item.qi.PART_NUMBERNew__c}"/></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.QUANTITY__c}</td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"><c:PDFWbr targetStr="{!item.description}"/></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.RATE__c}</td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.AMOUNT__c}</td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.TAX_RATE__c}</td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.TAX_AMT__c}</td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">{!item.qi.GROSS_AMT__c}</td>
+                                    </tr>
+                                    </apex:outputPanel>
+                                    <apex:outputPanel layout="none" rendered="{!IF(item.description == '绌虹櫧琛�', true, false)}">
+                                    <tr>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;">&nbsp;</td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                          <td style="border-bottom-width: 0; border-right-width: 0; border-top-width: 0;"></td>
+                                    </tr>  
+                                    </apex:outputPanel>    
+                              </apex:repeat>
+                        </table>
+                  </apex:outputPanel>
+
+                  <table border="0" style="font-family: Arial Unicode MS; page-break-inside: auto;font-size: 7px;" width="100%">
+                        <colgroup>
+                      <col width="76%"/>
+                      <col width="12%"/>
+                      <col width="12%"/>
+                  </colgroup>
+                  <tr>
+                        <td rowspan="4">
+                              <apex:outputField value="{!quo.CUSTOMER_MESSAGE__c}" />
+ <!--                               -鍦ㄧ淮淇殑杩囩▼涓紝鑻ュ彂鐜版柊鏁呴殰锛屾垜浠皢鍙﹀缁欐偍鎶ヤ环銆�<br/>
+-缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿��<br/>
+-<br/>
+濡傛偍纭姝ゆ姤浠峰苟鍚屾剰缁翠慨锛屾暚璇锋偍鍦�90澶╀箣鍐呭畬鎴愪粯娆俱�傚惁鍒欐偍鐨勪华鍣ㄨ灏嗚涓烘斁寮冪淮淇紝鎴戜滑浼氫互杩愯垂鍒颁粯鐨勬柟寮忔妸<br/>浠櫒缁欐偍瀵勫洖,骞跺悜鎮ㄦ敹鍙�1000鍏冪殑妫�娴嬭垂鐢ㄣ��<br/>   
+-鐢ㄦ埛鍦ㄦ纭鍚屾剰姝ゆ缁翠慨鎶ヤ环锛�<br/>
+瀹㈡埛绛惧瓧鎴栫洊绔狅細<br/>
+鏃ユ湡锛� -->
+                        </td>
+                        <td style="vertical-align: bottom; font-size: 14px;">
+                              Subtotal
+                        </td>
+                        <td style="vertical-align: bottom;font-size: 14px;">
+                              <apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!quo.SUBTOTAL__c}"/>
+                              </apex:outputText>
+                        </td>
+                  </tr>
+                  <tr>
+                      <apex:outputPanel layout="none" rendered="{!IF(quo.DISCOUNT__c != 0, true, false)}">
+                        <td style="vertical-align: top;font-size: 14px;">Discount</td>
+                        <td style="vertical-align: top;font-size: 14px;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!quo.DISCOUNT__c}"/>
+                              </apex:outputText></td>
+                      </apex:outputPanel>
+                  </tr>
+                  <tr>
+                        <td style="vertical-align: top;font-size: 14px;">Tax Total</td>
+                        <td style="vertical-align: top;font-size: 14px;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!quo.TAX__c}"/>
+                              </apex:outputText></td>
+                  </tr>
+                  <tr>
+                        <td style="vertical-align: top;font-size: 14px;">Total</td>
+                        <td style="vertical-align: top;font-size: 14px;"><apex:outputText value="{0,number,###,###,##0.00}">
+                                  <apex:param value="{!quo.TOTAL__c}"/>
+                              </apex:outputText></td>
+                  </tr>
+                  </table>
+
+
+            </body>
+      </html>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/QuotesPDF.page-meta.xml b/scr/pages/QuotesPDF.page-meta.xml
new file mode 100644
index 0000000..691c58b
--- /dev/null
+++ b/scr/pages/QuotesPDF.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>QuotesPDF</label>
+</ApexPage>
diff --git a/scr/pages/SWOPage.page b/scr/pages/SWOPage.page
new file mode 100644
index 0000000..b9d64c1
--- /dev/null
+++ b/scr/pages/SWOPage.page
@@ -0,0 +1,1787 @@
+<apex:page standardController="SWO__c" extensions="SWOController" showChat="false" showHeader="true" sidebar="false" action="{!init}" id="Page">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+
+	<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+	<script>
+		var IS_OPEN = true;
+
+		j$(document).ready(function() {
+			var type = j$(escapeVfId("type")).value();
+			clickColorChange(type);
+		});
+    	function openPDF(){
+    		if(!IS_OPEN){
+    			return;
+    		}
+    		openPageSave();
+    		var baseUrl = j$(escapeVfId("baseUrl")).value();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		/*alert(baseUrl);
+    		alert(swoId);*/
+
+    		window.open(baseUrl + '/apex/SendEmail?type=SWO&typeid=' + swoId);
+    		//openPopup(baseUrl + '/apex/SendEmail?type=SWO&typeid=' + swoId, 'pselect', 950, 450, 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+    		window.close();
+
+    	} 
+    	function searchProduct(i,str){
+           var baseUrl = '{!baseUrl}';
+            openPopup(baseUrl + '/apex/SWOSearchProduct?lineno=' + i + '&val=' + encodeURIComponent(str), 'pselect', 950, 450, 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+         function getLastLineNoNext(doc) {
+            var hasRecordFlg = false;
+            var lastLineNo = 0;
+            for(var i=99; i>=0; i--){
+                if (j$(escapeVfId('Page:mainForm:diagnosisList:' + i + ':Name')).value() != ''){
+                    if (!hasRecordFlg) {
+                        lastLineNo = i;
+                    }
+                    hasRecordFlg = true;
+                }
+                if (hasRecordFlg == true) {
+                    if (j$(escapeVfId('Page:mainForm:diagnosisList:' + i + ':Name')).value() == ''){
+                        var moveCheckbox = true;
+                        //deletelist(i, doc, moveCheckbox);
+                        lastLineNo = i;
+                    }
+                }
+            }
+            if (hasRecordFlg) {
+                lastLineNo = lastLineNo + 1;
+            }
+            return lastLineNo;
+        }
+
+    	function openQuote(){
+    		if(!IS_OPEN){
+    			return;
+    		}
+    		var baseUrl = j$(escapeVfId("baseUrl")).value();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		openPageSave();
+    		/*alert(baseUrl);
+    		alert(swoId);*/
+    		window.open(baseUrl + '/apex/NEWCreateSWOQuote?swoId=' + swoId);
+    		window.close();
+    	}
+
+    	function openRepair(id){
+    		if(!IS_OPEN){
+    			return;
+    		}
+    		/*var baseUrl = j$(escapeVfId("baseUrl")).value();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		var name = j$(escapeVfId("Name")).value();
+    		alert(baseUrl);
+    		alert(swoId);
+    		window.open(baseUrl + '/a0n/e?CF00N1e000000m7My= '+name+'&CF00N1e000000m7My_lkid=' + swoId + '&retURL=%2F'+swoId);*/
+    		openPageSave();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		var baseUrl = j$(escapeVfId("baseUrl")).value();
+            //var repairId = j$(escapeVfId("repairId")).value();
+            window.open(baseUrl + '/apex/NewRepairParts?swoId='+swoId+'&id='+id,'pselect', 'width=900,height=500,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+    	}
+
+        function openDiagnosisPart(){
+            if(!IS_OPEN){
+                return;
+            }
+            /*var baseUrl = j$(escapeVfId("baseUrl")).value();
+            var swoId = j$(escapeVfId("swoid")).value();
+            var name = j$(escapeVfId("Name")).value();
+            alert(baseUrl);
+            alert(swoId);
+            window.open(baseUrl + '/a0n/e?CF00N1e000000m7My= '+name+'&CF00N1e000000m7My_lkid=' + swoId + '&retURL=%2F'+swoId);*/
+            openPageSave();
+            var swoId = j$(escapeVfId("swoid")).value();
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            //var repairId = j$(escapeVfId("repairId")).value();
+            window.open(baseUrl + '/apex/NewDiagnosisPart?swoId='+swoId,'pselect', 'width=900,height=500,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+
+    	function repairReturnJS(repairPartId,swoId){
+    		repairReturn(swoid);
+    	}
+
+    	function mastDataJS(){
+    		mustData();
+    	}
+    	function isOk(){
+    		var errorMessage = j$(escapeVfId("errorMessage")).value();
+    		alert(errorMessage);
+    	}
+
+    	function clickColorChange(str){
+    		j$(escapeVfId("titleProduct")).attr("class","title1");
+    		j$(escapeVfId("titleCase")).attr("class","title1");
+    		j$(escapeVfId("titlemail")).attr("class","title1");
+    		j$(escapeVfId("titleTracking")).attr("class","title1");
+    		j$(escapeVfId("titleTechnical")).attr("class","title1");
+    		j$(escapeVfId("titleEstimation")).attr("class","title1");
+    		j$(escapeVfId("titleRepair")).attr("class","title1");
+    		j$(escapeVfId("titleQuotes")).attr("class","title1");
+    		j$(escapeVfId("titleGeneral")).attr("class","title1");
+    		j$(escapeVfId("titleIncoming")).attr("class","title1");
+    		j$(escapeVfId("titleOutgoing")).attr("class","title1");
+    		j$(escapeVfId("titleFault")).attr("class","title1");
+    		j$(escapeVfId("titleDiagnosis")).attr("class","title1");
+
+    		j$(escapeVfId("title"+str)).attr("class","title2");
+    	}
+
+    	function clickRepeat(){
+    		var obj = j$(escapeVfId("Page:mainForm:REPEAT")).value();
+    		if(obj == "1"){
+    			j$(escapeVfId("Page:mainForm:REPEAT")).attr("style","visibility:visible");
+    		}else{
+    			j$(escapeVfId("Page:mainForm:REPEAT")).attr("style","visibility:hidden");
+    		}
+    	}
+
+    	function uploadFileJS(){
+    		SWO_Id();
+    		if(!IS_OPEN){
+    			return;
+    		}
+    		openPageSave();
+    		uploadFile();
+    	}
+
+    	function SWO_Id(){
+    		IS_OPEN = true;
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		if(swoId == "" || swoId == null){
+    			alert("璇峰厛淇濆瓨SWO");
+    			IS_OPEN = false;
+    		}
+    	}
+	</script>
+
+	<style type="text/css"> 
+		.Page{
+			margin-left: 20px;
+			margin-right: 20px;
+		}
+
+		.title{
+    		height: 30px;
+    		background-color: #DFE6F0;
+    		font-size: 15px;
+    		color:#607799;
+    		font-weight: bold;
+    	}
+    	.title1{
+    		text-align:center;
+    		height: 30px;
+    		background-color: #607799;
+    		font-size: 15px;
+    		color:#FFFFFF;
+    		font-weight: bold;
+    	}
+    	.title1:hover{
+    		text-align:center;
+    		height: 28px;
+    		background-color: #DFE6F0;
+    		font-size: 15px;
+    		color:#00FFFF;
+    		font-weight: bold;
+    		padding: 0px 2px; 
+    	}
+    	.title2{
+    		text-align:center;
+    		height: 28px;
+    		background-color: #DFE6F0;
+    		font-size: 15px;
+    		color:#00FFFF;
+    		font-weight: bold;
+    		padding: 0px 2px; 
+    	}
+
+    	.red {
+            background-color:#B22222;
+            text-align: right;
+        }
+
+        .textRed{
+        	color: #B22222;
+        	font-size: 16px;
+        	font-weight: 700;
+        }
+
+        .messageInfo{
+        	color: #B22222;
+        	font-size: 16px;
+        }
+	</style>
+
+	<apex:form id="mainForm" style="width: 95%; margin-left: 30px;">
+		<apex:actionFunction name="mustData" action="{!mustData}" reRender="messageInfo" oncomplete="clickColorChange('Repair')"></apex:actionFunction>
+		<apex:actionFunction name="repairReturn" action="{!init}" reRender="mainForm" >
+			<apex:param name="swoid" assignTo="{!swoid}" value="" /><!-- mailRepair mainForm-->
+		</apex:actionFunction>
+		<apex:actionFunction name="openPageSave" action="{!openPageSave}" reRender="">
+		</apex:actionFunction>
+		<apex:actionFunction name="uploadFile" action="{!uploadFile}"></apex:actionFunction>
+		<input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+		<input type="hidden" id="swoid" value="{!swoid}"/>
+		<input type="hidden" id="type" value="{!type}"/>
+		<input type="hidden" id="Name" value="{!swo.Name}"/>
+		<input type="hidden" id="errorMessage" value="{!errorMessageInfo}" />
+		<br/>
+		<h3 id="h3" style="font-size: 24px;">Service Work Order</h3><br/>
+		<h3 style="font-size: 24px;">{!swo.Name}</h3>
+		<br/>
+		<br/>
+		<!-- <div id="messageInfo" class="messageInfo">
+			{!errorMessageInfo}
+		</div> -->
+		<apex:outputPanel id="messageInfo">
+			<apex:pagemessages />
+        </apex:outputPanel>
+		<apex:commandButton onclick="blockme();" value="Save" action="{!save}" style="width: 5%;"/>
+		<table style="width: 100%;">
+			<colgroup>
+	            <col width="16%"/>
+	            <col width="17%"/>
+	            <col width="33%"/>
+	            <col width="17%"/>
+	            <col width="17%"/>
+	        </colgroup>
+
+	        <tr>
+	        	<th colspan="5" class="title">SWO Basic Information</th>
+	        </tr>
+	        <tr>
+	        	<td>{!$ObjectType.SWO__c.fields.Name.label}</td>
+	        	<td >{!$ObjectType.SWO__c.fields.ETQ_NUMBER__c.label}</td>
+	        	<td><apex:inputField value="{!swo.EPCI_REQUIRED_FROM_CUSTOMER__c}" />{!$ObjectType.SWO__c.fields.EPCI_REQUIRED_FROM_CUSTOMER__c.label}</td>
+	        	<td>{!$ObjectType.SWO__c.fields.CUSTOMER_PO__c.label}</td>
+	        	<td>{!$ObjectType.SWO__c.fields.QUOTE_LEVEL__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td><apex:inputField value="{!swo.Name}"/></td>
+	        	<td><apex:inputField value="{!swo.ETQ_NUMBER__c}"/></td>
+	        	<td>{!$ObjectType.SWO__c.fields.SWO_STATUS__c.label}<span class="textRed">*</span></td>
+	        	<td><apex:inputField value="{!swo.CUSTOMER_PO__c}"/></td>
+	        	<td><apex:inputField value="{!swo.QUOTE_LEVEL__c}"/></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.SUBJECT__c.label}</td>
+	        	<td><apex:inputField value="{!swo.SWO_STATUS__c}"/></td>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.CLIN__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.SUBJECT__c}"/></td>
+	        	<td>{!$ObjectType.SWO__c.fields.SWO_STAGE__c.label}</td>
+	        	<td colspan="2"><apex:inputField value="{!swo.CLIN__c}"/></td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.SHIP_TO_LOCATION__c.label}</td>
+	        	<td><apex:inputField value="{!swo.SWO_STAGE__c}"/></td>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.ASSIGNEDTO__c.label}<span class="textRed">*</span></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.SHIP_TO_LOCATION__c}"/></td>
+	        	<td>{!$ObjectType.SWO__c.fields.TYPE__c.label}<span class="textRed">*</span></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.ASSIGNEDTO__c}" style="width: 50%;"/></td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.OFFICE__c.label}<span class="textRed">*</span></td>
+	        	<td><apex:inputField value="{!swo.TYPE__c}"/></td>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.CONTACT_NAME_HIDDEN__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.OFFICE__c}"/></td>
+	        	<td></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.CONTACT_NAME_HIDDEN__c}"/></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.SWO_PRIORITY__c.label}<span class="textRed">*</span></td>
+	        	<td></td>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.SO_NUMBER__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.SWO_PRIORITY__c}"/></td>
+	        	<td></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.SO_NUMBER__c}"/></td>
+	        </tr>
+	        
+		</table>
+
+		<table style="width: 100%;">
+			<colgroup>
+	            <col width="33%"/>
+	            <col width="33%"/>
+	            <col width="34%"/>
+	        </colgroup>
+
+	        <tr>
+	        	<td colspan="3" class="title">ETQ</td>
+	        </tr>
+
+	        <tr>
+	        	<td >{!$ObjectType.SWO__c.fields.MDR_STATEMENT__c.label}</td>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.PAE_Q_2__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td ><apex:inputField value="{!swo.MDR_STATEMENT__c}"/></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.PAE_Q_2__c}"/></td>
+	        </tr>
+	    </table>
+
+	    <table style="width: 100%;border-collapse: collapse; " >
+			<colgroup>
+	            <col width="16%"/>
+	            <col width="17%"/>
+	            <col width="33%"/>
+	            <col width="17%"/>
+	            <col width="17%"/>
+	        </colgroup>
+
+	        <tr class="title">
+	        	<td colspan="2" class="title">Repair Loaner</td>
+	        	<td class="title">Service Unit</td>
+	        	<td colspan="2" class="title">SWO Reason/Warranty Information</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.REPAIR_LOANER_SENT__c}" />{!$ObjectType.SWO__c.fields.REPAIR_LOANER_SENT__c.label}</td>
+	        	
+	        	<td>{!$ObjectType.SWO__c.fields.DEPARTMENT__c.label}<span class="textRed">*</span></td>
+	        	<td colspan="2">{!$ObjectType.SWO__c.fields.REASON__c.label}<span class="textRed">*</span></td>
+	        </tr>
+
+	         <tr>
+	         	<td colspan="2"><apex:inputField value="{!swo.REPAIR_LOANER_NOT_REQUIRED__c}" />{!$ObjectType.SWO__c.fields.REPAIR_LOANER_NOT_REQUIRED__c.label}</td>
+	        	
+	        	<td><apex:inputField value="{!swo.DEPARTMENT__c}" /></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.REASON__c}" /></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.REPAIR_LOANER_NOT_PROVIDED__c}" />{!$ObjectType.SWO__c.fields.REPAIR_LOANER_NOT_PROVIDED__c.label}</td>
+	        	
+	        	<td>{!$ObjectType.SWO__c.fields.PRODUCT_TYPE__c.label}<span class="textRed">*</span></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.UNDER_CONTRACT__c}"/>{!$ObjectType.SWO__c.fields.UNDER_CONTRACT__c.label}</td>
+	        </tr>
+	         <tr>
+	         	<td colspan="2">{!$ObjectType.SWO__c.fields.INSTRUMENT_MODEL__c.label}</td>
+	        	
+	        	<td><apex:inputField value="{!swo.PRODUCT_TYPE__c}"/></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.FACTORY_WARRANTY__c}"/>{!$ObjectType.SWO__c.fields.FACTORY_WARRANTY__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.INSTRUMENT_MODEL__c}"/></td>
+	        	
+	        	<td>{!$ObjectType.SWO__c.fields.CV_REPAIR_TYPE__c.label}</td>
+	        	<td colspan="2"><apex:inputField value="{!swo.OAI_WARRANTY__c}"/>{!$ObjectType.SWO__c.fields.OAI_WARRANTY__c.label}</td>
+	        </tr>
+	         <tr>
+	         	<td colspan="2">{!$ObjectType.SWO__c.fields.LOANER_SERIAL__c.label}</td>
+	        	
+	        	<td><apex:inputField value="{!swo.CV_REPAIR_TYPE__c}"/></td>
+	        	<td colspan="2"><apex:inputField value="{!swo.EXTENDED_WARRANTY__c}"/>{!$ObjectType.SWO__c.fields.EXTENDED_WARRANTY__c.label}</td>
+	        </tr>
+
+	         <tr>
+	         	<td colspan="2"><apex:inputField value="{!swo.LOANER_SERIAL__c}"/></td>
+	        	
+	        	<td></td>
+	        	<td>{!$ObjectType.SWO__c.fields.CLAIM__c.label}</td>
+	        	<td>{!$ObjectType.SWO__c.fields.PREV_CLAIMS__c.label}</td>
+	        </tr>
+	         <tr>
+	         	<td colspan="2" style="">{!$ObjectType.SWO__c.fields.LOANER_SHIPPED_DATE__c.label}</td>
+	        	
+	        	<td> &nbsp;</td>
+	        	<td><apex:inputField value="{!swo.CLAIM__c}"/></td>
+	        	<td><apex:inputField value="{!swo.PREV_CLAIMS__c}"/></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.LOANER_SHIPPED_DATE__c}"/></td>
+	        	
+	        	<td></td>
+	        	<td><apex:inputField value="{!swo.TRUE_PROTECTION_PLAN__c}"/>{!$ObjectType.SWO__c.fields.TRUE_PROTECTION_PLAN__c.label}</td>
+	        	<td>{!$ObjectType.SWO__c.fields.PER__c.label}</td>
+	        	
+	        </tr>
+	         <tr>
+	         	<td colspan="2">{!$ObjectType.SWO__c.fields.LOANER_RECEIVED_DATE__c.label}</td>
+	        	
+	        	<td></td>
+	        	<td><apex:inputField value="{!swo.GOOD_WILL__c}"/>{!$ObjectType.SWO__c.fields.GOOD_WILL__c.label}</td>
+	        	<td><apex:inputField value="{!swo.PER__c}"/></td>
+	        	
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:inputField value="{!swo.LOANER_RECEIVED_DATE__c}"/></td>
+	        	<td></td>
+	        	<td></td>
+	        	<td></td>
+	        	
+	        </tr>
+	        <tr>
+	        	<td><apex:inputField value="{!swo.GOVERNMENT_PROPERTY__c}"/>{!$ObjectType.SWO__c.fields.GOVERNMENT_PROPERTY__c.label}</td>
+	        	<td></td>
+	        	<td></td>
+	        	<td></td>
+	        	<td></td>
+	        	
+	        	
+	        </tr>
+
+	        <tr>
+	        	<td>&nbsp;</td>
+	        </tr>
+
+	    </table>
+
+	    <table style="width: 100%;border-collapse: collapse;">
+	    	<tr class="title">
+	    		<td id="titleProduct" class="title1"><apex:commandLink oncomplete="clickColorChange('Product')" action="{!setProduct}" reRender="table" value="Product Info" /></td>
+	    		<td id="titleCase" class="title1"><apex:commandLink oncomplete="clickColorChange('Case')" action="{!setCase}" reRender="table" value="Case Info" /></td>
+	    		<td id="titlemail" class="title1"><apex:commandLink oncomplete="clickColorChange('mail')" action="{!setMail}" reRender="table" value="Mail Merge" /></td>
+	    		<td id="titleTracking" class="title1"><apex:commandLink oncomplete="clickColorChange('Tracking')" action="{!setTracking}" reRender="table" value="Tracking" /></td>
+	    		<td id="titleTechnical" class="title1"><apex:commandLink oncomplete="clickColorChange('Technical')" action="{!setTechnical}" reRender="table" value="Technical Info" /></td>
+	    		<td id="titleEstimation" class="title1"><apex:commandLink oncomplete="clickColorChange('Estimation')" action="{!setEstimation}" reRender="table" value="Estimation" /></td>
+	    		<td id="titleRepair" class="title1"><apex:commandLink oncomplete="clickColorChange('Repair')" action="{!setRepair}" reRender="table" value="Repair Parts" /></td>
+	    		<td id="titleDiagnosis" class="title1"><apex:commandLink oncomplete="clickColorChange('Diagnosis')" action="{!setDiagnosis}" reRender="table" value="Diagnosis part " /></td>
+	    		<td id="titleQuotes" class="title1"><apex:commandLink oncomplete="clickColorChange('Quotes')" action="{!setQuotes}" reRender="table" value="Quotes" /></td>
+	    		<td id="titleGeneral" class="title1"><apex:commandLink oncomplete="clickColorChange('General')" action="{!setGeneral}" reRender="table" value="General" /></td>
+	    		<td id="titleIncoming" class="title1"><apex:commandLink oncomplete="clickColorChange('Incoming')" action="{!setIncoming}" reRender="table" value="Incoming Quality" /></td>
+	    		<td id="titleOutgoing" class="title1"><apex:commandLink oncomplete="clickColorChange('Outgoing')" action="{!setOutgoing}" reRender="table" value="Outgoing Quality" /></td>
+	    		<td id="titleFault" class="title1"><apex:commandLink oncomplete="clickColorChange('Fault')" action="{!setFault}" reRender="table" value="Fault Analysis" /></td>
+	    	</tr>
+	    </table>
+	    <br/>
+	    <apex:outputPanel id="table">
+	    	<apex:outputPanel rendered="{!IF(type = 'mail' || type = 'All',true,false)}">
+	    		<br/>
+	    		<apex:commandButton id="openPDF" value="Mail" onclick="SWO_Id();openPDF();return false;" style="width: 5%" />
+	    		<br/>
+	    		<table id="mailTable" style="width: 100%">
+	    			<colgroup>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			        </colgroup>
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+	    				<td>VIEW</td> 
+	    				<td>DATE</td>
+	    				<td>AUTHOR</td>
+	    				<td>MESSAGE</td>
+	    				<td>EMAIL SENT</td>
+	    				<td>PRIMARY RECIPIENT</td>
+	    				<td>CC</td>
+	    				<td>FILES</td>
+	    				<td>ATTACHMENTS</td>
+	    				<td>INTERNAL ONLY</td>
+	    			</tr>
+	    			<apex:repeat value="{!mailList}" var="mail" id="lines">
+	    				<tr>
+	    					<td><apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=SWO&typeid={!swoid}&openType=View">View</apex:outputLink>&nbsp;&nbsp;<apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=SWO&typeid={!swoid}&openType=Reply">Reply</apex:outputLink></td> 
+	    					<td><apex:outputField value="{!mail.mm.DATE__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.FROM__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.MESSAGE__c}" /></td>
+	    					<td><apex:outputText value="{!mail.mm.EMAIL_SENT__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.toName__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.ccName__c}" /></td>
+	    					<td><apex:outputText value="{!mail.haveAtt}" /></td>
+	    					<td>
+	    						<apex:repeat value="{!mail.attList}" var="att" id="lines">
+	    							<apex:outputLink value="/{!att.Id}"><c:PDFWbr targetStr="{!att.Name}" /></apex:outputLink>
+	    							<br/>
+	    						</apex:repeat>
+	    					</td>
+	    					<td><apex:outputText value="YES" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Quotes' || type = 'All',true,false)}">
+	    		<br/>
+	    		<apex:commandButton id="openquotes" value="Quotes" onclick="SWO_Id();openQuote();return false;" style="width: 5%"/>
+	    		<br/>
+	    		<table id="mailTable" style="width: 100%">
+	    			<colgroup>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			        </colgroup>
+	    			<tr style="background-color: #ccc;font-size:13px;line-height: 20px;width: 98%;">
+	    				<td>QUOTE NUMBER</td>
+	    				<td>STATUS</td>
+	    				<td>ITEM</td>
+	    				<td>PART NUMBER</td>
+	    				<td>QUANTITY</td>
+	    				<td>CURRENCY</td>
+	    				<td>AMOUNT</td>
+	    				
+	    			</tr>
+	    			<apex:repeat value="{!qiList}" var="qi" id="quotesLines">
+	    				<tr>
+	    					<td><apex:outputLink value="/{!qi.QUOTE__r.ID}" >{!qi.QUOTE__r.Name}</apex:outputLink></td>
+	    					<td><apex:outputField value="{!qi.QUOTE__r.STATUS__c}" /></td>
+	    					<td><apex:outputField value="{!qi.QuotesItemProduct__c}" /></td>
+	    					<td><apex:outputField value="{!qi.PART_NUMBERNew__c}" /></td>
+	    					<td><apex:outputField value="{!qi.QUANTITY__c}" /></td>
+	    					<td><apex:outputField value="{!qi.CURRENCY__c}" /></td>
+	    					<td><apex:outputField value="{!qi.AMOUNT__c}" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+
+	    		</table>
+	    	</apex:outputPanel>
+
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Repair' || type = 'All',true,false)}">
+	    		<br/>
+	    		<apex:commandButton id="openRepair" value="Repair Parts" onclick="SWO_Id();openRepair('');return false;" style="width: 8%"/>
+	    		<br/>
+	    		<table id="mailRepair" style="width: 100%;">
+	    			
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+	    				<td>ID</td>
+	    				<td>ITEM</td>
+	    				<td>PART NUMBER</td>
+	    				<td>INST. SERIAL #</td>
+	    				<td>DESCRIPTION</td>
+	    				<td>QUANTITY</td>
+	    				<td>DEFECT PART NUMBER</td>
+	    				<td>DEFECT SERIAL NUMBER</td>
+	    				<!-- <td>ANI DEFECT CATEGORY</td> -->
+	    				<td>HOURS</td>
+	    				<td>LOCATION</td>
+	    				<td>BILL AT 0$ VALUE</td>
+	    				<td>ECN</td>
+	    				<td>QTY PICKED</td>
+	    			</tr>
+	    			<apex:repeat value="{!rpList}" var="rp" id="RepairLines">
+	    				<tr>
+	    					<!-- value="/{!rp.ID}" -->
+	    					<!-- <td><apex:outputLink value="/{!rp.ID}" >{!rp.Name}</apex:outputLink></td> -->
+	    					<td><apex:outputLink onclick="openRepair('{!rp.ID}')" value="javascript:void(0)" >{!rp.Name}</apex:outputLink></td>
+	    					<td><apex:outputField value="{!rp.Product__r.ProductCode}" /></td>
+	    					<td><apex:outputField value="{!rp.Product__r.Product_ECCode__c}" /></td>
+	    					<td><apex:outputField value="{!rp.INST_SERIAL__c}" /></td>
+	    					<td><apex:outputField value="{!rp.Product__r.Description}" /></td>
+	    					<td><apex:outputField value="{!rp.QUANTITY__c}" /></td>
+	    					<td><apex:outputField value="{!rp.DEFECT_PART_NUMBER__c}" /></td>
+	    					<td><apex:outputField value="{!rp.DEFECT_SERIAL_NUMBER__c}" /></td>
+	    					<!-- <td><apex:outputField value="{!rp.DEFECT_CATEGORY__c}" /></td> -->
+	    					<td><apex:outputField value="{!rp.HOURS__c}" /></td>
+	    					<td><apex:outputField value="{!rp.LOCATION__c}" /></td>
+	    					<td><apex:outputField value="{!rp.BILL_AT_0_VALUE__c}" /></td>
+	    					<td><apex:outputField value="{!rp.ECN__c}" /></td>
+	    					<td><apex:outputField value="{!rp.QTY_PICKED__c}" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+
+	    		</table>
+	    	
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Product' || type = 'All',true,false)}">
+	    		<table id="mailProduct" style="width: 100%">
+	    			<colgroup>
+			            <col width="50%"/>
+			            <col width="50%"/>
+			        </colgroup>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ITEM__c.label}<span class="textRed">*</span></td>
+			        	<td>{!$ObjectType.SWO__c.fields.DESCRIPTION__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ITEM__c}"/></td>
+	        			<td><apex:inputField value="{!swo.DESCRIPTION_F__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PART_NUMBER_F__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.ETQ_NUMBER__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.PART_NUMBER_F__c}"/></td>
+	        			<td><apex:inputField value="{!swo.ETQ_NUMBER__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td ><apex:inputField value="{!swo.NON_STANDARD_ITEM__c}" />{!$ObjectType.SWO__c.fields.NON_STANDARD_ITEM__c.label}</td>
+			        	<td>
+			        		{!$ObjectType.SWO__c.fields.INSTRUMENT_MODEL_NUMBER__c.label}
+			        	</td>
+			        </tr>
+
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.QUANTITY__c.label}<span class="textRed">*</span></td>
+			        	<td><apex:inputField value="{!swo.INSTRUMENT_MODEL_NUMBER__c}" /></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.QUANTITY__c}" /></td>
+			        	<td>{!$ObjectType.SWO__c.fields.SERIAL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.MANUFACTURER__c.label}</td>
+			        	<td><apex:inputField value="{!swo.SERIAL__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.MANUFACTURER__c}" /></td>
+			        	<td>{!$ObjectType.SWO__c.fields.MFR_DATE__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:inputField value="{!swo.MFR_DATE__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td>{!$ObjectType.SWO__c.fields.XRF_REGISTRATION_NUMBER__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:inputField value="{!swo.XRF_REGISTRATION_NUMBER__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td>{!$ObjectType.SWO__c.fields.XRF_EXPIRATION_DATE__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:inputField value="{!swo.XRF_EXPIRATION_DATE__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td>{!$ObjectType.SWO__c.fields.XRF_REGISTRATION_NUMBER__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:inputField value="{!swo.CATALOG__c}" /></td>
+			        </tr>
+
+
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Case' || type = 'All',true,false)}">
+	    		<table id="mailCase" style="width: 100%">
+	    			<colgroup>
+			            <col width="50%"/>
+			            <col width="50%"/>
+			        </colgroup>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CASE_NUMBER__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.EMAIL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CASE_NUMBER__c}" ></apex:outputField></td>
+	        			<td><apex:inputField value="{!swo.EMAIL__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.COMPANY__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.ASSIGNED_TO__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.COMPANY__c}" ></apex:outputField></td>
+	        			<td><apex:inputField value="{!swo.ASSIGNED_TO__c}"/></td>
+			        </tr>
+			       <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CONTACT__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TRAN__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CONTACT__c}" ></apex:outputField></td>
+	        			<td><apex:inputField value="{!swo.TRAN__c}"/></td>
+			        </tr>
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Tracking' || type = 'All',true,false)}">
+	    		<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Tracking Turnaround Time</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.INSTRUMENT_RECEIVE_DATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.INSTRUMENT_SHIP_DATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.DAYS_IN_HOUSE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.INSTRUMENT_RECEIVE_DATE__c}"/></td>
+	        			<td><apex:inputField value="{!swo.INSTRUMENT_SHIP_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DAYS_IN_HOUSE__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.DIAGNOSIS_START__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.DIAGNOSIS_END__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.DIAGNOSIS_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.DIAGNOSIS_START__c}"/></td>
+	        			<td><apex:inputField value="{!swo.DIAGNOSIS_END__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DIAGNOSIS_TIME__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PO_RECEIVE_DATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.Quotation_send__c.label}</td>
+			        	<!-- <td>{!$ObjectType.SWO__c.fields.READY_TO_QUOTE__c.label}</td> -->
+			        	<td>{!$ObjectType.SWO__c.fields.TIME_AWAITING_PO__c.label}</td>
+			        </tr>
+			        <tr> 
+	        			<td><apex:inputField value="{!swo.PO_RECEIVE_DATE__c}"/></td>
+	        			<td><apex:inputField value="{!swo.Quotation_send__c}"/></td>
+			        	<!-- <td><apex:outputField value="{!swo.READY_TO_QUOTE__c}"/></td> -->
+	        			<td><apex:outputField value="{!swo.TIME_AWAITING_PO__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REPAIR_START__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.REPAIR_END__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.REPAIR_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.REPAIR_START__c}"/></td>
+	        			<td><apex:inputField value="{!swo.REPAIR_END__c}"/></td>
+	        			<td><apex:outputField value="{!swo.REPAIR_TIME__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CALIBRATION_START__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CALIBRATION_END__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CALIBRATION_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.CALIBRATION_START__c}"/></td>
+	        			<td><apex:inputField value="{!swo.CALIBRATION_END__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CALIBRATION_TIME__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_START__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_end__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.FQC_START__c}"/></td>
+			        	<td><apex:inputField value="{!swo.FQC_end__c}"/></td>
+	        			<td><apex:outputField value="{!swo.FQC_TIME__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<!-- <td>{!$ObjectType.SWO__c.fields.SALES_ORDER_FULFILLED__c.label}</td> -->
+			        	<td>{!$ObjectType.SWO__c.fields.Repair_DateTime__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.DELIVERED_TO_SERVICE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TIME_IN_QUEUE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<!-- <td><apex:inputField value="{!swo.SALES_ORDER_FULFILLED__c}"/></td> -->
+			        	<td><apex:outputField value="{!swo.Repair_DateTime__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DELIVERED_TO_SERVICE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TIME_IN_QUEUE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.Quotation_for_Approval__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.Quotation_Approved__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.READY_FOR_SALES_ORDER__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.Quotation_for_Approval__c}"/></td>
+			        	<td><apex:outputField value="{!swo.Quotation_Approved__c}"/></td>
+	        			<td><apex:outputField value="{!swo.READY_FOR_SALES_ORDER__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.LATE_REASON__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.ESTIMATED_PROMISE_DATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.DOOR_TO_DOOR_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+	        			<td><apex:inputField value="{!swo.LATE_REASON__c}"/></td>
+	        			<td><apex:inputField value="{!swo.ESTIMATED_PROMISE_DATE__c}"/></td>
+	        			<td><apex:inputField value="{!swo.DOOR_TO_DOOR_TIME__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_PROMISE_DATE__c.label}</td>
+			        	<td>&nbsp;</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TIMES_CALIBRATED__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ONSITE_PROMISE_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td><apex:inputField value="{!swo.TIMES_CALIBRATED__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_ARRIVAL_DATE__c.label}</td>
+	        			<td>{!$ObjectType.SWO__c.fields.READY_TO_QUOTE__c.label}</td>
+	        			<td><apex:inputField value="{!swo.FQC_PASS__c}"/>{!$ObjectType.SWO__c.fields.FQC_PASS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ONSITE_ARRIVAL_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.READY_TO_QUOTE__c}"/></td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_COMPLETION_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ONSITE_COMPLETION_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.LATE_REASONS__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.LATE_REASONS__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			    </table>
+			        
+			    <table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="5" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Holds</th>
+	    			</tr>
+			         <tr>
+			        	<td colspan="5"><apex:inputField value="{!swo.HOLDS__c}"/>{!$ObjectType.SWO__c.fields.HOLDS__c.label}</td>
+			        </tr>
+
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_START_1__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_END_1__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_REASON_1__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_NOTE_1__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_PHASE_1__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.HOLD_START_1__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_END_1__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_REASON_1__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_NOTE_1__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_PHASE_1__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_START_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_END_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_REASON_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_NOTE_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_PHASE_2__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.HOLD_START_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_END_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_REASON_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_NOTE_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_PHASE_2__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_START_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_END_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_REASON_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_NOTE_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HOLD_PHASE_3__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.HOLD_START_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_END_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_REASON_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_NOTE_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HOLD_PHASE_3__c}"/></td>
+			        </tr>
+	    		</table>
+
+	    		<!-- <table style="width: 100%">
+	    			<tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Factory</th>
+	    			</tr>
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+
+			       <tr>
+	        			<td><apex:inputField value="{!swo.FACTORY_REPAIR__c}"/>{!$ObjectType.SWO__c.fields.FACTORY_REPAIR__c.label}</td>
+	        			<td>{!$ObjectType.SWO__c.fields.REPAIR_LOCATION__c.label}</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+	        			<td>&nbsp;</td>
+	        			<td><apex:inputField value="{!swo.REPAIR_LOCATION__c}"/></td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.VENDOR_RMA__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CLOSED_DATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.LOGISTICS_SHIPMENT_TYPE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.VENDOR_RMA__c}"/></td>
+	        			<td><apex:inputField value="{!swo.CLOSED_DATE__c}"/></td>
+	        			<td><apex:inputField value="{!swo.LOGISTICS_SHIPMENT_TYPE__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td>{!$ObjectType.SWO__c.fields.LAST_MODIFIED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.BY__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.LATE_REASONS__c.label}</td>
+	        			<td><apex:inputField value="{!swo.LAST_MODIFIED__c}"/></td>
+	        			<td><apex:inputField value="{!swo.BY__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.LATE_REASONS__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.MEMO__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.MEMO__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_CARRIER__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.TO_VENDOR_CARRIER__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_TRACKING__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.TO_VENDOR_TRACKING__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_PROMISE_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ONSITE_PROMISE_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_ARRIVAL_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ONSITE_ARRIVAL_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_COMPLETION_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ONSITE_COMPLETION_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+
+			    </table>
+
+			     <table style="width: 100%">
+	    			<tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Other</th>
+	    			</tr>
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.DATE_CREATED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.ELTON__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_COST__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.DATE_CREATED__c}"/></td>
+	        			<td><apex:inputField value="{!swo.ELTON__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TO_CUSTOMER_COST__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PO_APPROVAL_TIME__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_CARRIER__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SHIPPED_TO_VENDOR_DATE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.PO_APPROVAL_TIME__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TO_CUSTOMER_CARRIER__c}"/></td>
+	        			<td><apex:inputField value="{!swo.SHIPPED_TO_VENDOR_DATE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.TECHNICIAN_COMPLETION_TIME__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_TRACKING__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_PACKING_SLIP__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.TECHNICIAN_COMPLETION_TIME__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TO_CUSTOMER_TRACKING__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TO_VENDOR_PACKING_SLIP__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.DOOR_TO_DOOR_TIME__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_PACKING_SLIP__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_COST__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.DOOR_TO_DOOR_TIME__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TO_CUSTOMER_PACKING_SLIP__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TO_VENDOR_COST__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ECN__c}"/>{!$ObjectType.SWO__c.fields.ECN__c.label}</td>
+			        	<td>&nbsp;</td>
+			        	<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.OT_CLAIM__c.label}</td>
+			        	<td>&nbsp;</td>
+			        	<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.OT_CLAIM__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			    </table> -->
+
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Technical' || type = 'All',true,false)}">
+	    		<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">As Reported by Customer</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REPORTED_PRODUCT_LINE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.AS_REPORTED_CODE_CLASS__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.AS_REPORTED_CODES_ETQ__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.REPORTED_PRODUCT_LINE__c}"/></td>
+	        			<td><apex:inputField value="{!swo.AS_REPORTED_CODE_CLASS__c}"/></td>
+	        			<td><apex:inputField value="{!swo.AS_REPORTED_CODES_ETQ__c}"/></td>
+			        </tr>
+	    		</table>
+
+	    		<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="16.5%"/>
+			            <col width="16.5%"/>
+			            <col width="34%"/>
+			           
+			        </colgroup>
+			        <tr>
+	    				<th colspan="4" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Technical Info</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.SPECIAL_CUSTOMER_REQUIREMENTS__c.label}</td>
+			        	<td colspan="2">{!$ObjectType.SWO__c.fields.ASSIGNED_TO_TECHNICIAN_DATE__c.label}</td>
+			        	<td >{!$ObjectType.SWO__c.fields.FAILURE_SYMPTOM__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.SPECIAL_CUSTOMER_REQUIREMENTS__c}"/></td>
+	        			<td colspan="2"><apex:inputField value="{!swo.ASSIGNED_TO_TECHNICIAN_DATE__c}"/></td>
+	        			<td ><apex:inputField value="{!swo.FAILURE_SYMPTOM__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REQUIREMENT_DETAILS__c.label}</td>
+			        	<td colspan="2">{!$ObjectType.SWO__c.fields.TECHNICIAN_COMPLETION_DATE__c.label}</td>
+			        	<td ><apex:inputField value="{!swo.ROOT_CAUSE__c}"/>{!$ObjectType.SWO__c.fields.ROOT_CAUSE__c.label}<apex:inputField value="{!swo.NCM__c}"/>{!$ObjectType.SWO__c.fields.NCM__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td rowspan="4"><apex:inputField value="{!swo.REQUIREMENT_DETAILS__c}" style="height: 100px;width: 80%" /></td>
+			        	<td colspan="2"><apex:inputField value="{!swo.TECHNICIAN_COMPLETION_DATE__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.FAILURE_SOURCE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td colspan="2">{!$ObjectType.SWO__c.fields.GOVERNMENT_INSPECTION_DATE__c.label}</td>
+			        	<td><apex:inputField value="{!swo.FAILURE_SOURCE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td colspan="2"><apex:inputField value="{!swo.GOVERNMENT_INSPECTION_DATE__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.FAILURE_SOURCE_DETAIL__c.label}</td>
+			        </tr>
+			        <!-- 绗竷琛� -->
+			        <tr>Part_Hold_Date__c
+			        	<td>{!$ObjectType.SWO__c.fields.Part_Hold_Date__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.In_Queue_Date__c.label}</td>
+			        	<td><apex:inputField value="{!swo.FAILURE_SOURCE_DETAIL__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REQUIREMENTS_FULFILLED_ON__c.label}</td>
+			        	<td><apex:outputField value="{!swo.Part_Hold_Date__c}"/></td>
+			        	<td><apex:outputField value="{!swo.In_Queue_Date__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.ROOT_CAUSE_FOR_FAILURE_S__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.REQUIREMENTS_FULFILLED_ON__c}"/></td>
+			        	<td colspan="2">{!$ObjectType.SWO__c.fields.Ready_for_Quote__c.label}</td>
+			        	<td><apex:inputField value="{!swo.ROOT_CAUSE_FOR_FAILURE_S__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+			        	<td colspan="2"><apex:outputField value="{!swo.Ready_for_Quote__c}"/></td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Parts_request_for_diagnosis_date__c.label}</td>
+			        	<td class="hand" colspan="2">{!$ObjectType.SWO__c.fields.Parts_ready_for_diagnosis_date__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Ready_to_ship_date__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.Parts_request_for_diagnosis_date__c}"/></td>
+			        	<td colspan="2"><apex:outputField value="{!swo.Parts_ready_for_diagnosis_date__c}"/></td>
+			        	<td><apex:outputField value="{!swo.Ready_to_ship_date__c}"/></td>
+			        </tr>
+	    		</table>
+
+	    		<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="4" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">As Analyzed by Service</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ANALYZED_PRODUCT_LINE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.AS_ANALYZED_CODE_CLASS__c.label}</td>
+			        	<td >{!$ObjectType.SWO__c.fields.AS_ANALYZED_CODES_ETQ__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ANALYZED_PRODUCT_LINE__c}"/></td>
+			        	<td><apex:inputField value="{!swo.AS_ANALYZED_CODE_CLASS__c}"/></td>
+			        	<td ><apex:inputField value="{!swo.AS_ANALYZED_CODES_ETQ__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REPAIR_PART_PRODUCT_LINE__c.label}</td>
+			        	<td >{!$ObjectType.SWO__c.fields.PART_CODE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.REPAIR_PART_PRODUCT_LINE__c}"/></td>
+			        	<td ><apex:inputField value="{!swo.PART_CODE__c}"/></td>
+			        </tr>
+			    </table>
+
+			     <table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr style="width: 98%">
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Repeat Repair</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Factory Support</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Service Notes</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REPEAT_REPAIR_REASON_CODE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.FACTORY_ASSIGNED_TO__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SYMPTOM_NOTES__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.REPEAT_REPAIR_REASON_CODE__c}"/></td>
+			        	<td><apex:inputField value="{!swo.FACTORY_ASSIGNED_TO__c}"/></td>
+			        	<td rowspan="3"><apex:inputField style="height: 100px;width: 80%" value="{!swo.SYMPTOM_NOTES__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField id="REPEAT" value="{!swo.REPEAT_REPAIR__c}" onclick="clickRepeat()"/>{!$ObjectType.SWO__c.fields.REPEAT_REPAIR__c.label}</td>
+			        	<td >{!$ObjectType.SWO__c.fields.FACTORY_ASSIGNED_TO_DATE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PREVIOUS_REPAIR_SWO__c.label}</td>
+			        	<td ><apex:inputField value="{!swo.FACTORY_ASSIGNED_TO_DATE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.PREVIOUS_REPAIR_SWO__c}"/></td>
+			        	<td >{!$ObjectType.SWO__c.fields.FACTORY_RETURNED_DATE__c.label}</td>
+			        	<td >{!$ObjectType.SWO__c.fields.DIAGNOSIS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PREVIOUS_COMPLETED_DATE__c.label}</td>
+			        	<!-- <td>{!$ObjectType.SWO__c.fields.REPEAT_REPAIR_ORIGINAL_NOTES__c.label}<span id="NOTESSPAN" class="textRed">*</span></td> -->
+			        	<td ><apex:inputField value="{!swo.FACTORY_RETURNED_DATE__c}"/></td>
+			        	<td rowspan="5"><apex:inputField style="height: 100px;width: 80%" value="{!swo.DIAGNOSIS__c}"/></td>
+
+			        </tr>
+			         <tr>
+			         	<td><apex:inputField value="{!swo.PREVIOUS_COMPLETED_DATE__c}"/></td>
+			        	<!-- <td rowspan="4"><apex:inputField style="height: 100px;width: 80%" value="{!swo.REPEAT_REPAIR_ORIGINAL_NOTES__c}"/></td> -->
+			        	<td >{!$ObjectType.SWO__c.fields.MICRO_CODE_CLASS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.REPEAT_REPAIR_ORIGINAL_NOTES__c.label}<span id="NOTESSPAN" class="textRed">*</span></td>
+			        	<td><apex:inputField value="{!swo.MICRO_CODE_CLASS__c}"/></td>
+			        </tr>
+			         <tr>
+			         	<td rowspan="2"><apex:inputField style="height: 100px;width: 80%" value="{!swo.REPEAT_REPAIR_ORIGINAL_NOTES__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.MICRO_FAILURE_DESCRIPTION__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.MICRO_FAILURE_DESCRIPTION__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.Problems_fixed_by_initial_solutions__c}"/>{!$ObjectType.SWO__c.fields.Problems_fixed_by_initial_solutions__c.label}</td>
+			        	<td></td>
+			        	<td>{!$ObjectType.SWO__c.fields.SERVICES_PERFORMED__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.reason_for_the_2nd_field_service__c.label}</td>
+			        	<td></td>
+			        	<td rowspan="2"><apex:inputField style="height: 100px;width: 80%" value="{!swo.SERVICES_PERFORMED__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField style="height: 100px;width: 80%" value="{!swo.reason_for_the_2nd_field_service__c}"/></td>
+			        	<td></td>
+			        	<td></td>
+			        </tr>
+
+			    </table>
+
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Estimation' || type = 'All',true,false)}">
+	    		<table id="mailEstimation" style="width: 100%">
+	    			<colgroup>
+			            <col width="50%"/>
+			            <col width="50%"/>
+			        </colgroup>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ESTIMATED_MATERIAL_COST__c.label}</td>
+			        	<td><apex:inputField value="{!swo.WORK_IS_COMPLETE__c}"/>{!$ObjectType.SWO__c.fields.WORK_IS_COMPLETE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ESTIMATED_MATERIAL_COST__c}"/></td>
+	        			<td>{!$ObjectType.SWO__c.fields.ESTIMATED_TOTAL_COST__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.MATERIAL_MARK_UP_RATE__c.label}</td>
+			        	<td><apex:inputField value="{!swo.ESTIMATED_TOTAL_COST__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.MATERIAL_MARK_UP_RATE__c}"/></td>
+	        			<td>{!$ObjectType.SWO__c.fields.ESTIMATED_TOTAL_PRICE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.USE_ESTIMATED_MATERIAL__c}"/>{!$ObjectType.SWO__c.fields.USE_ESTIMATED_MATERIAL__c.label}</td>
+			        	<td><apex:inputField value="{!swo.ESTIMATED_TOTAL_PRICE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ESTIMATED_LABOUR_HOURS__c.label}<!-- <span class="textRed">*</span> --></td>
+			        	<td>{!$ObjectType.SWO__c.fields.CURRENCY__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ESTIMATED_LABOUR_HOURS__c}"/></td>
+	        			<td><apex:inputField value="{!swo.CURRENCY__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.LABOUR_RATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.PRICE_LEVEL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.LABOUR_RATE__c}"/></td>
+	        			<td><apex:inputField value="{!swo.PRICE_LEVEL__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.USE_ESTIMATED_LABOUR__c}"/>{!$ObjectType.SWO__c.fields.USE_ESTIMATED_LABOUR__c.label}</td>
+			        	<td></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ESTIMATED_EXPENSES_COSTS__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ESTIMATED_EXPENSES_COSTS__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.EXPENSE_MARK_UP_RATE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.EXPENSE_MARK_UP_RATE__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.USE_ESTIMATED_EXPENSES__c}"/>{!$ObjectType.SWO__c.fields.USE_ESTIMATED_EXPENSES__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'General' || type = 'All',true,false)}">
+	    		<apex:commandButton value="Attach" onclick="uploadFileJS();return false;"></apex:commandButton>
+					
+			   
+		    	<table class="tableCss" style="border:1px solid #000000;width: 80%">	
+		    		<tr style="text-align:center;">
+		    			<th style="text-align:center;width: 33%;">File Name</th>
+		    			<th style="text-align:center;width: 33%;">Upload Time</th>
+		    			<th style="text-align:center;width: 33%;">File Size</th>
+		    		</tr>
+		    		<apex:repeat id="attachmentList" value="{!attachmentList}" var="attachment">
+		    			<tr style="text-align:center; vertical-align: middle;">
+		    				<!-- <td><input value="{!attachment.Name}" readonly="readonly" style="border:none;"/></td> -->
+		    				<td><apex:outputLink value="/{!attachment.Id}">{!attachment.Name}</apex:outputLink></td>
+		    				<td><apex:inputField value="{!attachment.CreatedDate}"/></td>
+		    				<td><apex:inputField value="{!attachment.BodyLength}"/></td>
+		    			</tr>
+		    		</apex:repeat>
+		    	</table>
+
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Outgoing' || type = 'All',true,false)}">
+		    	<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">New Section</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.OUTGOING_INSPECTION_COMPLETED_BY__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.HAVE_ALL_ACCESSORIES_BEEN_INCLUDED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.NOTES__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.OUTGOING_INSPECTION_COMPLETED_BY__c}"/></td>
+	        			<td><apex:inputField value="{!swo.HAVE_ALL_ACCESSORIES_BEEN_INCLUDED__c}"/></td>
+	        			<td><apex:inputField value="{!swo.NOTES__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.UNIT_POWERS_UP__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TRIGGER_LOCK_ONE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.UNIT_POWERS_UP__c}"/></td>
+	        			<td><apex:inputField value="{!swo.TRIGGER_LOCK_ONE__c}"/></td>
+	        			<td></td>
+			        </tr>
+
+			        <tr>
+			        	<td><apex:inputField value="{!swo.BATTERY_INCLUDED1__c}"/>{!$ObjectType.SWO__c.fields.BATTERY_INCLUDED1__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.DEAD_MAN_TRIGGER_ONE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ANY_VISIBLE_DAMAGE__c.label}</td>
+	        			<td><apex:inputField value="{!swo.DEAD_MAN_TRIGGER_ONE__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.ANY_VISIBLE_DAMAGE__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.SERIAL_MATCHES_SO__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CAL_CERT_AND_STICKER_VERIFIED_CORRECT__c.label}</td>
+	        			<td><apex:inputField value="{!swo.SERIAL_MATCHES_SO__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.CAL_CERT_AND_STICKER_VERIFIED_CORRECT__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.VERIFY_SOFTWARE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.KEYPAD_FUNCTIONS_CORRECTLY__c.label}</td>
+	        			<td><apex:inputField value="{!swo.VERIFY_SOFTWARE__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.KEYPAD_FUNCTIONS_CORRECTLY__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.RADIATION_SURVEYPERFORMED_ATTACHED__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CUSTOM_SETUPS_INCLUDED__c.label}</td>
+	        			<td><apex:inputField value="{!swo.RADIATION_SURVEYPERFORMED_ATTACHED__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.CUSTOM_SETUPS_INCLUDED__c}"/></td>
+			        	<td></td>
+			        	<td></td>
+			        </tr>
+
+				</table>
+
+				<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Legacy Fields</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CAL_CERT_AND_STICKER_INCLUDED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.POWER_UP_UNIT_DISPLAY_OK__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_RAD_SURVEY_PERFORMED_ATTACHED__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.CAL_CERT_AND_STICKER_INCLUDED__c}"/></td>
+	        			<td><apex:inputField value="{!swo.POWER_UP_UNIT_DISPLAY_OK__c}"/></td>
+	        			<td><apex:inputField value="{!swo.FQC_RAD_SURVEY_PERFORMED_ATTACHED__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.POWER_LEVEL__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.PASSED_COSMETIC_CHECK__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.POWER_LEVEL__c}"/></td>
+	        			<td><apex:inputField value="{!swo.PASSED_COSMETIC_CHECK__c}"/></td>
+	        			<td></td>
+			        </tr>
+			    </table>
+			</apex:outputPanel>
+
+			<apex:outputPanel rendered="{!IF(type = 'Incoming' || type = 'All',true,false)}">
+		    	<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">New Section</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.INCOMING_INSPECTION_COMPLETED_BY__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.BATTERY_MORE_THAN_3_YRS_OLD__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.NOTES__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.INCOMING_INSPECTION_COMPLETED_BY__c}"/></td>
+	        			<td><apex:inputField value="{!swo.BATTERY_MORE_THAN_3_YRS_OLD__c}"/></td>
+	        			<td><apex:inputField value="{!swo.NOTES__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.DOES_UNIT_POWER_UP_PROPERLY__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.VERIFY_SOFTWARE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.DOES_UNIT_POWER_UP_PROPERLY__c}"/></td>
+	        			<td><apex:inputField value="{!swo.VERIFY_SOFTWARE__c}"/></td>
+	        			<td></td>
+			        </tr>
+
+			        <tr>
+			        	<td><apex:inputField value="{!swo.BATTERY_INCLUDED__c}"/>{!$ObjectType.SWO__c.fields.BATTERY_INCLUDED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TRIGGER_LOCK__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ARRIVED_DAMAGED__c.label}</td>
+	        			<td><apex:inputField value="{!swo.TRIGGER_LOCK__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.ARRIVED_DAMAGED__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.DEAD_MAN_TRIGGER__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CONFIRMED_RECEIPT_WITH_CUSTOMER__c.label}</td>
+	        			<td><apex:inputField value="{!swo.DEAD_MAN_TRIGGER__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.CONFIRMED_RECEIPT_WITH_CUSTOMER__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.XRF_TUBE_HRS__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.CUSTOM_SETUPS_PRESENT__c.label}</td>
+	        			<td><apex:inputField value="{!swo.XRF_TUBE_HRS__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:inputField value="{!swo.CUSTOM_SETUPS_PRESENT__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.LOGIN__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.PASS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+			        	<td><apex:inputField value="{!swo.LOGIN__c}"/></td>
+			        	<td><apex:inputField value="{!swo.PASS__c}"/></td>
+			        </tr>
+				</table>
+
+				<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Legacy Fields</th>
+	    			</tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PASSED_COSMETIC_CHECK__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.RETURN_DEFECTIVE_PARTS__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SERIAL_MATCHES_PO__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.PASSED_COSMETIC_CHECK__c}"/></td>
+	        			<td><apex:inputField value="{!swo.RETURN_DEFECTIVE_PARTS__c}"/></td>
+	        			<td><apex:inputField value="{!swo.SERIAL_MATCHES_PO__c}"/></td>
+			        </tr>
+			    </table>
+			</apex:outputPanel>
+
+			<apex:outputPanel rendered="{!IF(type = 'Fault' || type = 'All',true,false)}">
+		    	<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="25%"/>
+			            <col width="25%"/>
+			            <col width="25%"/>
+			            <col width="25%"/>
+			        </colgroup>
+			        <tr>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Initial Customer Complaint</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Fault Analysis 2</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Fault Analysis 3</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Cal/QC First Pass Success/Fail Info</th>
+	    			</tr>
+	    			<tr>
+			        	<td>{!$ObjectType.SWO__c.fields.SYMPTOMS_1__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SYMPTOMS_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SYMPTOMS_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CAL_FP_SUCCESS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.SYMPTOMS_1__c}"/></td>
+	        			<td><apex:inputField value="{!swo.SYMPTOMS_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.SYMPTOMS_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.CAL_FP_SUCCESS__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.REPRODUCED_IN_SERVICE__c}"/>{!$ObjectType.SWO__c.fields.REPRODUCED_IN_SERVICE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.FAILURE_REASONS_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.FAILURE_REASONS_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CAL_FAIL_REASON__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.FAILURE_REASONS_1__c.label}</td>
+	        			<td><apex:inputField value="{!swo.FAILURE_REASONS_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.FAILURE_REASONS_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.CAL_FAIL_REASON__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.FAILURE_REASONS_1__c}"/></td>
+			        	<td>{!$ObjectType.SWO__c.fields.SECONDARY_FAILURE_REASONS_2__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SECONDARY_FAILURE_REASONS_3__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CAL_SOLUTION__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.SECONDARY_FAILURE_REASONS_1__c.label}</td>
+	        			<td><apex:inputField value="{!swo.SECONDARY_FAILURE_REASONS_2__c}"/></td>
+	        			<td><apex:inputField value="{!swo.SECONDARY_FAILURE_REASONS_3__c}"/></td>
+	        			<td><apex:inputField value="{!swo.CAL_SOLUTION__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:inputField value="{!swo.SECONDARY_FAILURE_REASONS_1__c}"/></td>
+			        	<td></td>
+			        	<td></td>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_FP_SUCCESS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+	        			<td></td>
+	        			<td></td>
+	        			<td><apex:inputField value="{!swo.FQC_FP_SUCCESS__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td></td>
+			        	<td></td>
+			        	<td></td>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_FAIL_REASON__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+	        			<td></td>
+	        			<td></td>
+	        			<td><apex:inputField value="{!swo.FQC_FAIL_REASON__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+			        	<td></td>
+			        	<td></td>
+			        	<td>{!$ObjectType.SWO__c.fields.FQC_SOLUTIONS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+	        			<td></td>
+	        			<td></td>
+	        			<td><apex:inputField value="{!swo.FQC_SOLUTIONS__c}"/></td>
+			        </tr>
+
+			    </table>
+			</apex:outputPanel>
+
+			<apex:outputPanel rendered="{!IF(type = 'Diagnosis' || type = 'All',true,false)}">
+				<br/>
+	    		<!-- <apex:commandButton id="Adddiagnosis" onclick="SWO_Id();" value="ADD" action="{!addDiagnosisInfo}" reRender="table" style="width: 5%" /> -->
+                <apex:commandButton id="openDiagnosisPart" value="Diagnosis Part" onclick="SWO_Id();openDiagnosisPart();return false;" style="width: 8%"/>
+	    		<br/>
+	    		<table id="diagnosisTable" style="width: 100%">
+	    			<colgroup>
+                        <col width="4%"/>
+			            <col width="6%"/>
+			            <col width="9%"/>
+			            <col width="9%"/>
+			            <col width="9%"/>
+			            <col width="6%"/>
+			            <col width="6%"/>
+			            <col width="9%"/>
+			            <col width="9%"/>
+			            <col width="7%"/>
+			            <col width="7%"/>
+			            <col width="9%"/>
+			            <col width="8%"/>
+			        </colgroup>
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+                        <th>EDIT</th>
+	    				<th>ITEM</th> 
+	    				<th>PART NUMBER</th>
+	    				<th>INST. SERIAL#</th>
+	    				<th>DESCRIPTION</th>
+	    				<th>QUANTITY</th>
+	    				<th>STATUS</th>
+	    				<th>HOLD REASON</th>
+	    				<th>REMARK</th>
+	    				<th>DELIVERED</th>
+	    				<th>RETURNED</th>
+	    				<th>Delivered date.</th>
+	    				<th>RETURN DATE</th>
+	    			</tr>
+	    			<apex:repeat value="{!diagnosisList}" var="dia" id="diagnosisList">
+	    				<tr>
+	    					<!-- <td><apex:inputField value="{!dia.di.ITEM__c}" id="Name"  onclick="searchProduct('{!dia.lineNumber}',this.value)"/><apex:inputText id="productId" value="{!dia.di.Product__c}" style="display: none;"/></td> -->
+                            <td>
+                                <apex:outputLink value="/apex/NewDiagnosisPart?id={!dia.di.Id}" target="LINK_{!dia.di.Id}}" >EDIT</apex:outputLink>
+                            </td>
+                            <td><apex:outputField value="{!dia.di.Product__r.ProductCode}" id="Name"  /></td>
+	    					<td><apex:outputField value="{!dia.di.Product__r.Product_ECCode__c}" id="partNumber"/></td>
+	    					<td><apex:outputField value="{!dia.di.INST_SERIAL__c}" id="instSerial"/></td>
+	    					<td><apex:outputField value="{!dia.di.Product__r.Description}" id="description"/></td>
+	    					<td><apex:outputField value="{!dia.di.QUANTITY__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.STATUS__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.HOLD_REASON__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.REMARK__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.DELIVERED__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.RETURNED__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.DeliveredDate__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.RETURN_DATE__c}" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+	    		</table>
+			</apex:outputPanel>
+	    	
+	    </apex:outputPanel>
+		
+
+
+
+
+		<br/>
+		<br/>
+		<br/>
+		<br/>
+		<br/>
+		<!-- <apex:commandButton action="{!save}" onclick="blockme();" value="Save" oncomplete="isOk();unblockUI();" reRender="Page,mainForm" style="width: 5%;"/> -->
+		<apex:commandButton onclick="blockme();" value="Save" action="{!save}" style="width: 5%;"/>
+
+	</apex:form>
+	
+	<br/>
+	<br/>
+	<br/>
+	<br/>
+	<br/>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SWOPage.page-meta.xml b/scr/pages/SWOPage.page-meta.xml
new file mode 100644
index 0000000..bae1f9f
--- /dev/null
+++ b/scr/pages/SWOPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SWOPage</label>
+</ApexPage>
diff --git a/scr/pages/SWOPageRead.page b/scr/pages/SWOPageRead.page
new file mode 100644
index 0000000..d076824
--- /dev/null
+++ b/scr/pages/SWOPageRead.page
@@ -0,0 +1,1732 @@
+<apex:page standardController="SWO__c" extensions="SWOController" showChat="false" showHeader="true" sidebar="false" action="{!init}" id="Page">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+
+	<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+	<script>
+		j$(document).ready(function() {
+			var type = j$(escapeVfId("type")).value();
+			clickColorChange(type);
+		});
+    	function openPDF(){
+    		//alert('11111');
+    		var baseUrl = j$(escapeVfId("baseUrl")).value();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		/*alert(baseUrl);
+    		alert(swoId);*/
+
+    		window.open(baseUrl + '/apex/SendEmail?type=SWO&typeid=' + swoId,'_blank').location;
+    		//window.close();
+
+    	} 
+    	function searchProduct(i,str){
+           var baseUrl = '{!baseUrl}';
+            openPopup(baseUrl + '/apex/SWOSearchProduct?lineno=' + i + '&val=' + encodeURIComponent(str), 'pselect', 950, 450, 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+         function getLastLineNoNext(doc) {
+            var hasRecordFlg = false;
+            var lastLineNo = 0;
+            for(var i=99; i>=0; i--){
+                if (j$(escapeVfId('Page:mainForm:diagnosisList:' + i + ':Name')).value() != ''){
+                    if (!hasRecordFlg) {
+                        lastLineNo = i;
+                    }
+                    hasRecordFlg = true;
+                }
+                if (hasRecordFlg == true) {
+                    if (j$(escapeVfId('Page:mainForm:diagnosisList:' + i + ':Name')).value() == ''){
+                        var moveCheckbox = true;
+                        //deletelist(i, doc, moveCheckbox);
+                        lastLineNo = i;
+                    }
+                }
+            }
+            if (hasRecordFlg) {
+                lastLineNo = lastLineNo + 1;
+            }
+            return lastLineNo;
+        }
+
+    	function openQuote(){
+
+    		var baseUrl = j$(escapeVfId("baseUrl")).value();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		/*alert(baseUrl);
+    		alert(swoId);*/
+    		window.open(baseUrl + '/apex/NEWCreateSWOQuote?swoId=' + swoId);
+    	}
+
+    	function openRepair(id){
+
+    		/*var baseUrl = j$(escapeVfId("baseUrl")).value();
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		var name = j$(escapeVfId("Name")).value();
+    		alert(baseUrl);
+    		alert(swoId);
+    		window.open(baseUrl + '/a0n/e?CF00N1e000000m7My= '+name+'&CF00N1e000000m7My_lkid=' + swoId + '&retURL=%2F'+swoId);*/
+    		var swoId = j$(escapeVfId("swoid")).value();
+    		var baseUrl = j$(escapeVfId("baseUrl")).value();
+            //var repairId = j$(escapeVfId("repairId")).value();
+            window.open(baseUrl + '/apex/NewRepairParts?swoId='+swoId+'&id='+id,'pselect', 'width=900,height=500,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+    	}
+
+        function openDiagnosisPart(){
+            
+            var swoId = j$(escapeVfId("swoid")).value();
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            window.open(baseUrl + '/apex/NewDiagnosisPart?swoId='+swoId,'pselect', 'width=900,height=500,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+
+    	function repairReturnJS(repairPartId,swoId){
+    		repairReturn(swoid);
+    	}
+
+    	function mastDataJS(){
+    		mustData();
+    	}
+    	function isOk(){
+    		//alert('淇濆瓨濂戒簡');
+    		//unblockUI();
+    		//alert("111");
+    		var errorMessage = j$(escapeVfId("errorMessage")).value();
+    		alert(errorMessage);
+    		console.log("errorMessage:"+errorMessage);
+    	}
+
+    	function clickColorChange(str){
+    		j$(escapeVfId("titleProduct")).attr("class","title1");
+    		j$(escapeVfId("titleCase")).attr("class","title1");
+    		j$(escapeVfId("titlemail")).attr("class","title1");
+    		j$(escapeVfId("titleTracking")).attr("class","title1");
+    		j$(escapeVfId("titleTechnical")).attr("class","title1");
+    		j$(escapeVfId("titleEstimation")).attr("class","title1");
+    		j$(escapeVfId("titleRepair")).attr("class","title1");
+    		j$(escapeVfId("titleQuotes")).attr("class","title1");
+    		j$(escapeVfId("titleGeneral")).attr("class","title1");
+    		j$(escapeVfId("titleIncoming")).attr("class","title1");
+    		j$(escapeVfId("titleOutgoing")).attr("class","title1");
+    		j$(escapeVfId("titleFault")).attr("class","title1");
+    		j$(escapeVfId("titleDiagnosis")).attr("class","title1");
+
+    		j$(escapeVfId("title"+str)).attr("class","title2");
+    	}
+
+        function SWO_Id(){
+            IS_OPEN = true;
+            var swoId = j$(escapeVfId("swoid")).value();
+            if(swoId == "" || swoId == null){
+                alert("璇峰厛淇濆瓨SWO");
+                IS_OPEN = false;
+            }
+        }
+	</script>
+
+	<style type="text/css"> 
+		.Page{
+			margin-left: 20px;
+			margin-right: 20px;
+		}
+
+		.title{
+    		height: 30px;
+    		background-color: #DFE6F0;
+    		font-size: 15px;
+    		color:#607799;
+    		font-weight: bold;
+    	}
+    	.title1{
+    		text-align:center;
+    		height: 30px;
+    		background-color: #607799;
+    		font-size: 15px;
+    		color:#FFFFFF;
+    		font-weight: bold;
+    	}
+    	.title1:hover{
+    		text-align:center;
+    		height: 28px;
+    		background-color: #DFE6F0;
+    		font-size: 15px;
+    		color:#00FFFF;
+    		font-weight: bold;
+    		padding: 0px 2px; 
+    	}
+    	.row:hover{
+    		background-color: #DFE6F0;
+    	}
+    	.title2{
+    		text-align:center;
+    		height: 28px;
+    		background-color: #DFE6F0;
+    		font-size: 15px;
+    		color:#00FFFF;
+    		font-weight: bold;
+    		padding: 0px 2px; 
+    	}
+
+    	.hand{
+    		font-weight:bold;
+    	}
+
+
+	</style>
+	<apex:form id="mainForm" style="width: 95%; margin-left: 30px;">
+		<apex:actionFunction name="mustData" action="{!mustData}" reRender="mainForm" oncomplete="isOk();"></apex:actionFunction>
+		<apex:actionFunction name="repairReturn" action="{!init}" reRender="mainForm" >
+			<!-- <apex:param name="type" assignTo="{!type}" value="Repair" /> -->
+			<apex:param name="swoid" assignTo="{!swoid}" value="" />
+		</apex:actionFunction>
+		<input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+		<input type="hidden" id="swoid" value="{!swoid}"/>
+		<input type="hidden" id="type" value="{!type}"/>
+		<input type="hidden" id="Name" value="{!swo.Name}"/>
+		<input type="hidden" id="errorMessage" value="{!errorMessageInfo}" />
+		<br/>
+		<h3 id="h3" style="font-size: 24px;">Service Work Order</h3><br/>
+		<h3 style="font-size: 24px;">{!swo.Name}</h3>
+		<br/>
+		<br/>
+
+		<apex:commandButton action="{!edit}"  value="EDIT" style="width: 5%;"/> 
+		<table style="width: 100%;">
+			<colgroup>
+	            <col width="16%"/>
+	            <col width="17%"/>
+	            <col width="33%"/>
+	            <col width="17%"/>
+	            <col width="17%"/>
+	        </colgroup>
+
+	        <tr>
+	        	<th colspan="5" class="title">SWO Basic Information</th>
+	        </tr>
+	        <tr>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.Name.label}</td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.ETQ_NUMBER__c.label}</td>
+	        	<td class="hand"><apex:outputField value="{!swo.EPCI_REQUIRED_FROM_CUSTOMER__c}" />{!$ObjectType.SWO__c.fields.EPCI_REQUIRED_FROM_CUSTOMER__c.label}</td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.CUSTOMER_PO__c.label}</td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.QUOTE_LEVEL__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td><apex:outputField value="{!swo.Name}"/></td>
+	        	<td><apex:outputField value="{!swo.ETQ_NUMBER__c}"/></td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.SWO_STATUS__c.label}</td>
+	        	<td><apex:outputField value="{!swo.CUSTOMER_PO__c}"/></td>
+	        	<td><apex:outputField value="{!swo.QUOTE_LEVEL__c}"/></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.SUBJECT__c.label}</td>
+	        	<td><apex:outputField value="{!swo.SWO_STATUS__c}"/></td>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.CLIN__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.SUBJECT__c}"/></td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.SWO_STAGE__c.label}</td>
+	        	<td colspan="2"><apex:outputField value="{!swo.CLIN__c}"/></td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.SHIP_TO_LOCATION__c.label}</td>
+	        	<td><apex:outputField value="{!swo.SWO_STAGE__c}"/></td>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.ASSIGNEDTO__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.SHIP_TO_LOCATION__c}"/></td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.TYPE__c.label}</td>
+	        	<td colspan="2"><apex:outputField value="{!swo.ASSIGNEDTO__c}" style="width: 50%;"/></td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.OFFICE__c.label}</td>
+	        	<td><apex:outputField value="{!swo.TYPE__c}"/></td>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.CONTACT_NAME_HIDDEN__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.OFFICE__c}"/></td>
+	        	<td></td>
+	        	<td colspan="2"><apex:outputField value="{!swo.CONTACT_NAME_HIDDEN__c}"/></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.SWO_PRIORITY__c.label}</td>
+	        	<td></td>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.SO_NUMBER__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.SWO_PRIORITY__c}"/></td>
+	        	<td></td>
+	        	<td colspan="2"><apex:outputField value="{!swo.SO_NUMBER__c}"/></td>
+	        </tr>
+	        
+		</table>
+
+		<table style="width: 100%;">
+			<colgroup>
+	            <col width="33%"/>
+	            <col width="33%"/>
+	            <col width="34%"/>
+	        </colgroup>
+
+	        <tr>
+	        	<td colspan="3" class="title">ETQ</td>
+	        </tr>
+
+	        <tr>
+	        	<td  class="hand">{!$ObjectType.SWO__c.fields.MDR_STATEMENT__c.label}</td>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.PAE_Q_2__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td ><apex:outputField value="{!swo.MDR_STATEMENT__c}"/></td>
+	        	<td colspan="2"><apex:outputField value="{!swo.PAE_Q_2__c}"/></td>
+	        </tr>
+	    </table>
+
+	    <table style="width: 100%;border-collapse: collapse; " >
+			<colgroup>
+	            <col width="16%"/>
+	            <col width="17%"/>
+	            <col width="33%"/>
+	            <col width="17%"/>
+	            <col width="17%"/>
+	        </colgroup>
+
+	        <tr class="title">
+	        	<td colspan="2" class="title">Repair Loaner</td>
+	        	<td class="title">Service Unit</td>
+	        	<td colspan="2" class="title">SWO Reason/Warranty Information</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.REPAIR_LOANER_SENT__c}" />{!$ObjectType.SWO__c.fields.REPAIR_LOANER_SENT__c.label}</td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.DEPARTMENT__c.label}</td>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.REASON__c.label}</td>
+	        </tr>
+
+	         <tr>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.REPAIR_LOANER_NOT_REQUIRED__c}" />{!$ObjectType.SWO__c.fields.REPAIR_LOANER_NOT_REQUIRED__c.label}</td>
+	        	
+	        	<td><apex:outputField value="{!swo.DEPARTMENT__c}" /></td>
+	        	<td colspan="2"><apex:outputField value="{!swo.REASON__c}" /></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.REPAIR_LOANER_NOT_PROVIDED__c}" />{!$ObjectType.SWO__c.fields.REPAIR_LOANER_NOT_PROVIDED__c.label}</td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.PRODUCT_TYPE__c.label}</td>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.UNDER_CONTRACT__c}"/>{!$ObjectType.SWO__c.fields.UNDER_CONTRACT__c.label}</td>
+	        </tr>
+	         <tr>
+	        	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.INSTRUMENT_MODEL__c.label}</td>
+	        	
+	        	<td><apex:outputField value="{!swo.PRODUCT_TYPE__c}"/></td>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.FACTORY_WARRANTY__c}"/>{!$ObjectType.SWO__c.fields.FACTORY_WARRANTY__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.INSTRUMENT_MODEL__c}"/></td>
+	        	
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.CV_REPAIR_TYPE__c.label}</td>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.OAI_WARRANTY__c}"/>{!$ObjectType.SWO__c.fields.OAI_WARRANTY__c.label}</td>
+	        </tr>
+	         <tr>
+	         	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.LOANER_SERIAL__c.label}</td>
+	        	
+	        	<td><apex:outputField value="{!swo.CV_REPAIR_TYPE__c}"/></td>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.EXTENDED_WARRANTY__c}"/>{!$ObjectType.SWO__c.fields.EXTENDED_WARRANTY__c.label}</td>
+	        </tr>
+
+	         <tr>
+	         	<td colspan="2"><apex:outputField value="{!swo.LOANER_SERIAL__c}"/></td>
+	        	
+	        	<td></td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.CLAIM__c.label}</td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.PREV_CLAIMS__c.label}</td>
+	        </tr>
+	         <tr>
+	         	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.LOANER_SHIPPED_DATE__c.label}</td>
+	        	
+	        	<td></td>
+	        	<td><apex:outputField value="{!swo.CLAIM__c}"/></td>
+	        	<td><apex:outputField value="{!swo.PREV_CLAIMS__c}"/></td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.LOANER_SHIPPED_DATE__c}"/></td>
+	        	
+	        	<td></td>
+	        	<td colspan="2" class="hand"><apex:outputField value="{!swo.TRUE_PROTECTION_PLAN__c}"/>{!$ObjectType.SWO__c.fields.TRUE_PROTECTION_PLAN__c.label}</td>
+	        </tr>
+	         <tr>
+	         	<td colspan="2" class="hand">{!$ObjectType.SWO__c.fields.LOANER_RECEIVED_DATE__c.label}</td>
+	        	
+	        	<td></td>
+	        	<td></td>
+	        	<td class="hand">{!$ObjectType.SWO__c.fields.PER__c.label}</td>
+	        </tr>
+
+	        <tr>
+	        	<td colspan="2"><apex:outputField value="{!swo.LOANER_RECEIVED_DATE__c}"/></td>
+	        	<td></td>
+	        	<td class="hand"><apex:outputField value="{!swo.GOOD_WILL__c}"/>{!$ObjectType.SWO__c.fields.GOOD_WILL__c.label}</td>
+	        	<td><apex:outputField value="{!swo.PER__c}"/></td>
+	        </tr>
+	        <tr>
+	        	<td class="hand"><apex:outputField value="{!swo.GOVERNMENT_PROPERTY__c}"/>{!$ObjectType.SWO__c.fields.GOVERNMENT_PROPERTY__c.label}</td>
+	        	<td></td>
+	        	<td></td>
+	        	
+	        </tr>
+	        <tr>
+	        	<td></td>
+	        	<td></td>
+	        	<td></td>
+	        	
+	        </tr>
+	        <tr>
+	        	
+	        	<td></td>
+	        	<td></td>
+	        	<td></td>
+	        	<td></td>
+	        </tr>
+	    </table>
+
+	    <table style="width: 100%;border-collapse: collapse;">
+	    	<tr class="title">
+	    		<td id="titleProduct" class="title1"><apex:commandLink oncomplete="clickColorChange('Product')" action="{!setProduct}" reRender="table" value="Product Info" /></td>
+	    		<td id="titleCase" class="title1"><apex:commandLink oncomplete="clickColorChange('Case')" action="{!setCase}" reRender="table" value="Case Info" /></td>
+	    		<td id="titlemail" class="title1"><apex:commandLink oncomplete="clickColorChange('mail')" action="{!setMail}" reRender="table" value="Mail Merge" /></td>
+	    		<td id="titleTracking" class="title1"><apex:commandLink oncomplete="clickColorChange('Tracking')" action="{!setTracking}" reRender="table" value="Tracking" /></td>
+	    		<td id="titleTechnical" class="title1"><apex:commandLink oncomplete="clickColorChange('Technical')" action="{!setTechnical}" reRender="table" value="Technical Info" /></td>
+	    		<td id="titleEstimation" class="title1"><apex:commandLink oncomplete="clickColorChange('Estimation')" action="{!setEstimation}" reRender="table" value="Estimation" /></td>
+	    		<td id="titleRepair" class="title1"><apex:commandLink oncomplete="clickColorChange('Repair')" action="{!setRepair}" reRender="table" value="Repair Parts" /></td>
+	    		<td id="titleDiagnosis" class="title1"><apex:commandLink oncomplete="clickColorChange('Diagnosis')" action="{!setDiagnosis}" reRender="table" value="Diagnosis part " /></td>
+	    		<td id="titleQuotes" class="title1"><apex:commandLink oncomplete="clickColorChange('Quotes')" action="{!setQuotes}" reRender="table" value="Quotes" /></td>
+	    		<td id="titleGeneral" class="title1"><apex:commandLink oncomplete="clickColorChange('General')" action="{!setGeneral}" reRender="table" value="General" /></td>
+	    		<td id="titleIncoming" class="title1"><apex:commandLink oncomplete="clickColorChange('Incoming')" action="{!setIncoming}" reRender="table" value="Incoming Quality" /></td>
+	    		<td id="titleOutgoing" class="title1"><apex:commandLink oncomplete="clickColorChange('Outgoing')" action="{!setOutgoing}" reRender="table" value="Outgoing Quality" /></td>
+	    		<td id="titleFault" class="title1"><apex:commandLink oncomplete="clickColorChange('Fault')" action="{!setFault}" reRender="table" value="Fault Analysis" /></td>
+	    		
+	    	</tr>
+	    </table>
+	    <br/>
+	    <apex:outputPanel id="table">
+	    	<apex:outputPanel rendered="{!IF(type = 'mail' || type = 'All',true,false)}">
+	    		<br/>
+	    		<apex:commandButton id="openPDF" value="Mail" onclick="openPDF();return false;" style="width: 5%" />
+	    		<br/>
+	    		<table id="mailTable" style="width: 100%">
+	    			<colgroup>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			        </colgroup>
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+	    				<td>VIEW</td> 
+	    				<td>DATE</td>
+	    				<td>AUTHOR</td>
+	    				<td>MESSAGE</td>
+	    				<td>EMAIL SENT</td>
+	    				<td>PRIMARY RECIPIENT</td>
+	    				<td>CC</td>
+	    				<td>FILES</td>
+	    				<td>ATTACHMENTS</td>
+	    				<td>INTERNAL ONLY</td>
+	    			</tr>
+	    			<apex:repeat value="{!mailList}" var="mail" id="lines">
+	    				<tr class="row">
+	    					<td><apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=SWO&typeid={!swoid}&openType=View">View</apex:outputLink>&nbsp;&nbsp;<apex:outputLink value="/apex/SendEmail?id={!mail.mm.ID}&type=SWO&typeid={!swoid}&openType=Reply">Reply</apex:outputLink></td> 
+	    					<td><apex:outputField value="{!mail.mm.DATE__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.FROM__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.MESSAGE__c}" /></td>
+	    					<td><apex:outputText value="{!mail.mm.EMAIL_SENT__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.toName__c}" /></td>
+	    					<td><apex:outputField value="{!mail.mm.ccName__c}" /></td>
+	    					<td><apex:outputText value="{!mail.haveAtt}" /></td>
+	    					<td>
+	    						<apex:repeat value="{!mail.attList}" var="att" id="lines">
+	    							<apex:outputLink value="/{!att.Id}"><c:PDFWbr targetStr="{!att.Name}" /></apex:outputLink>
+	    							<br/>
+	    						</apex:repeat>
+	    					</td>
+	    					<td><apex:outputText value="YES" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Quotes' || type = 'All',true,false)}">
+	    		<br/>
+	    		<apex:commandButton id="openquotes" value="Quotes" onclick="openQuote();return false;" style="width: 5%"/>
+	    		<br/>
+	    		<table id="mailTable" style="width: 100%">
+	    			<colgroup>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			            <col width="14%"/>
+			        </colgroup>
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+	    				<td>QUOTE NUMBER</td>
+	    				<td>STATUS</td>
+	    				<td>ITEM</td>
+	    				<td>PART NUMBER</td>
+	    				<td>QUANTITY</td>
+	    				<td>CURRENCY</td>
+	    				<td>AMOUNT</td>
+	    				
+	    			</tr>
+	    			<apex:repeat value="{!qiList}" var="qi" id="quotesLines">
+	    				<tr class="row">
+	    					<td><apex:outputLink value="/{!qi.QUOTE__r.ID}" >{!qi.QUOTE__r.Name}</apex:outputLink></td>
+	    					<td><apex:outputField value="{!qi.QUOTE__r.STATUS__c}" /></td>
+	    					<td><apex:outputField value="{!qi.QuotesItemProduct__c}" /></td>
+	    					<td><apex:outputField value="{!qi.PART_NUMBERNew__c}" /></td>
+	    					<td><apex:outputField value="{!qi.QUANTITY__c}" /></td>
+	    					<td><apex:outputField value="{!qi.CURRENCY__c}" /></td>
+	    					<td><apex:outputField value="{!qi.AMOUNT__c}" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+
+	    		</table>
+	    	</apex:outputPanel>
+
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Repair' || type = 'All',true,false)}">
+	    		<br/>
+	    		<apex:commandButton id="openRepair" value="Repair Parts" onclick="openRepair('');return false;" style="width: 8%"/>
+	    		<br/>
+	    		<table id="mailRepair" style="width: 100%; ">
+	    			
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+	    				<td>ID</td>
+	    				<td>ITEM</td>
+	    				<td>PART NUMBER</td>
+	    				<td>INST. SERIAL #</td>
+	    				<td>DESCRIPTION</td>
+	    				<td>QUANTITY</td>
+	    				<td>DEFECT PART NUMBER</td>
+	    				<td>DEFECT SERIAL NUMBER</td>
+	    				<!-- <td>ANI DEFECT CATEGORY</td> -->
+	    				<td>HOURS</td>
+	    				<td>LOCATION</td>
+	    				<td>BILL AT 0$ VALUE</td>
+	    				<td>ECN</td>
+	    				<td>QTY PICKED</td>
+	    			</tr>
+	    			<apex:repeat value="{!rpList}" var="rp" id="RepairLines">
+	    				<tr class="row">
+	    					<!-- <td><apex:outputLink value="/{!rp.ID}" >{!rp.Name}</apex:outputLink></td> -->
+	    					<td><apex:outputLink onclick="openRepair('{!rp.ID}')" value="javascript:void(0)" >{!rp.Name}</apex:outputLink></td>
+	    					<td><apex:outputField value="{!rp.Product__r.ProductCode}" /></td>
+	    					<td><apex:outputField value="{!rp.Product__r.Product_ECCode__c}" /></td>
+	    					<td><apex:outputField value="{!rp.INST_SERIAL__c}" /></td>
+	    					<td><apex:outputField value="{!rp.Product__r.Description}" /></td>
+	    					<td><apex:outputField value="{!rp.QUANTITY__c}" /></td>
+	    					<td><apex:outputField value="{!rp.DEFECT_PART_NUMBER__c}" /></td>
+	    					<td><apex:outputField value="{!rp.DEFECT_SERIAL_NUMBER__c}" /></td>
+	    					<!-- <td><apex:outputField value="{!rp.DEFECT_CATEGORY__c}" /></td> -->
+	    					<td><apex:outputField value="{!rp.HOURS__c}" /></td>
+	    					<td><apex:outputField value="{!rp.LOCATION__c}" /></td>
+	    					<td><apex:outputField value="{!rp.BILL_AT_0_VALUE__c}" /></td>
+	    					<td><apex:outputField value="{!rp.ECN__c}" /></td>
+	    					<td><apex:outputField value="{!rp.QTY_PICKED__c}" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+
+	    		</table>
+	    	
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Product' || type = 'All',true,false)}">
+	    		<table id="mailProduct" style="width: 100%">
+	    			<colgroup>
+			            <col width="50%"/>
+			            <col width="50%"/>
+			        </colgroup>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ITEM__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DESCRIPTION__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ITEM__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DESCRIPTION_F__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PART_NUMBER_F__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ETQ_NUMBER__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.PART_NUMBER_F__c}"/></td>
+	        			<td><apex:outputField value="{!swo.ETQ_NUMBER__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td  class="hand"><apex:outputField value="{!swo.NON_STANDARD_ITEM__c}" />{!$ObjectType.SWO__c.fields.NON_STANDARD_ITEM__c.label}</td>
+			        	<td class="hand">
+			        		{!$ObjectType.SWO__c.fields.INSTRUMENT_MODEL_NUMBER__c.label}
+			        	</td>
+			        </tr>
+
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.QUANTITY__c.label}</td>
+			        	<td><apex:outputField value="{!swo.INSTRUMENT_MODEL_NUMBER__c}" /></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.QUANTITY__c}" /></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SERIAL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.MANUFACTURER__c.label}</td>
+			        	<td><apex:outputField value="{!swo.SERIAL__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:outputField value="{!swo.MANUFACTURER__c}" /></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.MFR_DATE__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:outputField value="{!swo.MFR_DATE__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.XRF_REGISTRATION_NUMBER__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:outputField value="{!swo.XRF_REGISTRATION_NUMBER__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.XRF_EXPIRATION_DATE__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:outputField value="{!swo.XRF_EXPIRATION_DATE__c}" /></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.XRF_REGISTRATION_NUMBER__c.label}</td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td><apex:outputField value="{!swo.CATALOG__c}" /></td>
+			        </tr>
+
+
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Case' || type = 'All',true,false)}">
+	    		<table id="mailCase" style="width: 100%">
+	    			<colgroup>
+			            <col width="50%"/>
+			            <col width="50%"/>
+			        </colgroup>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CASE_NUMBER__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.EMAIL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CASE_NUMBER__c}" ></apex:outputField></td>
+	        			<td><apex:outputField value="{!swo.EMAIL__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.COMPANY__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ASSIGNED_TO__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.COMPANY__c}" ></apex:outputField></td>
+	        			<td><apex:outputField value="{!swo.ASSIGNED_TO__c}"/></td>
+			        </tr>
+			       <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CONTACT__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.TRAN__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CONTACT__c}" ></apex:outputField></td>
+	        			<td><apex:outputField value="{!swo.TRAN__c}"/></td>
+			        </tr>
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Tracking' || type = 'All',true,false)}">
+	    		<table style="width: 100%">
+	    			<tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Tracking Turnaround Time</th>
+	    			</tr>
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.INSTRUMENT_RECEIVE_DATE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.INSTRUMENT_SHIP_DATE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DAYS_IN_HOUSE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.INSTRUMENT_RECEIVE_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.INSTRUMENT_SHIP_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DAYS_IN_HOUSE__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DIAGNOSIS_START__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DIAGNOSIS_END__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DIAGNOSIS_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.DIAGNOSIS_START__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DIAGNOSIS_END__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DIAGNOSIS_TIME__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PO_RECEIVE_DATE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Quotation_send__c.label}</td>
+			        	<!-- <td>{!$ObjectType.SWO__c.fields.READY_TO_QUOTE__c.label}</td> -->
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.TIME_AWAITING_PO__c.label}</td>
+			        </tr>
+			        <tr> 
+	        			<td><apex:outputField value="{!swo.PO_RECEIVE_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.Quotation_send__c}"/></td>
+			        	<!-- <td><apex:outputField value="{!swo.READY_TO_QUOTE__c}"/></td> -->
+	        			<td><apex:outputField value="{!swo.TIME_AWAITING_PO__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPAIR_START__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPAIR_END__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPAIR_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.REPAIR_START__c}"/></td>
+	        			<td><apex:outputField value="{!swo.REPAIR_END__c}"/></td>
+	        			<td><apex:outputField value="{!swo.REPAIR_TIME__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CALIBRATION_START__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CALIBRATION_END__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CALIBRATION_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CALIBRATION_START__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CALIBRATION_END__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CALIBRATION_TIME__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_START__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_end__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.FQC_START__c}"/></td>
+			        	<td><apex:outputField value="{!swo.FQC_end__c}"/></td>
+	        			<td><apex:outputField value="{!swo.FQC_TIME__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<!-- <td>{!$ObjectType.SWO__c.fields.SALES_ORDER_FULFILLED__c.label}</td> -->
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Repair_DateTime__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DELIVERED_TO_SERVICE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.TIME_IN_QUEUE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<!-- <td><apex:outputField value="{!swo.SALES_ORDER_FULFILLED__c}"/></td> -->
+			        	<td><apex:outputField value="{!swo.Repair_DateTime__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DELIVERED_TO_SERVICE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TIME_IN_QUEUE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Quotation_for_Approval__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Quotation_Approved__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.READY_FOR_SALES_ORDER__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.Quotation_for_Approval__c}"/></td>
+			        	<td><apex:outputField value="{!swo.Quotation_Approved__c}"/></td>
+	        			<td><apex:outputField value="{!swo.READY_FOR_SALES_ORDER__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.LATE_REASON__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ESTIMATED_PROMISE_DATE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DOOR_TO_DOOR_TIME__c.label}</td>
+			        </tr>
+			        <tr>
+	        			<td><apex:outputField value="{!swo.LATE_REASON__c}"/></td>
+	        			<td><apex:outputField value="{!swo.ESTIMATED_PROMISE_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.DOOR_TO_DOOR_TIME__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ONSITE_PROMISE_DATE__c.label}</td>
+			        	<td>&nbsp;</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.TIMES_CALIBRATED__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ONSITE_PROMISE_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td><apex:outputField value="{!swo.TIMES_CALIBRATED__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ONSITE_ARRIVAL_DATE__c.label}</td>
+	        			<td class="hand">{!$ObjectType.SWO__c.fields.READY_TO_QUOTE__c.label}</td>
+	        			<td class="hand"><apex:outputField value="{!swo.FQC_PASS__c}"/>{!$ObjectType.SWO__c.fields.FQC_PASS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ONSITE_ARRIVAL_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.READY_TO_QUOTE__c}"/></td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ONSITE_COMPLETION_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ONSITE_COMPLETION_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.LATE_REASONS__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.LATE_REASONS__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			    </table>
+	    		
+			        
+			    <table style="width: 100%">
+	    			<tr>
+	    				<th colspan="5" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Holds</th>
+	    			</tr>
+	    			<colgroup>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			        </colgroup>
+			         <tr>
+			        	<td colspan="5" class="hand"><apex:outputField value="{!swo.HOLDS__c}"/>{!$ObjectType.SWO__c.fields.HOLDS__c.label}</td>
+			        </tr>
+
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_START_1__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_END_1__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_REASON_1__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_NOTE_1__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_PHASE_1__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.HOLD_START_1__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_END_1__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_REASON_1__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_NOTE_1__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_PHASE_1__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_START_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_END_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_REASON_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_NOTE_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_PHASE_2__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.HOLD_START_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_END_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_REASON_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_NOTE_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_PHASE_2__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_START_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_END_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_REASON_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_NOTE_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HOLD_PHASE_3__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.HOLD_START_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_END_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_REASON_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_NOTE_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HOLD_PHASE_3__c}"/></td>
+			        </tr>
+	    		</table>
+
+	    		<!-- <table style="width: 100%">
+	    			<tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Factory</th>
+	    			</tr>
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+
+			       <tr>
+	        			<td><apex:outputField value="{!swo.FACTORY_REPAIR__c}"/>{!$ObjectType.SWO__c.fields.FACTORY_REPAIR__c.label}</td>
+	        			<td>{!$ObjectType.SWO__c.fields.REPAIR_LOCATION__c.label}</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+	        			<td>&nbsp;</td>
+	        			<td><apex:outputField value="{!swo.REPAIR_LOCATION__c}"/></td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.VENDOR_RMA__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.CLOSED_DATE__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.LOGISTICS_SHIPMENT_TYPE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.VENDOR_RMA__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CLOSED_DATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.LOGISTICS_SHIPMENT_TYPE__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td>&nbsp;</td>
+			        	<td>{!$ObjectType.SWO__c.fields.LAST_MODIFIED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.BY__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.LATE_REASONS__c.label}</td>
+	        			<td><apex:outputField value="{!swo.LAST_MODIFIED__c}"/></td>
+	        			<td><apex:outputField value="{!swo.BY__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:outputField value="{!swo.LATE_REASONS__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			         <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.MEMO__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.MEMO__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_CARRIER__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.TO_VENDOR_CARRIER__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_TRACKING__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.TO_VENDOR_TRACKING__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_PROMISE_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ONSITE_PROMISE_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_ARRIVAL_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ONSITE_ARRIVAL_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.ONSITE_COMPLETION_DATE__c.label}</td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ONSITE_COMPLETION_DATE__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+
+			    </table>
+
+			     <table style="width: 100%">
+	    			<tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Other</th>
+	    			</tr>
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.DATE_CREATED__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.ELTON__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_COST__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.DATE_CREATED__c}"/></td>
+	        			<td><apex:outputField value="{!swo.ELTON__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TO_CUSTOMER_COST__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.PO_APPROVAL_TIME__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_CARRIER__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.SHIPPED_TO_VENDOR_DATE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.PO_APPROVAL_TIME__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TO_CUSTOMER_CARRIER__c}"/></td>
+	        			<td><apex:outputField value="{!swo.SHIPPED_TO_VENDOR_DATE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.TECHNICIAN_COMPLETION_TIME__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_TRACKING__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_PACKING_SLIP__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.TECHNICIAN_COMPLETION_TIME__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TO_CUSTOMER_TRACKING__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TO_VENDOR_PACKING_SLIP__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.DOOR_TO_DOOR_TIME__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_CUSTOMER_PACKING_SLIP__c.label}</td>
+			        	<td>{!$ObjectType.SWO__c.fields.TO_VENDOR_COST__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.DOOR_TO_DOOR_TIME__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TO_CUSTOMER_PACKING_SLIP__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TO_VENDOR_COST__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ECN__c}"/>{!$ObjectType.SWO__c.fields.ECN__c.label}</td>
+			        	<td>&nbsp;</td>
+			        	<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td>{!$ObjectType.SWO__c.fields.OT_CLAIM__c.label}</td>
+			        	<td>&nbsp;</td>
+			        	<td>&nbsp;</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.OT_CLAIM__c}"/></td>
+	        			<td>&nbsp;</td>
+	        			<td>&nbsp;</td>
+			        </tr>
+			    </table> -->
+
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Technical' || type = 'All',true,false)}">
+	    		<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">As Reported by Customer</th>
+	    			</tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPORTED_PRODUCT_LINE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.AS_REPORTED_CODE_CLASS__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.AS_REPORTED_CODES_ETQ__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.REPORTED_PRODUCT_LINE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.AS_REPORTED_CODE_CLASS__c}"/></td>
+	        			<td><apex:outputField value="{!swo.AS_REPORTED_CODES_ETQ__c}"/></td>
+			        </tr>
+	    		</table>
+
+	    		<table style="width: 100%">
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="16.5%"/>
+			            <col width="16.5%"/>
+			            <col width="34%"/>
+			           
+			        </colgroup>
+	    			<tr>
+	    				<th colspan="4" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Technical Info</th>
+	    			</tr>
+	    			
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SPECIAL_CUSTOMER_REQUIREMENTS__c.label}</td>
+			        	<td class="hand;colspan:2">{!$ObjectType.SWO__c.fields.ASSIGNED_TO_TECHNICIAN_DATE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FAILURE_SYMPTOM__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.SPECIAL_CUSTOMER_REQUIREMENTS__c}"/></td>
+	        			<td colspan="2"><apex:outputField value="{!swo.ASSIGNED_TO_TECHNICIAN_DATE__c}"/></td>
+	        			<td ><apex:outputField value="{!swo.FAILURE_SYMPTOM__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REQUIREMENT_DETAILS__c.label}</td>
+			        	<td class="hand;colspan:2">{!$ObjectType.SWO__c.fields.TECHNICIAN_COMPLETION_DATE__c.label}</td>
+			        	<td  class="hand"><apex:outputField value="{!swo.ROOT_CAUSE__c}"/>{!$ObjectType.SWO__c.fields.ROOT_CAUSE__c.label}<apex:outputField value="{!swo.NCM__c}"/>{!$ObjectType.SWO__c.fields.NCM__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td rowspan="4"><apex:outputField value="{!swo.REQUIREMENT_DETAILS__c}"  /></td>
+			        	<td colspan="2"><apex:outputField value="{!swo.TECHNICIAN_COMPLETION_DATE__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FAILURE_SOURCE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand;colspan:2">{!$ObjectType.SWO__c.fields.GOVERNMENT_INSPECTION_DATE__c.label}</td>
+			        	<td><apex:outputField value="{!swo.FAILURE_SOURCE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td colspan="2"><apex:outputField value="{!swo.GOVERNMENT_INSPECTION_DATE__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FAILURE_SOURCE_DETAIL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Part_Hold_Date__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.In_Queue_Date__c.label}</td>
+			        	<td><apex:outputField value="{!swo.FAILURE_SOURCE_DETAIL__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REQUIREMENTS_FULFILLED_ON__c.label}</td>
+			        	<td><apex:outputField value="{!swo.Part_Hold_Date__c}"/></td>
+			        	<td><apex:outputField value="{!swo.In_Queue_Date__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ROOT_CAUSE_FOR_FAILURE_S__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.REQUIREMENTS_FULFILLED_ON__c}"/></td>
+			        	<td class="hand;colspan:2">{!$ObjectType.SWO__c.fields.Ready_for_Quote__c.label}</td>
+			        	<td><apex:outputField value="{!swo.ROOT_CAUSE_FOR_FAILURE_S__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+			        	<td colspan="2"><apex:outputField value="{!swo.Ready_for_Quote__c}"/></td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Parts_request_for_diagnosis_date__c.label}</td>
+			        	<td class="hand" colspan="2">{!$ObjectType.SWO__c.fields.Parts_ready_for_diagnosis_date__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.Ready_to_ship_date__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.Parts_request_for_diagnosis_date__c}"/></td>
+			        	<td colspan="2"><apex:outputField value="{!swo.Parts_ready_for_diagnosis_date__c}"/></td>
+			        	<td><apex:outputField value="{!swo.Ready_to_ship_date__c}"/></td>
+			        </tr>
+	    		</table>
+
+	    		<table style="width: 100%">
+
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+	    			<tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">As Analyzed by Service</th>
+	    			</tr>
+	    			
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ANALYZED_PRODUCT_LINE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.AS_ANALYZED_CODE_CLASS__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.AS_ANALYZED_CODES_ETQ__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ANALYZED_PRODUCT_LINE__c}"/></td>
+			        	<td><apex:outputField value="{!swo.AS_ANALYZED_CODE_CLASS__c}"/></td>
+			        	<td><apex:outputField value="{!swo.AS_ANALYZED_CODES_ETQ__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPAIR_PART_PRODUCT_LINE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PART_CODE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.REPAIR_PART_PRODUCT_LINE__c}"/></td>
+			        	<td ><apex:outputField value="{!swo.PART_CODE__c}"/></td>
+			        	<td></td>
+			        </tr>
+			    </table>
+
+			     <table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr style="width: 98%">
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Repeat Repair</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Factory Support</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Service Notes</th>
+	    			</tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPEAT_REPAIR_REASON_CODE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FACTORY_ASSIGNED_TO__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SYMPTOM_NOTES__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.REPEAT_REPAIR_REASON_CODE__c}"/></td>
+			        	<td><apex:outputField value="{!swo.FACTORY_ASSIGNED_TO__c}"/></td>
+			        	<td rowspan="3"><apex:outputField value="{!swo.SYMPTOM_NOTES__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.REPEAT_REPAIR__c}"/>{!$ObjectType.SWO__c.fields.REPEAT_REPAIR__c.label}</td>
+			        	<td  class="hand">{!$ObjectType.SWO__c.fields.FACTORY_ASSIGNED_TO_DATE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PREVIOUS_REPAIR_SWO__c.label}</td>
+			        	<td ><apex:outputField value="{!swo.FACTORY_ASSIGNED_TO_DATE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.PREVIOUS_REPAIR_SWO__c}"/></td>
+			        	<td  class="hand">{!$ObjectType.SWO__c.fields.FACTORY_RETURNED_DATE__c.label}</td>
+			        	<td  class="hand">{!$ObjectType.SWO__c.fields.DIAGNOSIS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td  class="hand">{!$ObjectType.SWO__c.fields.PREVIOUS_COMPLETED_DATE__c.label}</td>
+			        	<!-- <td class="hand">{!$ObjectType.SWO__c.fields.REPEAT_REPAIR_ORIGINAL_NOTES__c.label}</td> -->
+			        	<td ><apex:outputField value="{!swo.FACTORY_RETURNED_DATE__c}"/></td>
+			        	<td rowspan="5"><apex:outputField value="{!swo.DIAGNOSIS__c}"/></td>
+
+			        </tr>
+			         <tr>
+			         	<td><apex:outputField value="{!swo.PREVIOUS_COMPLETED_DATE__c}"/></td>
+			        	<!-- <td rowspan="4"><apex:outputField value="{!swo.REPEAT_REPAIR_ORIGINAL_NOTES__c}"/></td> -->
+			        	<td  class="hand">{!$ObjectType.SWO__c.fields.MICRO_CODE_CLASS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.REPEAT_REPAIR_ORIGINAL_NOTES__c.label}</td>
+			        	<td><apex:outputField value="{!swo.MICRO_CODE_CLASS__c}"/></td>
+			        </tr>
+			         <tr>
+			         	<td rowspan="2"><apex:outputField value="{!swo.REPEAT_REPAIR_ORIGINAL_NOTES__c}"/></td>
+			        	<td  class="hand">{!$ObjectType.SWO__c.fields.MICRO_FAILURE_DESCRIPTION__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.MICRO_FAILURE_DESCRIPTION__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.Problems_fixed_by_initial_solutions__c}"/>{!$ObjectType.SWO__c.fields.Problems_fixed_by_initial_solutions__c.label}</td>
+			        	<td></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SERVICES_PERFORMED__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.reason_for_the_2nd_field_service__c.label}</td>
+			        	<td></td>
+			        	<td rowspan="2"><apex:outputField value="{!swo.SERVICES_PERFORMED__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.reason_for_the_2nd_field_service__c}"/></td>
+			        	<td></td>
+			        	<td></td>
+			        </tr>
+
+			    </table>
+
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Estimation' || type = 'All',true,false)}">
+	    		<table id="mailEstimation" style="width: 100%">
+	    			<colgroup>
+			            <col width="50%"/>
+			            <col width="50%"/>
+			        </colgroup>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ESTIMATED_MATERIAL_COST__c.label}</td>
+			        	<td class="hand"><apex:outputField value="{!swo.WORK_IS_COMPLETE__c}"/>{!$ObjectType.SWO__c.fields.WORK_IS_COMPLETE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ESTIMATED_MATERIAL_COST__c}"/></td>
+	        			<td class="hand">{!$ObjectType.SWO__c.fields.ESTIMATED_TOTAL_COST__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.MATERIAL_MARK_UP_RATE__c.label}</td>
+			        	<td><apex:outputField value="{!swo.ESTIMATED_TOTAL_COST__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.MATERIAL_MARK_UP_RATE__c}"/></td>
+	        			<td class="hand">{!$ObjectType.SWO__c.fields.ESTIMATED_TOTAL_PRICE__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.USE_ESTIMATED_MATERIAL__c}"/>{!$ObjectType.SWO__c.fields.USE_ESTIMATED_MATERIAL__c.label}</td>
+			        	<td><apex:outputField value="{!swo.ESTIMATED_TOTAL_PRICE__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ESTIMATED_LABOUR_HOURS__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CURRENCY__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ESTIMATED_LABOUR_HOURS__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CURRENCY__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.LABOUR_RATE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PRICE_LEVEL__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.LABOUR_RATE__c}"/></td>
+	        			<td><apex:outputField value="{!swo.PRICE_LEVEL__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.USE_ESTIMATED_LABOUR__c}"/>{!$ObjectType.SWO__c.fields.USE_ESTIMATED_LABOUR__c.label}</td>
+			        	<td></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ESTIMATED_EXPENSES_COSTS__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ESTIMATED_EXPENSES_COSTS__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.EXPENSE_MARK_UP_RATE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.EXPENSE_MARK_UP_RATE__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.USE_ESTIMATED_EXPENSES__c}"/>{!$ObjectType.SWO__c.fields.USE_ESTIMATED_EXPENSES__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        
+	    		</table>
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'General' || type = 'All',true,false)}">
+	    		<apex:commandButton value="Attach" action="{!uploadFile}"></apex:commandButton>
+					
+			   
+		    	<table class="tableCss" style="border:1px solid #000000;width: 80%">	
+		    		<tr style="text-align:center;">
+		    			<th style="text-align:center;width: 33%;">File Name</th>
+		    			<th style="text-align:center;width: 33%;">Upload Time</th>
+		    			<th style="text-align:center;width: 33%;">File Size</th>
+		    		</tr>
+		    		<apex:repeat id="attachmentList" value="{!attachmentList}" var="attachment">
+		    			<tr style="text-align:center; vertical-align: middle;">
+		    				<!-- <td><output value="{!attachment.Name}" readonly="readonly" style="border:none;"/></td> -->
+		    				<td><apex:outputLink value="/{!attachment.Id}">{!attachment.Name}</apex:outputLink></td>
+		    				<td><apex:outputField value="{!attachment.CreatedDate}"/></td>
+		    				<td><apex:outputField value="{!attachment.BodyLength}"/></td>
+		    			</tr>
+		    		</apex:repeat>
+		    	</table>
+
+	    	</apex:outputPanel>
+
+	    	<apex:outputPanel rendered="{!IF(type = 'Outgoing' || type = 'All',true,false)}">
+		    	<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">New Section</th>
+	    			</tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.OUTGOING_INSPECTION_COMPLETED_BY__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.HAVE_ALL_ACCESSORIES_BEEN_INCLUDED__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.NOTES__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.OUTGOING_INSPECTION_COMPLETED_BY__c}"/></td>
+	        			<td><apex:outputField value="{!swo.HAVE_ALL_ACCESSORIES_BEEN_INCLUDED__c}"/></td>
+	        			<td><apex:outputField value="{!swo.NOTES__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.UNIT_POWERS_UP__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.TRIGGER_LOCK_ONE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.UNIT_POWERS_UP__c}"/></td>
+	        			<td><apex:outputField value="{!swo.TRIGGER_LOCK_ONE__c}"/></td>
+	        			<td></td>
+			        </tr>
+
+			        <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.BATTERY_INCLUDED1__c}"/>{!$ObjectType.SWO__c.fields.BATTERY_INCLUDED1__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DEAD_MAN_TRIGGER_ONE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ANY_VISIBLE_DAMAGE__c.label}</td>
+	        			<td><apex:outputField value="{!swo.DEAD_MAN_TRIGGER_ONE__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.ANY_VISIBLE_DAMAGE__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SERIAL_MATCHES_SO__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CAL_CERT_AND_STICKER_VERIFIED_CORRECT__c.label}</td>
+	        			<td><apex:outputField value="{!swo.SERIAL_MATCHES_SO__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CAL_CERT_AND_STICKER_VERIFIED_CORRECT__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.VERIFY_SOFTWARE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.KEYPAD_FUNCTIONS_CORRECTLY__c.label}</td>
+	        			<td><apex:outputField value="{!swo.VERIFY_SOFTWARE__c}"/></td>
+	        			<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.KEYPAD_FUNCTIONS_CORRECTLY__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.RADIATION_SURVEYPERFORMED_ATTACHED__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CUSTOM_SETUPS_INCLUDED__c.label}</td>
+	        			<td><apex:outputField value="{!swo.RADIATION_SURVEYPERFORMED_ATTACHED__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:outputField value="{!swo.CUSTOM_SETUPS_INCLUDED__c}"/></td>
+			        	<td></td>
+			        	<td></td>
+			        </tr>
+
+				</table>
+
+				<table style="width: 100%">
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/> 
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Legacy Fields</th>
+	    			</tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CAL_CERT_AND_STICKER_INCLUDED__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.POWER_UP_UNIT_DISPLAY_OK__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_RAD_SURVEY_PERFORMED_ATTACHED__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.CAL_CERT_AND_STICKER_INCLUDED__c}"/></td>
+	        			<td><apex:outputField value="{!swo.POWER_UP_UNIT_DISPLAY_OK__c}"/></td>
+	        			<td><apex:outputField value="{!swo.FQC_RAD_SURVEY_PERFORMED_ATTACHED__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.POWER_LEVEL__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PASSED_COSMETIC_CHECK__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.POWER_LEVEL__c}"/></td>
+	        			<td><apex:outputField value="{!swo.PASSED_COSMETIC_CHECK__c}"/></td>
+	        			<td></td>
+			        </tr>
+			    </table>
+			</apex:outputPanel>
+
+			<apex:outputPanel rendered="{!IF(type = 'Incoming' || type = 'All',true,false)}">
+		    	<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">New Section</th>
+	    			</tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.INCOMING_INSPECTION_COMPLETED_BY__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.BATTERY_MORE_THAN_3_YRS_OLD__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.NOTES__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.INCOMING_INSPECTION_COMPLETED_BY__c}"/></td>
+	        			<td><apex:outputField value="{!swo.BATTERY_MORE_THAN_3_YRS_OLD__c}"/></td>
+	        			<td><apex:outputField value="{!swo.NOTES__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DOES_UNIT_POWER_UP_PROPERLY__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.VERIFY_SOFTWARE__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.DOES_UNIT_POWER_UP_PROPERLY__c}"/></td>
+	        			<td><apex:outputField value="{!swo.VERIFY_SOFTWARE__c}"/></td>
+	        			<td></td>
+			        </tr>
+
+			        <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.BATTERY_INCLUDED__c}"/>{!$ObjectType.SWO__c.fields.BATTERY_INCLUDED__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.TRIGGER_LOCK__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.ARRIVED_DAMAGED__c.label}</td>
+	        			<td><apex:outputField value="{!swo.TRIGGER_LOCK__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:outputField value="{!swo.ARRIVED_DAMAGED__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.DEAD_MAN_TRIGGER__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CONFIRMED_RECEIPT_WITH_CUSTOMER__c.label}</td>
+	        			<td><apex:outputField value="{!swo.DEAD_MAN_TRIGGER__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:outputField value="{!swo.CONFIRMED_RECEIPT_WITH_CUSTOMER__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.XRF_TUBE_HRS__c.label}</td>
+			        	<td></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CUSTOM_SETUPS_PRESENT__c.label}</td>
+	        			<td><apex:outputField value="{!swo.XRF_TUBE_HRS__c}"/></td>
+	        			<td></td>
+			        </tr>
+			         <tr>
+			        	<td><apex:outputField value="{!swo.CUSTOM_SETUPS_PRESENT__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.LOGIN__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PASS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+			        	<td><apex:outputField value="{!swo.LOGIN__c}"/></td>
+			        	<td><apex:outputField value="{!swo.PASS__c}"/></td>
+			        </tr>
+				</table>
+
+				<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="33%"/>
+			            <col width="33%"/>
+			            <col width="34%"/>
+			        </colgroup>
+			        <tr>
+	    				<th colspan="3" style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">Legacy Fields</th>
+	    			</tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.PASSED_COSMETIC_CHECK__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.RETURN_DEFECTIVE_PARTS__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SERIAL_MATCHES_PO__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.PASSED_COSMETIC_CHECK__c}"/></td>
+	        			<td><apex:outputField value="{!swo.RETURN_DEFECTIVE_PARTS__c}"/></td>
+	        			<td><apex:outputField value="{!swo.SERIAL_MATCHES_PO__c}"/></td>
+			        </tr>
+			    </table>
+			</apex:outputPanel>
+
+			<apex:outputPanel rendered="{!IF(type = 'Fault' || type = 'All',true,false)}">
+		    	<table style="width: 100%">
+	    			
+	    			<colgroup>
+			            <col width="25%"/>
+			            <col width="25%"/>
+			            <col width="25%"/>
+			            <col width="25%"/>
+			        </colgroup>
+			        <tr>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Initial Customer Complaint</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Fault Analysis 2</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Fault Analysis 3</th>
+	    				<th style="background-color: #ccc;font-size:14px;line-height: 20px;">Cal/QC First Pass Success/Fail Info</th>
+	    			</tr>
+	    			<tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SYMPTOMS_1__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SYMPTOMS_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SYMPTOMS_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CAL_FP_SUCCESS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.SYMPTOMS_1__c}"/></td>
+	        			<td><apex:outputField value="{!swo.SYMPTOMS_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.SYMPTOMS_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CAL_FP_SUCCESS__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td class="hand"><apex:outputField value="{!swo.REPRODUCED_IN_SERVICE__c}"/>{!$ObjectType.SWO__c.fields.REPRODUCED_IN_SERVICE__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FAILURE_REASONS_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FAILURE_REASONS_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CAL_FAIL_REASON__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FAILURE_REASONS_1__c.label}</td>
+	        			<td><apex:outputField value="{!swo.FAILURE_REASONS_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.FAILURE_REASONS_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CAL_FAIL_REASON__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.FAILURE_REASONS_1__c}"/></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SECONDARY_FAILURE_REASONS_2__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SECONDARY_FAILURE_REASONS_3__c.label}</td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.CAL_SOLUTION__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.SECONDARY_FAILURE_REASONS_1__c.label}</td>
+	        			<td><apex:outputField value="{!swo.SECONDARY_FAILURE_REASONS_2__c}"/></td>
+	        			<td><apex:outputField value="{!swo.SECONDARY_FAILURE_REASONS_3__c}"/></td>
+	        			<td><apex:outputField value="{!swo.CAL_SOLUTION__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td><apex:outputField value="{!swo.SECONDARY_FAILURE_REASONS_1__c}"/></td>
+			        	<td></td>
+			        	<td></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_FP_SUCCESS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+	        			<td></td>
+	        			<td></td>
+	        			<td><apex:outputField value="{!swo.FQC_FP_SUCCESS__c}"/></td>
+			        </tr>
+			         <tr>
+			        	<td></td>
+			        	<td></td>
+			        	<td></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_FAIL_REASON__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+	        			<td></td>
+	        			<td></td>
+	        			<td><apex:outputField value="{!swo.FQC_FAIL_REASON__c}"/></td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+			        	<td></td>
+			        	<td></td>
+			        	<td class="hand">{!$ObjectType.SWO__c.fields.FQC_SOLUTIONS__c.label}</td>
+			        </tr>
+			        <tr>
+			        	<td></td>
+	        			<td></td>
+	        			<td></td>
+	        			<td><apex:outputField value="{!swo.FQC_SOLUTIONS__c}"/></td>
+			        </tr>
+
+			    </table>
+			</apex:outputPanel>
+
+			<apex:outputPanel rendered="{!IF(type = 'Diagnosis' || type = 'All',true,false)}">
+				<br/>
+	    		<!-- <apex:commandButton id="Adddiagnosis" value="ADD" action="{!addDiagnosisInfo}" reRender="table" style="width: 5%" /> -->
+	    		<apex:commandButton id="openDiagnosisPart" value="Diagnosis Part" onclick="openDiagnosisPart();return false;" style="width: 8%"/>
+                <br/>
+	    		<table id="diagnosisTable" style="width: 100%">
+	    			<colgroup>
+                        <col width="4%"/>
+			            <col width="6%"/>
+			            <col width="9%"/>
+			            <col width="9%"/>
+			            <col width="9%"/>
+			            <col width="6%"/>
+			            <col width="6%"/>
+			            <col width="9%"/>
+			            <col width="9%"/>
+			            <col width="7%"/>
+			            <col width="7%"/>
+			            <col width="9%"/>
+			            <col width="8%"/>
+			        </colgroup>
+	    			<tr style="background-color: #ccc;font-size:14px;line-height: 20px;width: 98%;">
+                        <th>EDIT</th>
+	    				<th>ITEM</th> 
+	    				<th>PART NUMBER</th>
+	    				<th>INST. SERIAL#</th>
+	    				<th>DESCRIPTION</th>
+	    				<th>QUANTITY</th>
+	    				<th>STATUS</th>
+	    				<th>HOLD REASON</th>
+	    				<th>REMARK</th>
+	    				<th>DELIVERED</th>
+	    				<th>RETURNED</th>
+	    				<th>Delivered date.</th>
+	    				<th>RETURN DATE</th>
+	    			</tr>
+	    			<apex:repeat value="{!diagnosisList}" var="dia" id="diagnosisList">
+	    				<tr>
+                            <td>
+                                <apex:outputLink value="/apex/NewDiagnosisPart?id={!dia.di.Id}" target="LINK_{!dia.di.Id}}" >EDIT</apex:outputLink>
+                            </td>
+	    					<td><apex:outputField value="{!dia.di.Product__r.ProductCode}" id="Name"/></td>
+	    					<td><apex:outputField value="{!dia.di.Product__r.Product_ECCode__c}" id="partNumber"/></td>
+	    					<td><apex:outputField value="{!dia.di.INST_SERIAL__c}" id="instSerial"/></td>
+	    					<td><apex:outputField value="{!dia.di.Product__r.Description}" id="description"/></td>
+	    					<td><apex:outputField value="{!dia.di.QUANTITY__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.STATUS__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.HOLD_REASON__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.REMARK__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.DELIVERED__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.RETURNED__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.DeliveredDate__c}" /></td>
+	    					<td><apex:outputField value="{!dia.di.RETURN_DATE__c}" /></td>
+	    				</tr>
+
+	    			</apex:repeat>
+	    		</table>
+			</apex:outputPanel>
+	    	
+	    </apex:outputPanel>
+		
+
+
+
+
+		<br/>
+		<br/>
+		<br/>
+		<br/>
+		<br/>
+		<apex:commandButton action="{!edit}"  value="EDIT" style="width: 5%;"/> 
+
+	</apex:form>
+	
+	<br/>
+	<br/>
+	<br/>
+	<br/>
+	<br/>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SWOPageRead.page-meta.xml b/scr/pages/SWOPageRead.page-meta.xml
new file mode 100644
index 0000000..0deaccd
--- /dev/null
+++ b/scr/pages/SWOPageRead.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SWOPageRead</label>
+</ApexPage>
diff --git a/scr/pages/SWOSearchProduct.page b/scr/pages/SWOSearchProduct.page
new file mode 100644
index 0000000..4cec041
--- /dev/null
+++ b/scr/pages/SWOSearchProduct.page
@@ -0,0 +1,222 @@
+<apex:page id="Page" Controller="SWOSearchProductContaroller" sidebar="false" showHeader="false" action="{!init}">
+  <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+    <script>
+       var QuoteEntryMaxLine = 150;
+         
+       function setProductList() {
+  
+            var nextLine = top.window.opener.getLastLineNoNext(window.opener.document);
+
+            var hasCheckedCnt = 0;
+         
+            var checklist = j$("input[name='checklist']");
+           
+           
+            for(var i=0; i<checklist.length; i++){
+                
+                    if (checklist[i].checked) {
+                        
+                        hasCheckedCnt++;
+                        if (nextLine < QuoteEntryMaxLine) {
+                            
+                            SetProductId(nextLine, i);
+                            nextLine++;
+                        } else {
+                            return false;
+                        }
+                    }
+            }
+            if (hasCheckedCnt == 0) {
+                alert(top.window.opener.Error_Message34);
+                return false;
+            }
+            top.window.close();
+        }
+
+        function setProductOne(lineno, i) {
+            SetProductId(lineno, i);
+            window.opener.doReroad();
+            top.window.close();
+        }
+
+        function doSearch() {
+            blockme();
+            serProduct.call();
+        }
+
+        function SetProductId(lineno, i) {
+          var ProductName = j$(escapeVfId("Page:allForm:allBlock:ProductList:theTable_content:"+ i +":ProductName")).text();
+          var productId = j$(escapeVfId("Page:allForm:allBlock:ProductList:theTable_content:"+ i +":productId")).text();
+          var ProductCode = j$(escapeVfId("Page:allForm:allBlock:ProductList:theTable_content:"+ i +":ProductCode")).text();            
+            var Description = j$(escapeVfId("Page:allForm:allBlock:ProductList:theTable_content:"+ i +":Description")).value();
+
+            if (Description.indexOf(";") != -1) {
+                var array = Description.split(";");
+                Description = '';
+                for (var i = 0; i <array.length; i++) {
+                    if (array[i] != '') {
+                        Description += array[i] + ';\n';
+                    }   
+                }
+            }
+            var PART_NUMBER = j$(escapeVfId("Page:allForm:allBlock:ProductList:theTable_content:"+ i +":PART_NUMBER")).text();
+            var ProductInventory = j$(escapeVfId("Page:allForm:allBlock:ProductList:theTable_content:"+ i +":ProductInventory")).text();
+
+            var type = j$(escapeVfId("type")).value();
+          
+            if ("Quotes" == type) {
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":ProductName")).val(ProductName);
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":productId")).val(productId);
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":ProductCode")).text(ProductCode);
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":Description")).val(Description);
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":PART_NUMBER")).text(PART_NUMBER);
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":ProductInventory")).text(ProductInventory);
+                window.opener.j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:theTable_content:" + lineno  + ":quantity")).val(1);
+           }else{
+                window.opener.j$(escapeVfId("Page:mainForm:diagnosisList:" + lineno  + ":Name")).val(ProductName);
+                window.opener.j$(escapeVfId("Page:mainForm:diagnosisList:" + lineno  + ":partNumber")).val(ProductCode);
+                window.opener.j$(escapeVfId("Page:mainForm:diagnosisList:" + lineno  + ":productId")).val(productId);
+                window.opener.j$(escapeVfId("Page:mainForm:diagnosisList:" + lineno  + ":description")).val(Description);
+           }
+            
+        }
+
+    </script>
+    
+    <style type="text/css">
+        div#iframelike {
+            color: #fff;
+            height: 300px;
+            overflow-y: auto;
+            overflow-x: hidden;
+        }
+    </style>
+    <apex:outputPanel id="all">
+        <apex:outputPanel id="message1">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+        <apex:form id="allForm">
+        <apex:actionFunction action="{!serProduct}" name="serProduct" reRender="ProductList,message1" oncomplete="unblockUI();"/>
+        <input type="hidden" id="type" value="{!type}"/>
+        <!-- <apex:actionFunction name="save" action="{!save}" rerender="allForm" onComplete="unblockUI();refreshPage();closeJs();"></apex:actionFunction> -->
+        <!-- <input type="hidden" id="baseUrl" value="{!baseUrl}"/> -->
+        <apex:pageBlock title="Product" id="allBlock">
+            <apex:pageblocksection columns="1"  id="ProductList">
+                <apex:outputPanel >
+                    <DIV style="OVERFLOW-Y: hidden; OVERFLOW-X:auto;width:1260px">
+                         
+                        <div id="ProductList:tablediv" style="OVERFLOW-X: hidden; OVERFLOW-Y:auto;width:1800px; height:400px">
+
+                            <apex:pageBlock id="idSearchSetProduct" title="{!$Label.Product_Search}">
+                                <!-- <table width="900" border="0" style="background-color:#DCDCDC"> -->
+                                <table width="900" border="0" >
+
+                                    <colgroup>
+                                        <col width="12" />
+                                        <col width="20" />
+                                        <col width="20" />
+                                        <col width="200" />
+                                        <col width="20" />
+                                        <col width="100" />
+                                        <col width="120" />
+                                        <col width="208" />
+                                    </colgroup>
+                                    <tr>
+                                        <td> </td>
+                                        <th>{!$Label.Search_Condition}</th>
+                                        <td> </td>
+                                        <th>{!$Label.Asset_No}</th>
+                                        <td> </td>
+                                        <td> </td>
+                                        <td> </td>
+                                        <td> </td>
+                                    </tr>
+                                    <tr>
+                                        <td> </td>
+                                        <td> </td>
+                                        <td> </td>
+                                        <td><apex:inputText id="searchName" value="{!SearchName}" style="width:200px" required="false"/></td>
+                                        <td><apex:commandButton value="{!$Label.Search}" onclick="doSearch();return false;" style="width:100px" /></td>
+                                        
+                                        <td> <apex:commandButton value="{!$Label.Add_Product}" style="width:100px;float:right;" rerender="dummy" onclick="setProductList();return false;"/></td>
+                                    </tr>
+                                    <!-- <tr>
+                                        <td style="border-bottom: 1px solid #888;" colspan="15"> </td>
+                                    </tr> -->
+                                </table>
+                            </apex:pageBlock>
+                            <table id="theTable_header" border="0" style ="width:1800px;text-align: center;"   styleClass="list">
+                            <thead>
+                                <tr>
+                                     <th>{!$Label.Search_Result}</th>
+                                </tr>
+                                <tr>
+                                   <td style ="width: 1%;text-align: center" scope="col">閫夋嫨</td>
+                                    <td style ="width: 1%;text-align: center" scope="col">No</td>
+
+                                    
+                                    
+                                    <td style ="width: 10%;text-align: center" scope="col">ProductName</td>
+
+                                    <td style ="width: 10%;text-align: center" scope="col">OTCode</td>
+                                    <td style ="width: 10%;text-align: center" scope="col">DESCRIPTION</td>
+                                    <!-- <td style ="width: 10%;;text-align: center" scope="col">Part Number</td>
+                                    <td style ="width: 10%;;text-align: center" scope="col">搴撳瓨</td> -->
+                                </tr>
+                            </thead>
+                        </table>
+
+                            <apex:dataTable value="{!productInfoList}"  var="ProductInfo" id="theTable_content" border="0" 
+                            style="width:1800px;border-bottom-width: 0px; font-size:11px; border-spacing:0;text-align: left;" styleClass="list"> 
+                                <apex:column style="width: 2.3%" >
+                                           
+                                            <input type="checkbox" name="checklist" value="" />
+                                        </apex:column>
+                                <apex:column style="width: 1%">
+                                    <apex:outputText value="{!ProductInfo.lineNumber}" id="lineNumber" style="resize:vertical;width: 95%"/>
+                                </apex:column>
+                                 
+                                
+                                <apex:column style="width: 10%">
+                                    <apex:outputText value="{!ProductInfo.productPage.Name}" id="ProductName" style="resize:vertical;width: 95%"/>
+                                    <apex:outputText id="productId" value="{!ProductInfo.productId}" style="display: none;"/>
+                                </apex:column>
+                                <apex:column style="width: 10%">
+                                    <!-- <c:PDFWbr targetStr="{!ProductInfo.productPage.ProductCode}" id="ProductCode"/> -->
+                                    <apex:outputText value="{!ProductInfo.productPage.ProductCode}" id="ProductCode" style="resize:vertical;width: 95%"/>
+                                </apex:column>
+                                <apex:column style="width: 10%">
+                                    <!-- <c:PDFWbr targetStr="{!ProductInfo.productPage.Description}" id="Description"/> -->
+                                    <apex:outputField value="{!ProductInfo.productPage.Description}" id="Description" style="resize:vertical;width: 95%"/>
+                                </apex:column>
+                                <!-- <apex:column style="width: 10%">
+                                   
+                                    <apex:outputText value="{!ProductInfo.productPage.PART_NUMBER__c}" id="PART_NUMBER" style="resize:vertical;width: 95%"/>
+                                </apex:column>
+
+                                <apex:column style="width: 10%">
+                                    
+                                    <apex:outputText value="{!ProductInfo.productPage.ProductInventory__c}" id="ProductInventory" style="resize:vertical;width: 95%"/>
+                                </apex:column> -->
+                                
+                        </apex:dataTable>
+                    </div>
+                </DIV>
+            </apex:outputPanel>
+        </apex:pageblocksection>
+    </apex:pageBlock>
+</apex:form>
+    </apex:outputPanel>
+    <script type="text/javascript">
+        // 銉曘偐銉笺偒銈广偦銉冦儓
+        j$(escapeVfId('Page:mainForm:idSearchSetProduct:searchName'))[0].focus();
+        j$(escapeVfId('Page:mainForm:idSearchSetProduct:searchName')).val(j$(escapeVfId('Page:mainForm:idSearchSetProduct:searchName')).val());
+
+    </script>
+  
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SWOSearchProduct.page-meta.xml b/scr/pages/SWOSearchProduct.page-meta.xml
new file mode 100644
index 0000000..3e8c90e
--- /dev/null
+++ b/scr/pages/SWOSearchProduct.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SWOSearchProduct</label>
+</ApexPage>
diff --git a/scr/pages/SearchManagementCode.page b/scr/pages/SearchManagementCode.page
new file mode 100644
index 0000000..f06b103
--- /dev/null
+++ b/scr/pages/SearchManagementCode.page
@@ -0,0 +1,178 @@
+<apex:page id="page" Controller="SearchManagementController" sidebar="false" showHeader="false" action="{!init}">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+    <script>
+        function doSearch() {
+            blockme();
+            serUserFaultInfo();
+        }
+
+        function saveJS() {
+            blockme();
+            save();
+        }
+
+        // 鍏抽棴瀵煎叆椤甸潰
+        function closeJs(){
+            window.parent.opener=null;
+            window.parent.open('', '_self', ''); 
+            setTimeout('window.parent.close()', 10000);
+        }
+        // 璋冪敤鐖堕〉闈㈢殑鏂规硶鍒锋柊鐖堕〉闈�
+        function refreshPage(){
+            // alert('test');
+            var ErrorNum = j$(escapeVfId("ErrorNum")).value();
+            if (parseInt(ErrorNum) != 1) {
+                //alert(parseInt(ErrorNum));
+                return;
+            }
+            var fromUserFaultInfoId = j$(escapeVfId("fromUserFaultInfoId")).value();
+            var lineno = j$(escapeVfId("lineno")).value();
+
+            // alert(fromUserFaultInfoId);
+            // alert(lineno);
+            // 
+            window.opener.refreshPage(fromUserFaultInfoId,lineno); 
+            window.close();
+        }
+    </script>
+
+    <style type="text/css">
+        div#iframelike {
+            color : #fff;
+            height : 300px;
+            overflow-y : auto;
+            overflow-x : hidden;
+        }
+    </style> 
+
+    <apex:outputPanel id="all">
+        <apex:outputPanel id="message1">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+        <apex:form id="mainForm">
+            <apex:actionFunction action="{!serUserFaultInfo}" name="serUserFaultInfo" reRender="mainForm,message1" oncomplete="unblockUI();"/>
+            <apex:actionFunction action="{!save}" name="save" reRender="mainForm,message1" oncomplete="unblockUI();refreshPage();closeJs();"/>
+            <input type="hidden" id="ErrorNum" value="{!ErrorNum}"/>
+            <input type="hidden" id="fromUserFaultInfoId" value="{!fromUserFaultInfoId}"/>
+            <input type="hidden" id="lineno" value="{!lineno}"/>
+            <!-- <input type="hidden" id="specialDealer" value="{!specialDealer}"/> -->
+            <!-- <input type="hidden" id="businessActivityId" value="{!businessActivityId}"/> -->
+            <apex:pageBlock id="idSearchSetProdcut" title="{!$Label.Product_Search}">
+                <table width="900" border="0" style="background-color:#DCDCDC">
+                    <colgroup>
+                        <col width="12"/>
+                        <col width="20"/>
+                        <col width="20"/>
+                        <col width="100"/>
+                        <col width="20"/>
+                        <col width="100"/>
+                        <col width="100"/>
+                        <col width="120"/>
+                        <col width="208"/>
+                    </colgroup>
+                    <tr>
+                        <td> </td>
+                        <th></th><!-- {!$Label.Search_Condition} -->
+                        <td> </td>
+                        <td>{!$Label.Management_Code}</td>
+                        <td> </td>
+                        <td>{!$Label.OperatingHours}</td>
+                        <td> {!$ObjectType.BusinessActivity__c.fields.BusinessAAccount__c.label}</td>
+                        <td> </td>
+                        <td></td>  
+                    </tr>
+                    <tr>
+                        <td> </td>
+                        <td> </td>
+                        <td> </td>
+                        <td>
+                            <apex:inputText id="searchManagementCode" value="{!searchManagementCode}" style="width:100px" required="false"/>
+                        </td>
+                        <td> </td>
+                        <td>
+                            <apex:inputField id="UserFaultInfoReportDate" value="{!UserFaultInfo.UserFaultInfoReportDate__c}" style="width:100" required="false"/>
+                        </td>
+                        <td>
+                            <apex:inputField id="searchAccount" value="{!UserFaultInfo.UFAccount__c }" style="width:200px" required="false"/>
+                        </td>
+                        <td><apex:commandButton value="{!$Label.Search}" onclick="doSearch();return false;" style="width:100px"/>
+                        </td>
+                        <td><apex:commandButton value="淇濆瓨" onclick="saveJS();return false;" style="width:100px"/>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td style="border-bottom: 1px solid #888;" colspan="15"></td>
+                    </tr>
+                </table>
+                <table width="900" border="0" style="background-color:#DCDCDC">
+                    <tr>
+                        <td width="12"></td>
+                        <th valign="top">{!$Label.Search_Result}</th>
+                        <td width="20"></td>
+                        <td></td>
+                    </tr>
+                    <tr>
+                        <td width="12"></td>
+                        <td>
+                            <table border="0" style="background-color:#DCDCDC">
+                                    <tr>
+                                        <td width="12"></td>
+                                        <td>
+                                            <div id="iframelike" style="width:800px">
+                                                <apex:pageBlockTable id="UserFaultInfoList" value="{!UserFaultInfoList}" var="UserFaultInfo" border="1" columns="7" columnsWidth="5px,50px,125px,90px,95px,130,210px">
+                                                    
+                                                    <apex:column >
+                                                        <apex:outputText style="display: none;" id="hidId" value="{!UserFaultInfo.Id}"/>
+                                                        
+                                                        <apex:facet name="header">&nbsp;&nbsp;</apex:facet>
+                                                        <apex:inputCheckbox value="{!UserFaultInfo.UserFaultInfoBeSelected__c}" style="width:10px;"/>
+                                                    </apex:column>
+
+                                                    <apex:column >
+                                                        <apex:facet name="header">{!$ObjectType.User_FaultInfo__c.fields.UFManagementCode__c.label}</apex:facet>
+                                                        <apex:outputField id="UFManagementCode" value="{!UserFaultInfo.UFManagementCode__c}" />
+                                                    </apex:column> 
+
+                                                   
+                                                     <apex:column >
+                                                        <apex:facet name="header">鐢ㄦ埛鍗曚綅鍚嶇О</apex:facet>
+                                                        <apex:outputField id="UserFaultInfoCustomerUnit__c" value="{!UserFaultInfo.UserFaultInfoCustomerUnit__c}" />
+                                                    
+                                                    </apex:column> 
+                                                     <apex:column >
+                                                        <apex:facet name="header">鏈哄瀷</apex:facet>
+                                                        <apex:outputField id="UserFaultInfoModel__c" value="{!UserFaultInfo.UserFaultInfoModel__c}" />
+                                                    
+                                                    </apex:column> 
+                                                     <apex:column >
+                                                        <apex:facet name="header">鏁呴殰鍐呭</apex:facet>
+                                                        <apex:outputField id="UFFaultContent__c" value="{!UserFaultInfo.UFFaultContent__c}" />
+                                                    
+                                                    </apex:column> 
+                                                     <apex:column >
+                                                        <apex:facet name="header">{!$ObjectType.User_FaultInfo__c.fields.UserFaultInfoServiceContent__c.label}</apex:facet>
+                                                        <apex:outputField id="BusinessAServiceContent" value="{!UserFaultInfo.UserFaultInfoServiceContent__c}" />
+                                                    
+                                                    </apex:column> 
+
+                                                </apex:pageBlockTable>
+                                            </div>
+                                        </td>
+                                    </tr>
+                                </table>
+                            </td>
+                        <td width="20"></td>
+                        <td></td>
+                    </tr>
+                </table>
+            </apex:pageBlock>
+
+        </apex:form>
+    </apex:outputPanel>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SearchManagementCode.page-meta.xml b/scr/pages/SearchManagementCode.page-meta.xml
new file mode 100644
index 0000000..30b9c84
--- /dev/null
+++ b/scr/pages/SearchManagementCode.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>49.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SearchManagementCode</label>
+</ApexPage>
diff --git a/scr/pages/SearchMemberPage.page b/scr/pages/SearchMemberPage.page
new file mode 100644
index 0000000..4767d57
--- /dev/null
+++ b/scr/pages/SearchMemberPage.page
@@ -0,0 +1,133 @@
+<apex:page id="Page" Controller="SearchMemberPageController" sidebar="false" showHeader="false" action="{!init}">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+	<style type="text/css">
+		
+	</style>
+	<script>
+		function doSearchJS(){
+			blockme();
+			var searchByName = j$(escapeVfId("searchByName")).value();
+			var searchByAccount = j$(escapeVfId("searchByAccount")).value();
+			DoSearch(searchByName,searchByAccount);
+		}
+		function saveJS(){
+			blockme();
+			save();
+		}
+		//璇诲彇鏁版嵁锛岃皟鐢ㄧ埗椤甸潰鍒锋柊鏂规硶
+		function refreshPage(){
+			var isError = j$(escapeVfId("isError")).value();
+			if(isError == "true"){ 	
+				return;
+			}
+			var lineNum = j$(escapeVfId("lineNum")).value();
+			var memberId = j$(escapeVfId("memberId")).value();
+			var memberName = j$(escapeVfId("memberName")).value();
+			var memberEmail = j$(escapeVfId("memberEmail")).value();
+			window.opener.refreshPage(lineNum,memberId,memberName,memberEmail); 
+            window.close();
+		}
+		function closeJS(){
+			/*window.parent.opener=null;
+            window.parent.open('', '_self', ''); 
+            setTimeout('window.parent.close()', 10000);*/
+		}
+		function hiddenObj(){
+			var memberType = j$(escapeVfId('Page:allData:memberType')).value();
+			if(memberType == "User"){
+				j$(escapeVfId("accountLable")).attr("style","display:none");
+				j$(escapeVfId("dataAccount")).attr("style","display:none");
+			}
+			if(memberType == "Contact"){
+				j$(escapeVfId("accountLable")).attr("style","display:block");
+				j$(escapeVfId("dataAccount")).attr("style","display:block");
+			}
+		}
+	</script>
+	 <div style="width: 100%;height: 100%;">
+	 	<apex:outputPanel id="message1">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+	 	<apex:form id="allData">
+	 		<apex:actionFunction action="{!SearchMember}" name="DoSearch" reRender="result" oncomplete="unblockUI();">
+	 			<apex:param assignTo="{!searchByName}" name="searchByName" value=""></apex:param>
+	 			<apex:param assignTo="{!searchByAccount}" name="searchByAccount" value=""></apex:param>
+	 		</apex:actionFunction>
+	 		<apex:actionFunction action="{!save}" name="save" reRender="allData,message1" oncomplete="unblockUI();refreshPage();closeJS();">
+	 		</apex:actionFunction>
+	 		<input type="hidden" id="isError" value="{!isError}" />
+	 		<input type="hidden" id="lineNum" value="{!lineNum}" />
+	 		<input type="hidden" id="memberId" value="{!memberId}" />
+	 		<input type="hidden" id="memberName" value="{!memberName}" />
+	 		<input type="hidden" id="memberEmail" value="{!memberEmail}" />
+	 			
+	 			<table style="width: 100%;">
+	 				<colgroup>
+	 					<col style="width: 20%" />
+	 					<col style="width: 40%" />
+	 					<col style="width: 40%" />
+	 				</colgroup>
+	 				<tr>
+	 					<th colspan="3">
+	 						<apex:selectList onchange="hiddenObj()" id="memberType" value="{!memberType}" size="1">
+	 							<!-- <apex:selectOptions value="{!items}"></apex:selectOptions> -->
+	 							<apex:selectOption itemLabel="澶栭儴鐢ㄦ埛鑱旂郴浜�" itemValue="Contact"></apex:selectOption>
+	 							<apex:selectOption itemLabel="濂ユ灄宸存柉鍐呴儴鐢ㄦ埛" itemValue="User"></apex:selectOption>
+	 						</apex:selectList>
+						</th>
+					</tr>
+					<tr>
+	 					<th style="text-align:center;"><apex:commandButton value="Search" onclick="doSearchJS();return false;" />&nbsp;&nbsp;<apex:commandButton value="Save" onclick="saveJS();return false;"/></th>
+
+	 					<th id="nameLable" style="text-align:center;">Name锛�<input id="searchByName"  type="text" value="{!searchByName}" /></th>
+
+						<th style="text-align:center;"><div id="accountLable">Account锛�<input id="searchByAccount"  type="text" value="{!searchByAccount}" /></div></th>
+	 					
+	 				</tr> 	
+	 			</table>
+	 			<apex:outputPanel id="result">
+		 			<table>
+		 				<colgroup>
+		 					<col style="width: 10%" />
+		 					<col style="width: 20%" />
+		 					<col style="width: 30%" />
+		 					<col style="width: 40%" />
+		 				</colgroup>
+		 				<tr>
+		 					<th style="text-align:center;">
+		 						RESULT
+		 					</th>
+		 					<th colspan="2">
+		 					</th>
+		 				</tr>
+		 				<tr>
+		 					<th></th>
+		 					<th>NAME</th>
+		 		 			<th>EMAIL</th>
+		 		 			<th>ACCOUNT</th>
+		 		 			<!-- <apex:outputPanel layout="none" rendered="{!IF(memberType == 'Contact', true, false)}">
+		 						<th>ACCOUNT</th>
+		 		 			</apex:outputPanel>
+		 		 			<apex:outputPanel layout="none" rendered="{!IF(memberType == 'User', true, false)}">
+		 						<th></th>
+		 		 			</apex:outputPanel> -->
+		 				</tr>
+		 				<apex:repeat value="{!lineList}" var="line">
+			 				<tr>
+			 					<td style="text-align:right;">
+			 						<apex:inputCheckbox id="checkbox" value="{!line.check}" />
+			 					</td>
+			 					<td><apex:outputText value="{!line.name}"></apex:outputText></td>
+			 					<td><apex:outputText value="{!line.email}"></apex:outputText></td>
+			 					<td><apex:outputText value="{!line.account}"></apex:outputText></td>
+			 				</tr>
+		 				</apex:repeat>
+		 			</table>
+	 			</apex:outputPanel>
+	 	</apex:form>
+	 </div>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SearchMemberPage.page-meta.xml b/scr/pages/SearchMemberPage.page-meta.xml
new file mode 100644
index 0000000..3209565
--- /dev/null
+++ b/scr/pages/SearchMemberPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SearchMemberPage</label>
+</ApexPage>
diff --git a/scr/pages/SearchProduct.page b/scr/pages/SearchProduct.page
new file mode 100644
index 0000000..b559e10
--- /dev/null
+++ b/scr/pages/SearchProduct.page
@@ -0,0 +1,269 @@
+<apex:page id="Page" Controller="SearchProductController" sidebar="false" showHeader="false" action="{!init}">
+  <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+    <script>
+       var QuoteEntryMaxLine = 150;
+         
+       function setProductList() {
+            var nextLine = top.window.opener.getLastLineNoNext(window.opener.document);
+            var hasCheckedCnt = 0;
+            var checklist = j$("input[name='checklist']");
+
+            // var is_hidden_all = j$(escapeVfId("isHiddenAllsearch")).val();
+            //alert('is_hidden_all=====>'+ is_hidden_all);
+
+            for(var i=0; i<checklist.length; i++){
+                    if (checklist[i].checked) {
+                        hasCheckedCnt++;
+                        if (nextLine < QuoteEntryMaxLine) {
+                            SetProductId(nextLine, i);
+                            nextLine++;
+                        } else {
+                            //alert('Over Max Line ' + QuoteEntryMaxLine);
+                            return false;
+                        }
+                    }
+            }
+            if (hasCheckedCnt == 0) {
+                alert(top.window.opener.Error_Message34);
+                return false;
+            }
+            window.opener.doReroad();
+            top.window.close();
+        }
+
+        function setProductOne(lineno, i) {
+            SetProductId(lineno, i);
+            window.opener.doReroad();
+            top.window.close();
+        }
+
+        function doSearch() {
+            blockme();
+            serContact.call();
+        }
+
+        function SetProductId(lineno, i) {
+
+          var ProductCode = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":ProductCode")).text();
+            if (ProductCode.indexOf('0000000000') == 0) {
+                ProductCode = ProductCode.substring(10);
+            }
+            var ProductECCode = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":ProductECCode")).text();
+          var name = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":Name")).text();
+
+          var PbeId = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":hidId")).text();
+            var pId = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":pId")).text();
+            //XHL-20190428-UpdateStart
+            // var productSet = j$(escapeVfId("Page:mainForm:idSearchSetProduct:productSet")).val();
+            // var productSetLabel = j$(escapeVfId("Page:mainForm:idSearchSetProduct:productSet") + ' option:selected').text();
+            //XHL-20190428-UpdateEnd
+            var salesprice = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":Salesprice")).text();
+            var salespriceA = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":SalespriceA")).text();
+            var salespriceB = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":SalespriceB")).text();
+            var salespriceC = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":SalespriceC")).text();
+            var pm = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":ProductModel")).text();
+            var productDescription = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":ProductDescription")).text();
+            var salespriceR = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":SalespriceR")).text();
+            var hiddenflg = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+ i +":Hiddenflg")).text();
+            var is_hidden_all = j$(escapeVfId("isHiddenAllsearch")).val();
+            var specialDealer = j$(escapeVfId("specialDealer")).val();
+            //alert('Salesprice=====>'+ salesprice);
+            var openFlag = j$(escapeVfId("openFlag")).val();
+            if (openFlag == 'opp') {
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:" + (lineno - 1) + ":product")).val(name);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:" + (lineno - 1) + ":productId")).val(pId);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:" + (lineno - 1) + ":isProductModel")).val(pm);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":price0")).val(salesprice);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":unitPrice")).val(salespriceR);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":hiddenflg")).val(hiddenflg);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":description")).val(productDescription);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":productCode")).text(ProductCode);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":productCodeHidden")).val(ProductCode);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":productEC")).text(ProductECCode);
+                window.opener.j$(escapeVfId("allPage:allForm:allBlock:records:"+ (lineno - 1) +":productECHidden")).val(ProductECCode);
+                if (specialDealer == 'true') {
+                    window.opener.j$(escapeVfId("isHiddenAll")).val(is_hidden_all);
+                }
+                
+                
+            } else {
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":indexNo")).text(parseInt(lineno)+1);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":ProductName")).val(name);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":ProductCode")).text(ProductCode);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":ProductCodeHidden")).val(ProductCode);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":ProductEC")).text(ProductECCode);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":ProductECHidden")).val(ProductECCode);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":PbeId")).val(PbeId);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":ProId")).val(pId);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":UnitPrice")).val(salespriceR);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":hiddenflg")).val(hiddenflg);
+                //window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":UnitPriceHidden")).val(salesprice);
+                //XHL-20190428-UpdateStart
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":Set")).text('{!$Label.SingleProduct}');
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":SetName")).val('{!$Label.SingleProduct}');
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":SingleProduct")).val('true');
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":hidSet")).val('{!$Label.SingleProduct}');
+                //XHL-20190428-UpdateEnd
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":price0")).val(salesprice);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":price1")).val(salespriceA);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":price2")).val(salespriceB);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":price3")).val(salespriceC);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":Distingush")).val(null);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":isProductModel")).val(pm);
+                window.opener.j$(escapeVfId("Page:mainForm:block:lists:"+ lineno +":Description")).val(productDescription);
+
+                if (specialDealer == 'true') {
+                    window.opener.j$(escapeVfId("isHiddenAll")).val(is_hidden_all);
+                }
+            }
+
+        }
+
+    </script>
+    
+    <style type="text/css">
+        div#iframelike {
+            color: #fff;
+            height: 300px;
+            overflow-y: auto;
+            overflow-x: hidden;
+        }
+    </style>
+    <apex:outputPanel id="all">
+        <apex:outputPanel id="message1">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+        <apex:form id="mainForm">
+
+            <apex:actionFunction action="{!serContact}" name="serContact" reRender="mainForm,message1" oncomplete="unblockUI();"/>
+
+            <input type="hidden" id="openFlag" value="{!openFlag}"/>
+            <input type="hidden" value="{!is_hidden_all}" id="isHiddenAllsearch"/>
+            <input type="hidden" value="{!specialDealer}" id="specialDealer"/>
+            <apex:pageBlock id="idSearchSetProduct" title="{!$Label.Product_Search}">
+                <table width="900" border="0" style="background-color:#DCDCDC">
+                    <colgroup>
+                        <col width="12" />
+                        <col width="20" />
+                        <col width="20" />
+                        <col width="200" />
+                        <col width="20" />
+                        <col width="100" />
+                        <col width="120" />
+                        <col width="208" />
+                    </colgroup>
+                    <tr>
+                        <td> </td>
+                        <th>{!$Label.Search_Condition}</th>
+                        <td> </td>
+                        <th>{!$Label.Asset_No}</th>
+                        <td> </td>
+                        <td> </td>
+                        <td> </td>
+                        <td> </td>
+                    </tr>
+                    <tr>
+                        <td> </td>
+                        <td> </td>
+                        <td> </td>
+                        <td><apex:inputText id="searchName" value="{!SearchName}" style="width:200px" required="false"/></td>
+                        <td><apex:commandButton value="{!$Label.Search}" onclick="doSearch();return false;" style="width:100px" /></td>
+                        <!-- XHL-20190428-UpdateStart -->
+             <!--            <th style="text-align:right;width:90px;"><apex:outputLabel value="{!$ObjectType.QuoteLineItem.fields.Set__c.label}" rendered="{!oppflg}"/></th>
+                        <td><apex:selectList id="productSet" value="{!productSetVal}" rendered="{!oppflg}" size="1" style="width:100px;float:right;">
+                            <apex:selectOptions value="{!productSet}"/>
+                            </apex:selectList>
+                        </td> -->
+                        <!-- XHL-20190428-UpdateEnd -->
+                        <td> <apex:commandButton value="{!$Label.Add_Product}" rendered="{!oppflg}" style="width:100px;float:right;" disabled="{!Hascl}" rerender="dummy" onclick="setProductList();return false;"/></td>
+                    </tr>
+                    <tr>
+                        <td style="border-bottom: 1px solid #888;" colspan="15"> </td>
+                    </tr>
+                </table>
+                <table width="900" border="0" style="background-color:#DCDCDC">
+                    <tr>
+                        <td width="12"> </td>
+                        <th valign="top">{!$Label.Search_Result}</th>
+                        <td width="20"> </td>
+                        <td>
+                            <table border="0">
+                                <tr>
+                                    <td>
+                                    <div id="iframelike" style="width:800px">
+                                    <apex:pageBlockTable id="idRezultVisitor" value="{!cl}" var="c" border="1" columns="7" columnsWidth="25px,125px,125px,90px,95px,130,210px">
+
+                                        <apex:column style="width:15px;" >
+                                            <apex:outputText style="display: none;" id="hidId" value="{!c.pbeId}"/>
+                                            <apex:outputText style="display: none;" id="pId" value="{!c.pbe.Product__c}"/>
+                                            <apex:facet name="header">{!$Label.Selected}</apex:facet>
+                                            <input type="checkbox" name="checklist" value="" style="width:10px;"/>
+                                        </apex:column>
+
+                                        <apex:column >
+                                            <apex:facet name="header">{!$ObjectType.Product_Search__c.fields.name.label}</apex:facet>
+                                            <apex:outputText style="display: none;" id="Name" value="{!c.pbe.Name}" />
+                                            <apex:outputLink id="NameLink" value="#" onclick="setProductOne('{!lineno}','{!c.idx}');return false;">{!c.pbe.Name}</apex:outputLink>
+                                        </apex:column> 
+
+                                        <apex:column >
+                                            <apex:facet name="header">{!$ObjectType.Product_Search__c.fields.ProductCode__c.Label}</apex:facet>
+                                            <apex:outputField id="ProductCode" value="{!c.pbe.ProductCode__c}" />
+                                        </apex:column>
+
+                                        <apex:column >
+                                            <apex:facet name="header">{!$ObjectType.Product_Search__c.fields.Product_ECCode__c.Label}</apex:facet>
+                                            <apex:outputField id="ProductECCode" value="{!c.pbe.Product_ECCode__c}" />
+                                        </apex:column>
+
+                                        <apex:column >
+                                            <apex:facet name="header">{!$ObjectType.Product_Search__c.fields.ProductModels1__c.Label}</apex:facet>
+                                            <apex:outputField id="ProductModels" value="{!c.pbe.ProductModels1__c}" />
+                                            <apex:outputText id="ProductModel" value="{!c.pbe.ProductModels1__c}" style="display: none;"/>
+                                        </apex:column>
+
+                                        <apex:column >
+                                            <apex:facet name="header">{!$ObjectType.PricebookEntry.fields.SalesPrice__c.label}</apex:facet>
+                                            <apex:outputText id="SalespriceR" value="{!c.salespriceR}" />
+                                            <apex:outputText id="Salesprice" value="{!c.salesprice}" style="display: none;"/>
+                                            <apex:outputText id="SalespriceA" value="{!c.salespriceA}" style="display: none;"/>
+                                            <apex:outputText id="SalespriceB" value="{!c.salespriceB}" style="display: none;"/>
+                                            <apex:outputText id="SalespriceC" value="{!c.salespriceC}" style="display: none;"/>
+                                            <apex:outputText id="Hiddenflg" value="{!c.hiddenflg}" style="display: none;"/>
+                                        </apex:column> 
+
+<!--                                         <apex:column >
+                                         <apex:facet name="header">{!$ObjectType.PricebookEntry.fields.Pricebook2Id.label}</apex:facet>
+                                            <apex:outputText id="Pricebook" value="{!c.pbId}" /> 
+                                        </apex:column> -->
+
+                                         <apex:column >
+                                            <apex:facet name="header">{!$ObjectType.Product_Search__c.fields.ProductDescription__c.label}</apex:facet>
+                                            <apex:outputField id="ProductDescription" value="{!c.pbe.ProductDescription__c}" />
+                                        </apex:column> 
+
+                                         
+                                    </apex:pageBlockTable>
+                                    </div>
+                                    </td>
+                                </tr>
+                            </table>
+                        </td>
+                    </tr>
+                </table>
+            </apex:pageBlock>
+        </apex:form>
+    </apex:outputPanel>
+    <script type="text/javascript">
+        // 銉曘偐銉笺偒銈广偦銉冦儓
+        j$(escapeVfId('Page:mainForm:idSearchSetProduct:searchName'))[0].focus();
+        j$(escapeVfId('Page:mainForm:idSearchSetProduct:searchName')).val(j$(escapeVfId('Page:mainForm:idSearchSetProduct:searchName')).val());
+
+    </script>
+  
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SearchProduct.page-meta.xml b/scr/pages/SearchProduct.page-meta.xml
new file mode 100644
index 0000000..1749c5b
--- /dev/null
+++ b/scr/pages/SearchProduct.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SearchProduct</label>
+</ApexPage>
diff --git a/scr/pages/SearchSetProduct.page b/scr/pages/SearchSetProduct.page
new file mode 100644
index 0000000..26fb065
--- /dev/null
+++ b/scr/pages/SearchSetProduct.page
@@ -0,0 +1,180 @@
+<apex:page id="Page" standardController="productSet__c" extensions="SearchSetProductController" sidebar="false" showHeader="false" action="{!init}">
+<!-- XHL-20190426-AddStart -->
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <script type="text/javascript">
+
+        function SelectDoneJS(){
+            SelectDone();
+            // alert('1111111111');
+            // SetMuiltProduct();
+        }
+
+        function SetMuiltProduct(){
+
+            
+
+            var Str = j$(escapeVfId("Page:mainForm:setPFString")).value();
+            // alert(Str);
+            var Size = j$(escapeVfId("activitiesSize")).value();
+            var productSetNames = '';
+            var flag = '0';
+            var errorFlag = false;
+            var errorMsg = '';
+            for (var i= 0; i < Size ;i++) {
+                var Checkbox = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+i+":Checkbox")).value();
+                var quantity = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+i+":Quantity")).value();
+                var QuantityReference = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+i+":QuantityReference")).value();
+                var Discount = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+i+":Discount")).value();
+                var Name = j$(escapeVfId("Page:mainForm:idSearchSetProduct:idRezultVisitor:"+i+":Name")).value();
+                if (Checkbox == 'on') {
+
+                    if (parseFloat(Discount).toString() == "NaN" || parseFloat(Discount) <= 0 || 
+                        parseFloat(quantity).toString() == "NaN" || quantity.indexOf(".") != -1 || 
+                        parseFloat(quantity) < 0 || (quantity == 0 && quantity == QuantityReference) ) {
+                        errorFlag = true;
+
+                        if (errorMsg == '') {
+                            errorMsg = Name;
+                        } else {
+                            errorMsg = errorMsg + ',' +Name;
+                        }
+                    }
+
+                    if (quantity == 0 && quantity != QuantityReference ) {
+                        flag = '1';
+                        if (productSetNames == '') {
+                            productSetNames = Name;
+                        } else {
+                            productSetNames += ';' + Name;
+                        }
+                    } 
+                    
+                }
+            }
+            if (errorFlag) {
+                alert('鎮ㄥ凡閫夋嫨[ '+errorMsg+' ]浜у搧閰嶅,灏氭湭濉啓鏈夋晥鏁板瓧,璇风‘璁�');
+                return;
+            }
+            if (flag == '1') {
+                if(confirm("鎮ㄥ嵆灏嗗垹闄�"+productSetNames+"锛岀‘璁ゅ畬鎴愪箞锛�")){
+                    
+                    top.window.opener.setProductEntryGateway(Str);
+                    top.window.close();
+                    return;
+                }else{
+                    return;
+                }
+            }
+            
+
+            if(Str==''||Str==null){
+                if(confirm("鎮ㄥ皻鏈�夊彇浠讳綍浜у搧閰嶅锛岀‘璁ゅ畬鎴愪箞锛�")){
+                    top.window.opener.setProductEntryGateway(Str);
+                    top.window.close();
+                }else{
+                }
+            }else{
+                 top.window.opener.setProductEntryGateway(Str);
+                 top.window.close();
+            } 
+            
+        }
+        
+    </script>
+    <style type="text/css">
+        div#iframelike {
+            color: #fff;
+            height: 300px;
+            overflow-y: auto;
+            overflow-x: hidden;
+        }
+    </style>
+    <apex:outputPanel id="all">
+        <apex:form id="mainForm">
+        <apex:actionFunction action="{!SelectDone}" name="SelectDone" reRender="setPFString" oncomplete="SetMuiltProduct();"/>
+        <apex:inputHidden value="{!setPFString}" id="setPFString"/>
+        <input type="hidden" id="activitiesSize" value="{!activitiesSize}" />
+            <apex:pageBlock id="idSearchSetProduct" title="{!$Label.Product_Assort_Search}">
+
+                <table width="900" border="0" style="background-color:#DCDCDC">
+                    <colgroup>
+                        <col width="12" />
+                        <col width="20" />
+                        <col width="20" />
+                        <col width="200" />
+                        <col width="200" />
+                        <col width="200" />
+                        <col width="100" />
+                        <col width="128" />
+                    </colgroup>
+                    
+                    <tr>
+                        <td>&nbsp;</td>
+                        <th>{!$Label.Search_Condition}</th>
+                        <td>&nbsp;</td>
+                        <th>{!$Label.Set_Name}</th>
+                        <th>{!$Label.Set_Code}</th>
+                        <td>&nbsp;</td>
+                        <td>&nbsp;</td>
+                    </tr>
+                    <tr>
+                        <td>&nbsp;</td>
+                        <td>&nbsp;</td>
+                        <td>&nbsp;</td>
+                        <td><apex:inputText value="{!SearchName}" style="width:150px" required="false"/></td>
+                        <td><apex:inputText value="{!SearchCode}" style="width:150px" required="false"/></td>
+                        
+                        <td><apex:commandButton value="{!$Label.Search}" action="{!serContact}" style="width:100px" rerender="idRezultVisitor" /></td>
+                        <!-- <td><apex:commandButton value="娣诲姞" onclick="SelectDone()" style="width:100px"/></td> -->
+                        <td><apex:commandButton value="娣诲姞" onclick="SelectDoneJS();return false;" style="width:100px"/></td>
+                    </tr>
+                    <tr>
+                        <td style="border-bottom: 1px solid #888;" colspan="15">&nbsp;</td>
+                    </tr>
+                </table>
+                <table width="900" border="0" style="background-color:#DCDCDC">
+                    <tr>
+                        <td width="12">&nbsp;</td>
+                        <th valign="top">{!$Label.Search_Result}</th>
+                        <td width="20">&nbsp;</td>
+                        <td>
+                            <table border="0">
+                                <tr>
+                                    <td>
+                                    <div id="iframelike" style="width:770px">
+                                        <apex:pageBlockTable id="idRezultVisitor" value="{!activities}" var="c" border="1" columns="7" columnsWidth="30px,120px,300px,90x,200px,50px">
+                                            <apex:column >
+                                                <apex:facet name="header">閫夋嫨</apex:facet>
+                                                <apex:inputCheckbox value="{!c.isSelected}" id="Checkbox"/>
+                                            </apex:column>
+                                            <apex:column >
+                                                <apex:facet name="header">{!$Label.Set_Name}</apex:facet>
+                                                <apex:outputText value="{!c.Name}" id="Name"/>   
+                                            </apex:column>
+                                            <apex:column >
+                                                <apex:facet name="header">{!$Label.Set_Code}</apex:facet>
+                                                <apex:outputText value="{!c.Code}" />
+                                            </apex:column>
+                                            <apex:column >
+                                                <apex:facet name="header">{!$Label.Quantity}</apex:facet>
+                                                <apex:InputText value="{!c.Quantity}" Id="Quantity"/>
+                                                <apex:inputHidden id="QuantityReference" value="{!c.QuantityReference}"/>
+                                            </apex:column>
+                                            <apex:column >
+                                                <apex:facet name="header">鎶樻墸</apex:facet>
+                                                <apex:InputText value="{!c.Discount}" Id="Discount"/>
+                                            </apex:column>
+                                            
+                                        </apex:pageBlockTable>
+                                    </div>
+                                    </td>
+                                </tr>
+                            </table>
+                        </td>
+                    </tr>
+                </table>
+            </apex:pageBlock>
+        </apex:form>
+    </apex:outputPanel>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SearchSetProduct.page-meta.xml b/scr/pages/SearchSetProduct.page-meta.xml
new file mode 100644
index 0000000..690b0a5
--- /dev/null
+++ b/scr/pages/SearchSetProduct.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SearchSetProduct</label>
+</ApexPage>
diff --git a/scr/pages/SendEmail.page b/scr/pages/SendEmail.page
new file mode 100644
index 0000000..c6a373f
--- /dev/null
+++ b/scr/pages/SendEmail.page
@@ -0,0 +1,340 @@
+<apex:page id="Page" standardController="Mail_Merge__c" extensions="SendEmailController" sidebar="false" showHeader="false" action="{!init}" title="SendEmail">
+
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"/>
+    <style type="text/css"> 
+        .tableCss{
+            width: 100%;
+            border: 0;
+        }
+        .errorMessage{
+            font-size: 15px;
+            color:#FF0000;
+        }
+        .title{
+            height: 30px;
+            background-color: #DFE6F0;
+        }
+        .title font{
+            font-size:15px;
+            color:#607799;
+        }
+    </style>
+    <script>
+
+        function formSubmit(){
+            testFile();
+        }
+        function openPDF(){
+            //var typeId = "{!mail.RECORD__c}";
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            window.open(baseUrl + '/apex/QuotesPDF?id={!mail.RECORD__c}');
+        }
+        function openSearchMemberPage(lineNum){
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            //var repairId = j$(escapeVfId("repairId")).value();
+            window.open(baseUrl + '/apex/SearchMemberPage?lineNum='+lineNum,'pselect', 'width=600,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+        function refreshPage(lineNum,memberId,memberName,memberEmail){
+            /*var memberNameId = "memberName"+lineNum;
+            var memberEmailId = "memberEmail"+lineNum;
+            j$(escapeVfId(memberNameId)).attr("value",memberName);
+            j$(escapeVfId(memberEmailId)).attr("value",memberEmail);*/
+            addMemberData(lineNum,memberId,memberName,memberEmail);
+        }
+        function statusChabge(linenumNum,type){
+            var toId = "Page:messageForm:lineDataList:"+linenumNum+":"+"to";
+            var ccId = "Page:messageForm:lineDataList:"+linenumNum+":"+"cc";
+            var bccId = "Page:messageForm:lineDataList:"+linenumNum+":"+"bcc";
+            var toValue = j$(escapeVfId(toId)).value();
+            var ccValue = j$(escapeVfId(ccId)).value();
+            var bccValue = j$(escapeVfId(bccId)).value();
+            j$(escapeVfId(toId)).attr("checked",false);
+            j$(escapeVfId(ccId)).attr("checked",false);
+            j$(escapeVfId(bccId)).attr("checked",false);
+            //杩欎釜if鍒ゆ柇锛屼繚璇佷笁涓敹浠朵汉绫诲瀷鏈変竴涓椂閫変腑鐨勶紝涓嶅彲浠ヤ笁涓兘涓轰笉鍕鹃��
+            //if(toValue == ""&&ccValue==""&&bccValue==""){
+                if(type == "to"){
+                    j$(escapeVfId(toId)).attr("checked",true);
+                }
+                if(type == "cc"){
+                    j$(escapeVfId(ccId)).attr("checked",true);
+                }
+                if(type == "bcc"){
+                    j$(escapeVfId(bccId)).attr("checked",true);
+                }
+            //}
+            //涓嬭竟涓変釜if锛屼笁涓嬀閫夋浜掓枼锛屽彧鑳藉嬀閫変竴涓�
+            /*if(type == "to"){
+                j$(escapeVfId(ccId)).attr("checked",false);
+                j$(escapeVfId(bccId)).attr("checked",false);
+            }
+            if(type == "cc"){
+                j$(escapeVfId(toId)).attr("checked",false);
+                j$(escapeVfId(bccId)).attr("checked",false);
+            }
+            if(type == "bcc"){
+                j$(escapeVfId(toId)).attr("checked",false);
+                j$(escapeVfId(ccId)).attr("checked",false);
+            }*/
+        }
+
+        //dialog 寮圭獥 start 
+        var popupBox;
+            popupBox = new SimpleDialog("SpeedDialogId", false);  // 涓嶅彲鎷栧姩
+            popupBox.createDialog();        
+        function openFile(){
+            // alert('111111111');
+            // uploadFileS();
+            popupBox.setTitle("璇烽�夋嫨瑕佷笂浼犵殑鍥剧墖锛�");
+            popupBox.importContentNode(document.getElementById("Page:messageForm:popupBox"));
+            popupBox.show(document.getElementById("Page:messageForm:popupBox"));
+            document.getElementById("Page:messageForm:popupBox").style.display = 'block';
+           
+
+        }
+        //dialog 寮圭獥 end 
+        
+        //涓婁紶鍥剧墖
+            function saveAttachment(){
+                 var maxFileSize = 4350000;      //Base64 缂栫爜浠ュ悗鏈�澶х殑鏂囦欢瀛楄妭鏁�
+                 var attachmentBody;                //闄勪欢鍐呭
+                 var attachmentName;                //闄勪欢鍚嶇О
+                 var attachmentType;                //闄勪欢鍚嶇О
+                 var attachmentSize;                //闄勪欢澶у皬
+                 var parentId = j$(escapeVfId("parentId")).value();
+                 // 鑾峰彇涓婁紶鍥剧墖鐨勬暟閲�
+                 var size = document.getElementById("file_input").files.length;
+                 if (size > 0) {
+                    var nameList = [];
+                    var typeList = [];
+                    var bodyList = [];
+                    for(var i = 0;i < size;i++){
+                        var fbody = document.getElementById("file_input").files[i];
+                        attachmentName = fbody.name;
+                        if(fbody.size <= maxFileSize) {
+                            attachmentType = fbody.type;
+                            nameList.push(attachmentName);
+                            typeList.push(attachmentType);
+                            var fileReader = new FileReader();
+                            fileReader.readAsBinaryString(fbody);
+                            fileReader.onload = function(e) {
+                                bodyList.push(window.btoa(this.result));
+                            }
+                            fileReader.onerror = function(e) {
+                                alert("涓婁紶澶辫触锛岃閲嶆柊灏濊瘯");
+                            }
+                            fileReader.onabort = function(e) {
+                                alert("涓婁紶澶辫触锛岃閲嶆柊灏濊瘯");
+                            }
+                        } else {
+                            alert("Base64 缂栫爜鏈�澶у厑璁�4.3M鏂囦欢,"+attachmentName + '杩囧ぇ鏃犳硶涓婁紶');
+                        }
+
+
+                    }
+                    if (nameList.length > 0) {
+                         //浣跨敤RemoteAction涓婁紶闄勪欢
+                         Visualforce.remoting.Manager.invokeAction(
+                           '{!$RemoteAction.SendEmailController.AddAttachment}',
+                           nameList,
+                           typeList,
+                           bodyList,
+                           parentId,
+                           function(result,event) {
+                               
+                             if(result == '鏂囦欢涓婁紶鎴愬姛'){
+                                alert(result); 
+                                RefreshPage();
+                             } else if (result == null){
+                                result = '鏂囦欢涓婁紶澶辫触,璇烽噸鏂颁笂浼�';
+                                alert(result); 
+                                RefreshPage();
+                             } else {
+                                alert(result); 
+                             }
+                             
+                           });
+ 
+                    }
+                    
+                 }
+                 
+                 
+            }
+    </script>
+    <div style="width : 100%;">
+    <div style="width : 70%; margin: auto;">
+        <apex:form id="messageForm">
+            <input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+            <input type="hidden" id="parentId" value="{!Id}"/>
+            <input type="hidden" id="isOnClick" value="{!isOnClick}"/>
+            <apex:actionFunction name="addMemberData" action="{!addMemberData}" reRender="messageForm">
+                <apex:param name="lineNum" assignTo="{!lineNum}" value="" />
+                <apex:param name="memberId" assignTo="{!memberId}" value="" />
+                <apex:param name="memberName" assignTo="{!memberName}" value="" />
+                <apex:param name="memberEmail" assignTo="{!memberEmail}" value="" />
+            </apex:actionFunction>
+            <!-- 鍥剧墖鎵归噺涓婁紶 淇濆瓨Email -->
+             <apex:actionFunction name="uploadFileS" action="{!uploadFileS}" reRender="messageForm" oncomplete="openFile();"/>
+             <!-- 鍥剧墖鎵归噺涓婁紶 鍒锋柊椤甸潰 -->
+              <apex:actionFunction name="RefreshPage"  action="{!RefreshPage}" reRender="messageForm"/>
+            <apex:actionFunction name="deleteFile" reRender="fileForm">
+                <!-- <apex:param name="lineNum" assignTo="{!lineNum}" value="" /> -->
+            </apex:actionFunction>
+
+            <div style="width: 100%">
+                <div class="errorMessage" style="margin-left: 39%">
+                    <span id="errorMessage">{!errorMessage}</span>
+                </div>
+            </div>
+
+            <div style="width: 100%;">
+                <table class="tableCss">
+                    <tr class="title">
+                        <th colspan="2"><font>Recipients</font></th>
+                    </tr>
+                    <tr>
+                        <th style="width: 20%;text-align:center;">FROM:</th>
+                        <td><apex:outputText value="{!mail.FROM__c}" style="width: 40%"/></td>
+                    </tr>
+                </table>
+            </div>
+            <div style="width: 50%;margin-left: 20%;">
+                <!-- style="border:1px solid #000000;" -->
+                <table class="tableCss">
+                    <thead>
+                        <tr>
+                            <th style="width: 25%;text-align:center;">email</th>
+                            <th style="width: 10%;text-align:center;">name</th>
+                            <th style="width: 5%;text-align:center;">TO</th>
+                            <th style="width: 5%;text-align:center;">CC</th>
+                            <th style="width: 5%;text-align:center;">BCC</th>
+                            <th style="width: 5%;text-align:center;"></th>
+                        </tr>
+                    </thead>
+                    <tbody id="memberBody">
+                        <apex:repeat id="lineDataList" value="{!memberLineDatas}" var="lineData">
+                            <tr style="text-align:center;">
+                                <td>
+                                <input type="hidden" id="memberName{!lineData.lineNum}" value="{!lineData.name}" />
+                                <apex:inputText value="{!lineData.emailAddress}" /></td>
+                                <td><apex:inputText value="{!lineData.name}" /></td>
+                                <td><apex:inputCheckbox onclick="statusChabge({!lineData.lineNum},'to')" id="to" value="{!lineData.to}"/></td>
+                                <td><apex:inputCheckbox onclick="statusChabge({!lineData.lineNum},'cc')" id="cc" value="{!lineData.cc}"/></td>
+                                <td><apex:inputCheckbox onclick="statusChabge({!lineData.lineNum},'bcc')" id="bcc" value="{!lineData.bcc}"/></td>
+                                <td><apex:commandButton onclick="blockme();" action="{!deLine}" reRender="messageForm" value="delete"  oncomplete="unblockUI();" disabled="{!isOnClick}">
+                                    <apex:param name="lineNum" assignTo="{!lineNum}" value="{!lineData.lineNum}" />
+                                </apex:commandButton></td>
+                                <td>
+                                    <apex:commandButton onclick="openSearchMemberPage({!lineData.lineNum});" value="Search" disabled="{!isOnClick}">
+                                        
+                                    </apex:commandButton>
+                                </td>
+                            </tr>
+                        </apex:repeat>
+                    </tbody>
+                    <thead>
+                        <tr style="text-align:center;">
+                            <td><apex:commandButton id="addLine" onclick="blockme();" action="{!addLine}" reRender="messageForm" value="ADD Member" oncomplete="unblockUI();" disabled="{!isOnClick}"></apex:commandButton></td>
+                        </tr>
+                    </thead>
+                </table>
+            </div>
+            <div style="width: 100%">
+                <table class="tableCss">    
+                    <tr class="title">
+                        <th colspan="2"><font>Message</font></th>
+                    </tr>
+                    <tr>
+                        <th style="width: 20%;text-align:center;">Date Time:</th>
+                        <td><apex:inputField value="{!mail.DATE__c}" style="width: 40%"/></td>
+                    </tr>
+                    <!-- <tr>
+                        <th style="width: 20%;text-align:center;">RECORD:</th>
+                        <td><apex:inputField value="{!mail.RECORD__c}" style="width: 40%"/></td>
+                    </tr>
+                    <tr>
+                        <th style="width: 20%;text-align:center;">RECORD TYPE:</th>
+                        <td><apex:inputField value="{!mail.RECORD_TYPE__c}" style="width: 40%"/></td>
+                    </tr> -->
+                    <tr>
+                        <th style="text-align:center;width: 20%;">SUBJECT:</th>
+                        <td><apex:inputField value="{!mail.SUBJECT__c}" style="width: 40%"/></td>
+                    </tr>
+                    <tr>
+                        <th style="text-align:center;width: 20%;">MESSAGE:</th>
+                        <td><apex:inputField style="height: 200px;width: 60%" value="{!mail.MESSAGE__c}"/></td>
+                    </tr>
+                </table>
+            </div>
+        <!-- </apex:form>
+        <apex:form id="fileForm"> -->
+            <div style="width: 100%">
+                <table class="tableCss">
+                    <tr class="title">
+                        <th colspan="2"><font>Attachments</font></th>
+                    </tr>
+
+                    <tr>
+                        <td>
+                            <apex:commandButton value="Upload Attachment" action="{!uploadFile}" disabled="{!isOnClick}">
+                            </apex:commandButton>
+                             <apex:panelGroup >
+                                 <apex:commandButton onclick="uploadFileS();return false;" value="鍥剧墖鎵归噺涓婁紶" disabled="{!isOnClick}"/>
+                            </apex:panelGroup>
+                        </td>
+                    </tr>
+                </table>
+            </div>
+            <div style="margin-left: 5px;"> 
+                <!-- border:1px solid #000000; -->
+                <table class="tableCss" style="width: 80%"> 
+                    <tr style="text-align:center;">
+                        <th style="text-align:center;width: 33%;">File Name</th>
+                        <th style="text-align:center;width: 33%;">Upload Time</th>
+                        <th style="text-align:center;width: 33%;">File Size</th>
+                    </tr>
+                    <apex:repeat id="attachmentList" value="{!attachmentList}" var="attachment">
+                        <tr style="text-align:center; vertical-align: middle;">
+                            <!-- <td><input value="{!attachment.Name}" readonly="readonly" style="border:none;"/></td> -->
+                            <td><apex:outputLink value="/{!attachment.Id}">{!attachment.Name}</apex:outputLink></td>
+                            <td><apex:inputField value="{!attachment.CreatedDate}"/></td>
+                            <td><apex:inputField value="{!attachment.BodyLength}"/></td>
+                            <td id="{!attachment.Id}">
+                                <apex:commandButton id="deleteFile" value="delete" action="{!deleteFile}" reRender="messageForm" onclick="blockme();" oncomplete="unblockUI();" disabled="{!isOnClick}">
+                                    <apex:param name="fileId" assignTo="{!fileId}" value="{!attachment.Id}" />
+                                </apex:commandButton>
+                            </td>
+                        </tr>
+                    </apex:repeat>
+                </table>
+            </div>
+
+            <div style="width: 30%;height: 5%;margin-left: 30%;margin-top: middle;">
+                 <apex:outputPanel rendered="{!IF(type == 'Quotes', true, false)}">
+                    <apex:commandButton id="open" value="鏌ョ湅鎶ヤ环鍗�" onclick="openPDF()" style="width: 49%;height: 5%" />
+                    <apex:commandButton id="addPDf" value="娣诲姞鎶ヤ环鍗�" action="{!addPDF}" onclick="blockme();"  oncomplete="unblockUI();" reRender="messageForm" style="width: 49%;height: 5%" disabled="{!isOnClick}"/>
+                </apex:outputPanel>
+                <apex:commandButton id="test" action="{!SendEmail}" value="Send   Mail" onclick="blockme();"  oncomplete="unblockUI();" reRender="messageForm" style="width: 99%;height: 5%" disabled="{!isOnClick}">
+                    <apex:param name="handleType" assignTo="{!handleType}" value="send" />
+                </apex:commandButton>
+            </div>
+            <apex:outputPanel id="popupBox" layout="block" style="display:none">
+
+                <input type="file" id="file_input" name="attFile" multiple="true"/><br/>
+                <center>
+                    <apex:commandButton value="纭" onclick="saveAttachment(); return false;" style="width: 20%; margin: 20px 10px 0px 10px" />
+                    <apex:commandButton value="鍙栨秷" onclick="popupBox.hide();" style="width: 20%; margin: 20px 10px 0px 10px" />
+                </center>
+            </apex:outputPanel> 
+        </apex:form>
+    </div>
+    </div>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SendEmail.page-meta.xml b/scr/pages/SendEmail.page-meta.xml
new file mode 100644
index 0000000..a43a7e1
--- /dev/null
+++ b/scr/pages/SendEmail.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SendEmail</label>
+</ApexPage>
diff --git a/scr/pages/SiteLogin.page b/scr/pages/SiteLogin.page
new file mode 100644
index 0000000..6f0900b
--- /dev/null
+++ b/scr/pages/SiteLogin.page
@@ -0,0 +1,29 @@
+<apex:page id="loginPage" showHeader="false" title="{!$Label.site.site_login}">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">  
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.login}"/>
+                  <br/>
+                  <c:SiteLogin id="siteLogin"/>
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+             </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SiteLogin.page-meta.xml b/scr/pages/SiteLogin.page-meta.xml
new file mode 100644
index 0000000..a63a271
--- /dev/null
+++ b/scr/pages/SiteLogin.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 鐧诲綍椤甸潰</description>
+    <label>SiteLogin</label>
+</ApexPage>
diff --git a/scr/pages/SiteRegister.page b/scr/pages/SiteRegister.page
new file mode 100644
index 0000000..b4e443e
--- /dev/null
+++ b/scr/pages/SiteRegister.page
@@ -0,0 +1,45 @@
+<apex:page id="Registration" showHeader="false" controller="SiteRegisterController" title="{!$Label.site.register}">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">  
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.user_registration}"/>
+                  <br/>
+                  <apex:form id="theForm" forceSSL="true">
+                    <apex:pageMessages id="error"/>
+                    <apex:panelGrid columns="2" style="margin-top:1em;">
+                      <apex:outputLabel value="{!$Label.site.username}" for="username"/>
+                      <apex:inputText required="true" id="username" value="{!username}"/>
+                      <apex:outputLabel value="{!$Label.site.community_nickname}" for="communityNickname"/>
+                      <apex:inputText required="true" id="communityNickname" value="{!communityNickname}"/>
+                      <apex:outputLabel value="{!$Label.site.email}" for="email"/>
+                      <apex:inputText required="true" id="email" value="{!email}"/>
+                      <apex:outputLabel value="{!$Label.site.password}" for="password"/>
+                      <apex:inputSecret id="password" value="{!password}"/>
+                      <apex:outputLabel value="{!$Label.site.confirm_password}" for="confirmPassword"/>
+                      <apex:inputSecret id="confirmPassword" value="{!confirmPassword}"/>
+                      <apex:outputText value=""/>
+                      <apex:commandButton action="{!registerUser}" value="{!$Label.site.submit}" id="submit"/>
+                    </apex:panelGrid> 
+                    </apex:form>                  
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+             </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SiteRegister.page-meta.xml b/scr/pages/SiteRegister.page-meta.xml
new file mode 100644
index 0000000..30e18c4
--- /dev/null
+++ b/scr/pages/SiteRegister.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 鐢ㄦ埛娉ㄥ唽椤甸潰</description>
+    <label>SiteRegister</label>
+</ApexPage>
diff --git a/scr/pages/SiteRegisterConfirm.page b/scr/pages/SiteRegisterConfirm.page
new file mode 100644
index 0000000..6001957
--- /dev/null
+++ b/scr/pages/SiteRegisterConfirm.page
@@ -0,0 +1,30 @@
+<apex:page showHeader="false" title="{!$Label.site.registration_confirmation}">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">  
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1" style="align: center;"> 
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" style="topPanel"> 
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanelContainer">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="2"> 
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:panelGroup >
+                  <br/>
+                  <apex:outputText styleClass="title" value="{!$Label.site.thank_you_for_registering}"/>
+                  <br/>
+                  <br/>
+                  <apex:outputLink value="{!$Page.SiteLogin}" rendered="{!$Site.LoginEnabled}">{!$Label.site.go_to_login_page}</apex:outputLink>
+                  <br/>
+                </apex:panelGroup>
+              </apex:panelGrid> 
+            </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid> 
+       </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SiteRegisterConfirm.page-meta.xml b/scr/pages/SiteRegisterConfirm.page-meta.xml
new file mode 100644
index 0000000..0449358
--- /dev/null
+++ b/scr/pages/SiteRegisterConfirm.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 鐢ㄦ埛娉ㄥ唽纭椤甸潰</description>
+    <label>SiteRegisterConfirm</label>
+</ApexPage>
diff --git a/scr/pages/SiteTemplate.page b/scr/pages/SiteTemplate.page
new file mode 100644
index 0000000..2476eb5
--- /dev/null
+++ b/scr/pages/SiteTemplate.page
@@ -0,0 +1,13 @@
+<apex:page showHeader="false" id="SiteTemplate">
+  <apex:stylesheet value="{!URLFOR($Resource.SiteSamples, 'SiteStyles.css')}"/>
+  <apex:insert name="header">
+    <c:SiteHeader />
+    <hr/>
+  </apex:insert>
+  <apex:insert name="body"/>
+  <apex:insert name="footer">
+    <hr/>
+    <c:SiteFooter />
+    <site:googleAnalyticsTracking />
+  </apex:insert>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SiteTemplate.page-meta.xml b/scr/pages/SiteTemplate.page-meta.xml
new file mode 100644
index 0000000..87b1b50
--- /dev/null
+++ b/scr/pages/SiteTemplate.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>绔欑偣椤甸潰鐨勯粯璁� Force.com 妯℃澘</description>
+    <label>SiteTemplate</label>
+</ApexPage>
diff --git a/scr/pages/SoftphoneConsole.page b/scr/pages/SoftphoneConsole.page
new file mode 100644
index 0000000..64d83b5
--- /dev/null
+++ b/scr/pages/SoftphoneConsole.page
@@ -0,0 +1,132 @@
+<apex:page showChat="false" Controller="SoftphoneConsoleController" showHeader="false" sidebar="false" action="{!init}" id="allpage">
+    <apex:includeScript value="{!URLFOR($Resource.cti)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+
+    <script type="text/javascript">
+        var cti;
+        var stateDescrArray = ["鏈櫥褰�", "绀哄繖", "绀洪棽", "灏忎紤", "鎸搩", "鎷ㄥ彿", "閫氳瘽", "璇濆悗"];
+        var consultStateDescrArray = ["鏈煡鐘舵��", "姝e湪鍛煎彨", "鍗忓晢鎺ラ��", "涓夋柟閫氳瘽", "涓夋柟澶辫触"];
+         
+        try {
+            cti = createCTI();
+            cti.onAgentStateChanged = function (e) { 
+                AppendLog("鐘舵�佹敼鍙�, 褰撳墠鐘舵�侊細 " + getStateDescr(e.NewState.StateCode)); 
+            };
+            cti.onAnswerRequest = function () { AppendLog("璇锋眰搴旂瓟"); };
+            cti.onRecordStart = function (e) { AppendLog("褰曢煶寮�濮嬶細 CallId = " + e.CallId + ", 鏂囦欢鍚� = " + e.RecordFileName) };
+            cti.onRecordStop = function (e) { AppendLog("褰曢煶鍋滄锛� CallId = " + e.CallId + ", 鏂囦欢鍚� = " + e.RecordFileName) };
+            cti.onConsultStateChange = function (e) { AppendLog("涓夋柟鐘舵�佹敼鍙橈細   " + getConsultStateDescr(e.NewState.StateCode));  };
+            cti.onAgentAsrNotify = function (e) { AppendLog("璇煶璇嗗埆锛�   ")  };
+            cti.onQueueNumNotify = function (e) { AppendLog(e)  };
+            cti.attachEvent();
+        }
+        catch (e) {
+            alert(e.message);
+        }
+
+        // 閰嶇疆鍙傛暟
+        function config() {
+            try {
+                //var config = GetConfig(鏈嶅姟鍣ㄥ湴鍧�, 绔彛, 鍧愬腑鍙�, "as", 鏄惁寮�鍚蒋鐢佃瘽,杞數璇濆湴鍧�, 绔彛鍙�,杞數璇濆彿鐮�, 瀵嗙爜);
+                var config = GetConfig("domain_ysb", "223.112.26.254", "9528", "10005", "1234", "true", "223.112.26.254|domain_ysb", "63000", "80005", "1234");
+                //var config = GetConfig("domain_ysb", "223.112.26.254", "9528", "10200", "1234", "true", "223.112.26.254|domain_ysb", "9060", "80200", "pactera_op");
+                cti.setConfig(config);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+        function getConsultStateDescr(stateCode) {
+
+            if (stateCode < 0 || stateCode >= consultStateDescrArray.length) {
+                return "鏈煡鐘舵��";
+            }
+
+            return consultStateDescrArray[stateCode];
+        }
+
+        function getStateDescr(stateCode) {
+
+            if (stateCode < 0 || stateCode >= stateDescrArray.length) {
+                return "鏈煡鐘舵��";
+            }
+
+            return stateDescrArray[stateCode];
+        }
+        var GetConfig = function (domain, serverAddress, serverPort, agentID, agentPassword,
+            useWebVoip, webVoipSIPServerIP, webVoipSIPServerPort, webVoipAccount, webVoipPassword) {
+
+            return {
+                "CTI.Provider": "Lusca.LuscaCTIProvider, Lusca"                           // 鎻愪緵绋嬪簭
+                , "CTI.Timeout": "30000"                                                          // 瓒呮椂璁剧疆
+                , "CTI.Lusca.ServerAddress": serverAddress                 // 鏈嶅姟鍣ㄥ湴鍧� |domain
+                , "CTI.Lusca.ServerPort": serverPort                                                 // 鏈嶅姟鍣ㄧ鍙e彿
+                , "CTI.Lusca.EventPollUrl": "http://"+serverAddress+":"+serverPort + "/as/event?agent_id="+agentID
+                , "CTI.Lusca.UseWebVoip": useWebVoip                                              // 鏄惁浣跨敤杞數璇�
+                , "CTI.Lusca.WebVoipSIPServerIP": webVoipSIPServerIP                              // 杞數璇濇湇鍔″櫒鍦板潃
+                , "CTI.Lusca.WebVoipSIPServerPort": webVoipSIPServerPort                                      // 杞數璇濇湇鍔″櫒绔彛
+                , "CTI.Lusca.WebVoipAccount": webVoipAccount                                            // 杞數璇濊处鍙�
+                , "CTI.Lusca.WebVoipPassword": webVoipPassword                                       // 杞數璇濆瘑鐮�
+                , "CTI.AgentID": agentID                                                           // 搴у腑宸ュ彿
+                , "CTI.AgentPassword": agentPassword                                                // 搴у腑瀵嗙爜
+                , "CTI.Lusca.TenantId": "as"
+                , "CTI.Lusca.QueueName": "support@default"   //闃熷垪
+                , "CTI.UpdatePath": "ftp://192.168.17.141//Lusca"
+                , "CTI.UpdateMode": "0" //0:ftp 1:netbios
+                , "CTI.AutoLogout": "true"
+                , "CTI.EnableVoiceAnalysis": "false"
+                , "CTI.LocalRecording.Mode": ""
+                , "CTI.LocalRecording.Path": ""
+                , "CTI.Lusca.Domain": ""//domain
+            }
+        }
+
+         // 鐧诲綍
+        function login() {
+            try {
+                config();
+                var result = cti.agentLogin(false);
+
+                if (result == 1) {
+                    if (confirm("搴у腑宸茬粡鐧诲綍锛岃寮哄埗鐧诲綍鍚楋紵")) {
+                        cti.agentLogin(true);
+                    }
+                    else {
+                        return;
+                    }
+                }
+
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+    </script>
+
+    <style type="text/css"> 
+        #btnLogin {
+            width: 100px;
+        }
+
+        .login {
+            width: 150px;
+            text-align: center;
+            
+
+        }
+    </style>
+
+    <apex:form id="allform">
+        
+        <apex:outputPanel >
+            <div class="login" ><input type="userName" id="userName" name="userName" /></div>
+            <div class="login" ><input type="password" id="password" name="password" /></div>
+            <input id="btnLogin" type="button" value="鐧诲綍" onclick="login()" />    
+        </apex:outputPanel>
+
+    </apex:form>
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SoftphoneConsole.page-meta.xml b/scr/pages/SoftphoneConsole.page-meta.xml
new file mode 100644
index 0000000..eeffada
--- /dev/null
+++ b/scr/pages/SoftphoneConsole.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SoftphoneConsole</label>
+</ApexPage>
diff --git a/scr/pages/SoftwarePhoneInformation.page b/scr/pages/SoftwarePhoneInformation.page
new file mode 100644
index 0000000..42b85f6
--- /dev/null
+++ b/scr/pages/SoftwarePhoneInformation.page
@@ -0,0 +1,853 @@
+<apex:page showChat="false" showHeader="false" sidebar="false">
+
+<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<head>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+    <title></title>
+    <style type="text/css">
+        #Text1 {
+            width: 236px;
+        }
+
+        #TextArea1 {
+            height: 192px;
+            width: 472px;
+        }
+
+        #txtLog {
+            height: 201px;
+            width: 503px;
+        }
+
+        #btnConfig {
+            width: 60px;
+        }
+
+        #btnLogin {
+            width: 60px;
+        }
+
+        #btnLogout {
+            width: 60px;
+        }
+
+        #btnReady {
+            width: 60px;
+        }
+
+        #btnNotReady {
+            width: 60px;
+        }
+
+        #btnMakeCall {
+            width: 78px;
+        }
+
+        #btnAnswer {
+            width: 78px;
+        }
+
+        #btnDTMF {
+            width: 78px;
+        }
+
+        #btnHangup {
+            width: 78px;
+        }
+
+        #btnHold {
+            width: 78px;
+        }
+
+        #btnUnhold {
+            width: 78px;
+        }
+
+        #btnMuteOn {
+            width: 78px;
+        }
+
+        #btnMuteOff {
+            width: 78px;
+        }
+
+        #btnFinish {
+            width: 78px;
+        }
+
+        #btnUnhold {
+            width: 78px;
+        }
+
+        #btnConsultOut {
+            width: 94px;
+        }
+
+        #btnConsultInner {
+            width: 94px;
+        }
+
+        #btnCompleteTransfer {
+            width: 94px;
+        }
+
+        #btnCompleteTransfer0 {
+            width: 94px;
+        }
+
+        #btnCancelTransfer {
+            width: 94px;
+        }
+
+        #btnCompleteTransfer0 {
+            width: 94px;
+        }
+
+        #btnTransOut {
+            width: 94px;
+        }
+
+        #btnTransInner {
+            width: 94px;
+        }
+
+        #btnTransIVR {
+            width: 94px;
+        }
+
+        #btnConsultIVR {
+            width: 94px;
+        }
+
+        #btnCancelConsult {
+            width: 94px;
+        }
+
+        #btnDTMF0 {
+            width: 78px;
+        }
+
+        #btnDTMF1 {
+            width: 78px;
+        }
+
+        #btnMakeCall0 {
+            width: 78px;
+        }
+
+        #btnCallOut {
+            width: 78px;
+        }
+
+        #btnAnswer0 {
+            width: 78px;
+        }
+
+        #btnConsultOut0 {
+            width: 94px;
+        }
+
+        #btnConsultOut1 {
+            width: 94px;
+        }
+
+        #btnConsultOut2 {
+            width: 94px;
+        }
+
+        #btnForceOut0 {
+            width: 83px;
+        }
+
+        #btnForceOut1 {
+            width: 83px;
+        }
+
+        #btnForceOut2 {
+            width: 83px;
+        }
+
+        #btnForceOut3 {
+            width: 83px;
+        }
+
+        #btnListen {
+            width: 81px;
+        }
+
+        #btnInsert {
+            width: 88px;
+        }
+    </style>
+</head>
+<body>
+    <!-- <script type="text/javascript" src="cti.js"></script> -->
+    <apex:includeScript value="{!URLFOR($Resource.cti)}"/>
+    <p>
+        <input id="btnLogin" type="button" value="鐧诲綍" onclick="login()" />
+        <!-- <input id="btnLogout" type="button" value="娉ㄩ攢" onclick="logout()" />
+        <input id="btnReady" type="button" value="绀洪棽" onclick="setReady()" />
+        <input id="btnNotReady" type="button" value="绀哄繖" onclick="setNotReady()" />
+        <input id="btnQueryAllAgents" type="button" value="鏌ヨ搴у腑鐘舵��" onclick="queryAllAgentStatus()" /> -->
+    </p>
+
+
+    <!-- <p>
+        <input id="txtNumber" type="text" />
+        <input id="btnCallOut" type="button" value="鎷ㄦ墦" onclick="callOut()" />
+        <input id="btnCallInner" type="button" value="鍛煎彨搴у腑" onclick="callInner()" />
+        <input id="btnAnswer" type="button" value="鎺ュ惉" onclick="answer()" />&nbsp;
+        <input id="btnCallInfo" type="button" value="鍛煎彨淇℃伅" onclick="showCallInfo()" />
+    </p>
+    <p>
+        <input id="txtDTMF" type="text" />
+        <input id="btnDTMF" type="button" value="浜屾鎷ㄥ彿" onclick="sendDTMF()" />
+    </p>
+    <p>
+        <input id="txtCallData" type="text" />
+        <input id="btnDTMF0" type="button" value="璇婚殢璺暟鎹�" onclick="getCallData()" />
+        <input id="btnDTMF1" type="button" value="鍐欓殢璺暟鎹�" onclick="setCallData()" />
+    </p>
+    <p>
+        <input id="btnHold" type="button" value="淇濇寔" onclick="hold()" />
+        <input id="btnUnhold" type="button" value="鍙栦繚鎸�" onclick="unhold()" />
+        <input id="btnMuteOn" type="button" value="璁剧疆闈欓煶" onclick="setmuteon()" />
+        <input id="btnMuteOff" type="button" value="鍙栨秷闈欓煶" onclick="setmuteoff()" />
+        <input id="btnHangup" type="button" value="鎸傛柇" onclick="hangup()" />
+        <input id="btnFinish" type="button" value="缁撴潫閫氳瘽" onclick="finish()" />
+    </p>
+    <p>
+        <input id="txtTransNum" type="text" />
+    </p>
+    <p>
+        <input id="btnTransOut" type="button" value="鍗曟杞绾�" onclick="transOut()" />
+        <input id="btnTransInner" type="button" value="鍗曟杞唴绾�" onclick="transInner()" />
+        <input id="btnTransQueue" type="button" value="杞槦鍒�" onclick="transQueue()" />
+        <input id="btnTransIVR" type="button" value="鍗曟杞琁VR" onclick="transIVR()" />
+        <input id="btnConsultIVR" type="button" value="鎸傝捣杞琁VR" onclick="consultIVR()" />&nbsp;&nbsp;
+    </p>
+    <p>
+        <input id="btnConsultOut" type="button" value="鍗忓晢澶栫嚎" onclick="consultOut()" />
+        <input id="btnConsultInner" type="button" value="鍗忓晢搴у腑" onclick="consultInner()" />
+        <input id="btnCompleteTransfer" type="button" value="瀹屾垚杞帴" onclick="consultTransfer()" />
+        <input id="btnCompleteTransfer0" type="button" value="涓夋柟閫氳瘽" onclick="consultConference()" />
+        <input id="btnCancelConsult" type="button" value="鍙栨秷鍗忓晢" onclick="cancelConsult()" />
+    </p>
+    <p>
+        <input id="txtAgentId" type="text" />&nbsp;
+    </p>
+    <p>
+        <input id="btnForceBusy" type="button" value="寮哄埗绀哄繖" onclick="forceBusy()" />
+        <input id="btnForceReady" type="button" value="寮哄埗绀洪棽" onclick="forceReady()" />
+        <input id="btnForceOut" type="button" value="寮哄埗绛惧嚭" onclick="forceOut()" />
+        <input id="btnListen" type="button" value="鐩戝惉" onclick="listen()" />
+        <input id="btnStopListen" type="button" value="鍋滄鐩戝惉" onclick="stopListen()" />
+        <input id="btnInsert" type="button" value="鎻掑叆" onclick="insert()" />
+        <input id="btnStopInsert" type="button" value="鍋滄鎻掑叆" onclick="stopInsert()" />
+    </p> -->
+
+    <script type="text/javascript">
+
+        var cti;
+        var stateDescrArray = ["鏈櫥褰�", "绀哄繖", "绀洪棽", "灏忎紤", "鎸搩", "鎷ㄥ彿", "閫氳瘽", "璇濆悗"];
+        var consultStateDescrArray = ["鏈煡鐘舵��", "姝e湪鍛煎彨", "鍗忓晢鎺ラ��", "涓夋柟閫氳瘽", "涓夋柟澶辫触"];
+         
+        try {
+            cti = createCTI();
+            cti.onAgentStateChanged = function (e) { 
+                AppendLog("鐘舵�佹敼鍙�, 褰撳墠鐘舵�侊細 " + getStateDescr(e.NewState.StateCode)); 
+            };
+            cti.onAnswerRequest = function () { AppendLog("璇锋眰搴旂瓟"); };
+            cti.onRecordStart = function (e) { AppendLog("褰曢煶寮�濮嬶細 CallId = " + e.CallId + ", 鏂囦欢鍚� = " + e.RecordFileName) };
+            cti.onRecordStop = function (e) { AppendLog("褰曢煶鍋滄锛� CallId = " + e.CallId + ", 鏂囦欢鍚� = " + e.RecordFileName) };
+            cti.onConsultStateChange = function (e) { AppendLog("涓夋柟鐘舵�佹敼鍙橈細   " + getConsultStateDescr(e.NewState.StateCode));  };
+            cti.onAgentAsrNotify = function (e) { AppendLog("璇煶璇嗗埆锛�   ")  };
+            cti.onQueueNumNotify = function (e) { AppendLog(e)  };
+            cti.attachEvent();
+        }
+        catch (e) {
+            alert(e.message);
+        }
+        function getConsultStateDescr(stateCode) {
+
+            if (stateCode < 0 || stateCode >= consultStateDescrArray.length) {
+                return "鏈煡鐘舵��";
+            }
+
+            return consultStateDescrArray[stateCode];
+        }
+
+        function getStateDescr(stateCode) {
+
+            if (stateCode < 0 || stateCode >= stateDescrArray.length) {
+                return "鏈煡鐘舵��";
+            }
+
+            return stateDescrArray[stateCode];
+        }
+        var GetConfig = function (domain, serverAddress, serverPort, agentID, agentPassword,
+            useWebVoip, webVoipSIPServerIP, webVoipSIPServerPort, webVoipAccount, webVoipPassword) {
+
+            return {
+                "CTI.Provider": "Lusca.LuscaCTIProvider, Lusca"                           // 鎻愪緵绋嬪簭
+                , "CTI.Timeout": "30000"                                                          // 瓒呮椂璁剧疆
+                , "CTI.Lusca.ServerAddress": serverAddress                 // 鏈嶅姟鍣ㄥ湴鍧� |domain
+                , "CTI.Lusca.ServerPort": serverPort                                                 // 鏈嶅姟鍣ㄧ鍙e彿
+                , "CTI.Lusca.EventPollUrl": "http://"+serverAddress+":"+serverPort + "/as/event?agent_id="+agentID
+                , "CTI.Lusca.UseWebVoip": useWebVoip                                              // 鏄惁浣跨敤杞數璇�
+                , "CTI.Lusca.WebVoipSIPServerIP": webVoipSIPServerIP                              // 杞數璇濇湇鍔″櫒鍦板潃
+                , "CTI.Lusca.WebVoipSIPServerPort": webVoipSIPServerPort                                      // 杞數璇濇湇鍔″櫒绔彛
+                , "CTI.Lusca.WebVoipAccount": webVoipAccount                                            // 杞數璇濊处鍙�
+                , "CTI.Lusca.WebVoipPassword": webVoipPassword                                       // 杞數璇濆瘑鐮�
+                , "CTI.AgentID": agentID                                                           // 搴у腑宸ュ彿
+                , "CTI.AgentPassword": agentPassword                                                // 搴у腑瀵嗙爜
+                , "CTI.Lusca.TenantId": "as"
+                , "CTI.Lusca.QueueName": "support@default"   //闃熷垪
+                , "CTI.UpdatePath": "ftp://192.168.17.141//Lusca"
+                , "CTI.UpdateMode": "0" //0:ftp 1:netbios
+                , "CTI.AutoLogout": "true"
+                , "CTI.EnableVoiceAnalysis": "false"
+                , "CTI.LocalRecording.Mode": ""
+                , "CTI.LocalRecording.Path": ""
+                , "CTI.Lusca.Domain": ""//domain
+            }
+        }
+
+        // 閰嶇疆鍙傛暟
+        function config() {
+            try {
+                //var config = GetConfig(鏈嶅姟鍣ㄥ湴鍧�, 绔彛, 鍧愬腑鍙�, "as", 鏄惁寮�鍚蒋鐢佃瘽,杞數璇濆湴鍧�, 绔彛鍙�,杞數璇濆彿鐮�, 瀵嗙爜);
+                var config = GetConfig("domain_ysb", "223.112.26.254", "9528", "10005", "1234", "true", "223.112.26.254|domain_ysb", "63000", "80005", "1234");
+                //var config = GetConfig("domain_ysb", "223.112.26.254", "9528", "10200", "1234", "true", "223.112.26.254|domain_ysb", "9060", "80200", "pactera_op");
+                cti.setConfig(config);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鐧诲綍
+        function login() {
+            try {
+                config();
+                var result = cti.agentLogin(false);
+
+                if (result == 1) {
+                    if (confirm("搴у腑宸茬粡鐧诲綍锛岃寮哄埗鐧诲綍鍚楋紵")) {
+                        cti.agentLogin(true);
+                    }
+                    else {
+                        return;
+                    }
+                }
+
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 娉ㄩ攢
+        function logout() {
+            try {
+                cti.agentLogout();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 绀洪棽
+        function setReady() {
+            try {
+                cti.agentSetReady();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 绀哄繖
+        function setNotReady() {
+            try {
+                cti.agentSetNotReady();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎺ュ惉
+        function answer() {
+            try {
+                cti.answerCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍛煎嚭
+        function callOut() {
+            try {
+
+                var number = txtNumber.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.callOut("", number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍐呯嚎鍛煎彨
+        function callInner() {
+            try {
+
+                var number = txtNumber.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.callInner(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎸傛満
+        function hangup() {
+            try {
+                cti.releaseCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 浜屾鎷ㄥ彿
+        function sendDTMF() {
+            try {
+
+                var number = txtDTMF.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.sendDTMF(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 璁剧疆闈欓煶
+        function setmuteon() {
+            try {
+                cti.setMuteOn();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍙栨秷闈欓煶
+        function setmuteoff() {
+            try {
+                cti.setMuteOff();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 璇婚殢璺暟鎹�
+        function getCallData() {
+            try {
+                txtCallData.value = cti.queryCallData();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍐欓殢璺暟鎹�
+        function setCallData() {
+            try {
+                cti.setCallData(txtCallData.value);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 淇濇寔
+        function hold() {
+            try {
+                cti.holdCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍙栦繚鎸�
+        function unhold() {
+            try {
+                cti.retrieveCall();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 缁撴潫閫氳瘽锛堝皬缁撴椂璋冪敤锛�
+        function finish() {
+            try {
+                cti.finishCall(0);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞绾�
+        function transOut() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferOut("", number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞唴绾�
+        function transInner() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferInner(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞槦鍒�
+        function transQueue() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferQueue(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗曟杞琁VR
+        function transIVR() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.transferIVR(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎸傝捣杞琁VR
+        function consultIVR() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.consultIVR(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗忓晢澶栫嚎
+        function consultOut() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.consultOut("", number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗忓晢搴у腑
+        function consultInner() {
+            try {
+                var number = txtTransNum.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ彿鐮�.");
+                    return;
+                }
+
+                cti.consultInner(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍙栨秷鍗忓晢
+        function cancelConsult() {
+            try {
+                cti.cancelConsult();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍗忓晢杞帴
+        function consultTransfer() {
+            try {
+                cti.consultTransfer();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 涓夋柟閫氳瘽
+        function consultConference() {
+            try {
+                cti.consultConference();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 寮哄埗绀哄繖
+        function forceBusy() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.forceAgentBusy(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 寮哄埗绀洪棽
+        function forceReady() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.forceAgentReady(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 寮哄埗绛惧嚭
+        function forceOut() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.forceAgentLogout(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鐩戝惉
+        function listen() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.listen(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍋滄鎻掑叆
+        function stopListen() {
+            try {
+                cti.stopListen();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鎻掑叆
+        function insert() {
+            try {
+                var number = txtAgentId.value;
+
+                if (number == null || number == undefined || number.length == 0) {
+                    alert("璇疯緭鍏ュ骇甯伐鍙�.");
+                    return;
+                }
+
+                cti.insert(number);
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        // 鍋滄鎻掑叆
+        function stopInsert() {
+            try {
+                cti.stopInsert();
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        function showCallInfo() {
+            try {
+                var call = cti.getActiveCallInfo();
+
+                if (call != null) {
+                    alert("娲诲姩鍛煎彨锛� CallId = " + call.CallId + ", 涓诲彨 = " + call.CallerNum + ", 琚彨 = " + call.CalledNum);
+                }
+
+                call = cti.getHeldCallInfo();
+
+                if (call != null) {
+                    alert("淇濇寔鍛煎彨锛� CallId = " + call.CallId + ", 涓诲彨 = " + call.CallerNum + ", 琚彨 = " + call.CalledNum);
+                }
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        function queryAllAgentStatus() {
+            try {
+                var result = cti.queryAllAgentStatus();
+
+                if (result != null) {
+
+                    var str = "";
+
+                    for (var i = 0; i < result.length; i++) {
+
+                        str += "宸ュ彿: " + result[i].AgentId;
+                        str += ", 鐘舵�侊細 " + getStateDescr(result[i].AgentState);
+                        str += "\r\n";
+                    }
+
+                    alert(str);
+                }
+                else {
+                    alert("娌℃湁搴у腑.");
+                }
+            }
+            catch (e) {
+                alert(e.message);
+            }
+        }
+
+        Date.prototype.Format = function (fmt) { //author: meizz
+            var o = {
+                "M+": this.getMonth() + 1, //鏈堜唤
+                "d+": this.getDate(), //鏃�
+                "h+": this.getHours(), //灏忔椂
+                "m+": this.getMinutes(), //鍒�
+                "s+": this.getSeconds(), //绉�
+                "q+": Math.floor((this.getMonth() + 3) / 3), //瀛e害
+                "S": this.getMilliseconds() //姣
+            };
+
+            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
+            for (var k in o)
+                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
+            return fmt;
+        }
+
+        // 杈撳嚭鏃ュ織
+        function AppendLog(message) {
+            var now = new Date();
+            txtLog.value += now.Format("yyyy-MM-dd hh:mm:ss") + "  " + message + "\r\n";
+        }
+    </script>
+
+    <!-- <p>
+        <textarea id="txtLog" name="S1"></textarea>
+    </p> -->
+
+</body>
+</html>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/SoftwarePhoneInformation.page-meta.xml b/scr/pages/SoftwarePhoneInformation.page-meta.xml
new file mode 100644
index 0000000..4342ac4
--- /dev/null
+++ b/scr/pages/SoftwarePhoneInformation.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>SoftwarePhoneInformation</label>
+</ApexPage>
diff --git a/scr/pages/StageProgressBar.page b/scr/pages/StageProgressBar.page
new file mode 100644
index 0000000..419d92a
--- /dev/null
+++ b/scr/pages/StageProgressBar.page
@@ -0,0 +1,246 @@
+<apex:page standardController="Opportunity" standardStylesheets="false" sidebar="false" extensions="StageProgressBarExtension">
+    <apex:form >
+        <apex:outputPanel id="thePanel">
+            <apex:stylesheet value="{!URLFOR($Resource.StageProgressBarCss)}" />
+            <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+            <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+            <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+            <apex:includeScript value="{!URLFOR($Resource.CommonUtilJs)}"/>
+            <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+            <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+            <apex:includeScript value="{!URLFOR($Resource.StageMapJsNew1)}"/>
+            <style>
+                .stage {
+                  background: #B1B4B6;
+                  font-size: 10px;
+                  padding: 6px 10px;
+                  margin:0,0;
+                  display: inline-block;
+                  -webkit-transition-duration: 0.3s;
+                  transition-duration: 0.3s;
+                  -webkit-transition-property: box-shadow;
+                  transition-property: box-shadow;
+                  -webkit-transform: translateZ(0);
+                  transform: translateZ(0);
+                  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
+                }
+            </style>
+            <script>
+                var stage = '{!JSENCODE(Opportunity.stageName)}';
+                var stageObj = new Object();
+                var colorObj = new Object();
+                // StageMap.js銇儜銉┿儭銉笺偪銈掔洿鎺ヨ銈�
+                var debugview1 = '{!recordTypeName}';
+               //alert(debugview1);
+                for(i = 0; i < {!recordTypeName}.length; i++){
+                    var dData = {!recordTypeName}[i];
+                    var cDate = {!recordTypeName}COLOR[i];
+                    stageObj[dData[0]] = dData;
+                    colorObj[cDate[0]] = cDate;
+                }
+                // 浠娿伄Stage銇銇椼�併偗銉儍銈仹銇嶃倠Stage銈掕ō瀹�
+                // 瀹氱京銇椼仸銇亜鍫村悎銆佸叏Stage銈儶銉冦偗涓嶈兘
+                var activeStage = stageObj[stage];
+                var activeStageObj = new Object();
+                if (activeStage != undefined && activeStage.length > 1) {
+                    for (i = 1; i < activeStage.length; i++) {
+                        activeStageObj[activeStage[i]] = activeStage[i];
+                    }
+                }
+                var activeColor = colorObj[stage];
+                var activeColorObj = new Object();
+                if (activeColor != undefined && activeColor.length > 1) {
+                    for (i = 1; i < activeColor.length; i++) {
+                        activeColorObj[activeColor[i]] = activeColor[i];
+                    }
+                }
+                
+                j$(document).ready(function() {
+                    var stages = j$('.stage');
+                    //for (i = 0; i < stages.length; i++) {
+                    //    j$(stages[i]).css('background-color', '#2A94D6');
+                    //    if (j$(stages[i]).text() == stage) {
+                    //        break;
+                    //    }
+                    //}
+                    for (i = 0; i < stages.length; i++) {
+                        if (activeColorObj[j$(stages[i]).text()] != undefined) {
+                            j$(stages[i]).css('background-color', '#2A94D6');
+                        }
+                    }
+                    // cursor銇╟lass
+                    for (i = 0; i < stages.length; i++) {
+                        j$(stages[i]).css({'cursor':'default'});
+                        j$(stages[i]).addClass('ng-stage');
+                        if (activeStageObj[j$(stages[i]).text()] != undefined) {
+                            j$(stages[i]).css({'cursor':'pointer'});
+                            j$(stages[i]).removeClass('ng-stage');
+                        }
+                    }
+                    // 銈ゃ儥銉炽儓銉忋兂銉夈儵鈥�
+                    j$('.stage').click(
+                        function() {
+                            if (j$(this).hasClass('ng-stage') == false) {
+                                var s = j$(this).text(); 
+                                if (confirm('鍙樻洿璇环闃舵鍒�' + s + '锛屾槸鍚︾‘瀹氾紵') == false) {
+                                    return;
+                                }
+                                if (s == '瀹屾垚') {
+                                    //璇环绂佹浠g悊鍟嗙偣鍑烩�滃畬鎴愨�濇寜閽�
+                                    var conzt ='{!Opportunity.CreatedBy.User_Type__c}';
+                                    if(conzt == 'PowerPartner'){
+                                        alert('鎶辨瓑,璇环绂佹浠g悊鍟嗙偣鍑烩�滃畬鎴愨�濇寜閽�');
+                                            return;
+                                        }else{
+                                        s = 'Closed Won';
+                                    }
+                                } else if (s == '澶辫触') {
+                                    var oppId = '{!Opportunity.Id}';
+                                    var creuser = '{!Opportunity.CreatedById}'.substring(0,15);
+                                    var owner = '{!Opportunity.OwnerId}'.substring(0,15);
+                                    
+                                    var userId = '{!$User.Id}'.substring(0,15);
+                                   
+                                    var roleId = '{!$User.UserRoleId}'.substring(0,15);
+                                    //alert(userId); 
+                                    if(userId == '005280000037mrQ' || userId == '00528000002OAvH' || userId == '00528000000YSdB' || roleId == '00E0K000001ywwz' || roleId == '00E0K000001jGiM' || roleId == '00E0K000001jGib' || roleId == '00E0K000001ywgS' || roleId == '00E28000000knAm' || roleId == '00E28000000knAr' || roleId == '00E28000000aKzn' || roleId == '00E0K000001jGhn' || roleId == '00E0K000001jGhs' || roleId == '00E0K000001ywgN' || roleId == '00E0K000001PWuh' || roleId == '00E0K000001PWum' || roleId == '00E0K000001PWur' || roleId == '00E280000015xus' || roleId == '00E280000015xux' || roleId == '00E28000000aKzs' || roleId == '00E0K000001jGiC' || roleId == '00E0K000001jGiR' || roleId == '00E0K000001ywgX' || roleId == '00E28000000knAc' || roleId == '00E28000000knAh' || roleId == '00E28000000aKzx' || roleId == '00E28000000knAw' || roleId == '00E28000000knB1' || roleId == '00E28000000aL02' || roleId == '00E28000000kjpX'){
+                                        var rtn = sforce.apex.execute("OpportunityWebService", "checkOrderStatus", {oppId: oppId,stageName:'Closed Lost',creuser: creuser,owner: owner});
+                                        if(rtn == '1' && (creuser == userId || owner == userId)){
+                                            /*if(!confirm("鏄惁澶辫触璇环锛�")){
+                                                return;
+                                            }*/
+                                    
+                                            /*var rac = new sforce.SObject("Opportunity");
+                                            rac.Id = "{!Opportunity.Id}";
+                                            rac.Cancel_Fail_Approve__c = 'Pass';
+                                            rac.StageName = 'Closed Lost';
+                                            var result = sforce.connection.update([rac]);
+                                            var messages = getConnectDMLErrorMessages(result);
+                                            if (messages.length > 0) {
+                                                alert(messages.join("\n"));
+                                                return;
+                                            }*/
+                                            alert('璇环宸插け璐�.');
+                                            refreshPage();
+                                            return;
+                                        }else{
+                                            //alert(rtn);
+                                            if(creuser != userId || owner != userId){
+                                                alert('鍙湁鍒涘缓浜哄拰鎵�鏈変汉鎵嶈兘澶辫触璇环');
+                                            }else if(rtn == '0' ){
+                                                alert('璇环涓嬪瓨鍦ㄦ湁鏁堝悎鍚岋紝涓嶈兘鍙栨秷/澶辫触');
+                                            }else{
+                                                alert(rtn);
+                                            }
+                                            return;
+                                        }
+                                    
+                                    }
+                                    
+                                    s = 'Closed Lost';
+                                } else if (s == '鍙栨秷') {
+                                    var oppId = '{!Opportunity.Id}';
+                                    var creuser = '{!Opportunity.CreatedById}'.substring(0,15);
+                                    var owner = '{!Opportunity.OwnerId}'.substring(0,15);
+                                    
+                                    var userId = '{!$User.Id}'.substring(0,15);
+                                   
+                                    var roleId = '{!$User.UserRoleId}'.substring(0,15);
+                                    //alert(userId); 
+                                    if(userId == '005280000037mrQ' || userId == '00528000002OAvH' || userId == '00528000000YSdB' || roleId == '00E0K000001ywwz' || roleId == '00E0K000001jGiM' || roleId == '00E0K000001jGib' || roleId == '00E0K000001ywgS' || roleId == '00E28000000knAm' || roleId == '00E28000000knAr' || roleId == '00E28000000aKzn' || roleId == '00E0K000001jGhn' || roleId == '00E0K000001jGhs' || roleId == '00E0K000001ywgN' || roleId == '00E0K000001PWuh' || roleId == '00E0K000001PWum' || roleId == '00E0K000001PWur' || roleId == '00E280000015xus' || roleId == '00E280000015xux' || roleId == '00E28000000aKzs' || roleId == '00E0K000001jGiC' || roleId == '00E0K000001jGiR' || roleId == '00E0K000001ywgX' || roleId == '00E28000000knAc' || roleId == '00E28000000knAh' || roleId == '00E28000000aKzx' || roleId == '00E28000000knAw' || roleId == '00E28000000knB1' || roleId == '00E28000000aL02' || roleId == '00E28000000kjpX'){
+                                        var rtn = sforce.apex.execute("OpportunityWebService", "checkOrderStatus", {oppId: oppId,stageName:'Closed Cancel',creuser: creuser,owner: owner});
+                                        if(rtn == '1' && (creuser == userId || owner == userId)){
+                                            /*if(!confirm("鏄惁澶辫触璇环锛�")){
+                                                return;
+                                            }*/
+                                    
+                                            /*var rac = new sforce.SObject("Opportunity");
+                                            rac.Id = "{!Opportunity.Id}";
+                                            rac.Cancel_Fail_Approve__c = 'Pass';
+                                            rac.StageName = 'Closed Cancel';
+                                            var result = sforce.connection.update([rac]);
+                                            var messages = getConnectDMLErrorMessages(result);
+                                            if (messages.length > 0) {
+                                                alert(messages.join("\n"));
+                                                return;
+                                            }*/
+                                            alert('璇环宸插彇娑�.');
+                                            refreshPage();
+                                            return;
+                                        }else{
+                                            if(creuser != userId || owner != userId){
+                                                alert('鍙湁鍒涘缓浜哄拰鎵�鏈変汉鎵嶈兘鍙栨秷璇环');
+                                            }else if(rtn == '0' ){
+                                                alert('璇环涓嬪瓨鍦ㄦ湁鏁堝悎鍚岋紝涓嶈兘鍙栨秷/澶辫触');
+                                            }else{
+                                                alert(rtn);
+                                            }
+                                            return;
+                                        }
+                                    
+                                    }
+                                    s = 'Closed Cancel';
+                                }
+                                //updateOpp(j$(this).attr('data-id'), j$(this).text());
+                                updateOpp(j$(this).attr('data-id'), s);
+                            }
+                        }
+                    );
+                    j$('.stage').mouseover(
+                        function() {
+                            if (j$(this).hasClass('ng-stage') == false) {
+                                j$(this).css({'box-shadow':'0 0 8px rgba(0, 0, 0, 0.6)'});
+                            }
+                        }
+                    );
+                    j$('.stage').mouseleave(
+                        function() {
+                            if (j$(this).hasClass('ng-stage') == false) {
+                                j$(this).css({'box-shadow':''});
+                            }
+                        }
+                    );
+                });
+                
+                function updateOpp(id, stage) {
+                    //var opp = new sforce.SObject("Opportunity");
+                    //opp.Id = id;
+                    //opp.StageName = stage;
+                    //var result = sforce.connection.update([opp]);
+                    //var messages = getConnectDMLErrorMessages(result); 
+                    //if (messages.length > 0) { 
+                    //    alert(messages.join("\n")); 
+                    //    return; 
+                    //} else {
+                    //    refreshPage();
+                    //}
+                    var rs = sforce.apex.execute("OpportunityWebService", "UpdateStageName", {opportunityId: id, targetStageName: stage}); 
+                    if (rs != '1') { 
+                        alert(rs); 
+                        return;
+                    } else {
+                        refreshPage();
+                    }
+                }
+                
+                function refreshPage(){
+                    var path = window.location.pathname;
+                    if (path.indexOf('/servlet/') > 0) {
+                        path = path.substring(0, path.indexOf('/servlet/'));
+                    } else {
+                        path = '';
+                    }
+                    window.parent.location.href = path + '/{!Opportunity.id}';
+                }
+            </script>
+<!--             <apex:pageMessages /> -->
+<!--             <apex:actionFunction action="{!updateOpp}" name="updateOpp" reRender="thePanel" oncomplete="refreshPage()"> -->
+<!--                 <apex:param assignTo="{!targetId}" name="oppId" value="" /> -->
+<!--                 <apex:param assignTo="{!targetStageName}" name="stage" value="" /> -->
+<!--             </apex:actionFunction> -->
+           <div align = "left"><apex:repeat value="{!stages}" var="stage">
+                <a href="#" class="progress-button stage" data-id="{!Opportunity.id}">{!HTMLENCODE(stage)}</a>
+            </apex:repeat></div>
+        </apex:outputPanel>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/StageProgressBar.page-meta.xml b/scr/pages/StageProgressBar.page-meta.xml
new file mode 100644
index 0000000..fba4f04
--- /dev/null
+++ b/scr/pages/StageProgressBar.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>StageProgressBar</label>
+</ApexPage>
diff --git a/scr/pages/StdExceptionTemplate.page b/scr/pages/StdExceptionTemplate.page
new file mode 100644
index 0000000..965917d
--- /dev/null
+++ b/scr/pages/StdExceptionTemplate.page
@@ -0,0 +1,23 @@
+<apex:page showHeader="false" title="{!$Label.site.site_under_construction}" id="StdExceptionTemplate" cache="false">
+  <apex:stylesheet value="{!URLFOR($Resource.SiteSamples, 'SiteStyles.css')}"/>
+  <center>
+  <apex:panelGrid bgcolor="white" columns="1">
+    <br/>
+    <br/>
+    <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer">
+      <br/>
+      <apex:outputPanel layout="block" styleClass="topPanel">
+        <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="3">
+          <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+          <apex:insert name="icon"/>
+          <apex:insert name="error"/>
+        </apex:panelGrid>
+      </apex:outputPanel>
+      <c:SitePoweredBy />
+    </apex:panelGrid>
+    <br/>
+    <site:previewAsAdmin />
+    <br/>
+  </apex:panelGrid>
+  </center>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/StdExceptionTemplate.page-meta.xml b/scr/pages/StdExceptionTemplate.page-meta.xml
new file mode 100644
index 0000000..176dca4
--- /dev/null
+++ b/scr/pages/StdExceptionTemplate.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>鏍囧噯渚嬪椤甸潰鐨勯粯璁� Force.com 妯℃澘</description>
+    <label>StdExceptionTemplate</label>
+</ApexPage>
diff --git a/scr/pages/TSRepair.page b/scr/pages/TSRepair.page
new file mode 100644
index 0000000..0c54e4a
--- /dev/null
+++ b/scr/pages/TSRepair.page
@@ -0,0 +1,1006 @@
+<apex:page standardController="TS_Repair__c" extensions="TSRepairController" showHeader="true" sidebar="false" id="allPage" action="{!init}" title="TS鏃ユ姤">
+    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <!-- <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/> -->
+    <!-- <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/> -->
+    <apex:stylesheet value="{!URLFOR($Resource.jquerysuggestcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquerysuggestjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"/>
+    <style type="text/css"> 
+        /*.sfdcBody {position: absolute;
+        left:0px;
+        right:0px;
+        top:0px;
+        bottom:0px;
+        width: 80%;
+        overflow:auto;}
+
+        */
+        .dateFormat  {
+            display: none;
+        }
+        .pbSubheader {
+            /*background: #BFB19C;*/
+            /*background-color: #44A3BB!important;
+            background-color: #E6E6FA!important;*/
+            background-color: #1797c0!important;
+            background-color: #BFB19C!important;
+
+
+        }
+        td.columuslowercolour {
+            background-color:red;
+            text-align: right;
+        }
+            td.columuscuperolour {
+            background-color: yellow;
+            text-align: right;
+        }
+
+        .visitorplace_results {
+            border: 1px solid gray;
+            background-color: white;
+            padding: 0;
+            margin: 0;
+            list-style: none;
+            position: absolute;
+            z-index: 10000;
+            display: none;
+            overflow:auto;
+            white-space:nowrap;
+            width:400px;
+            height:250px;
+        }
+        .visitorplace_results li {
+            padding: 2px 5px 2px 0px;
+            margin-left : 2px;
+            color: #101010;
+            text-align: left;
+        }
+        .status {
+            width: 50px;
+            box-sizing: border-box;
+            background: #B1B4B6;
+            font-size: 9px;
+            padding: 6px 2px;
+            margin:0,0;
+            display: inline-block;
+            -webkit-transition-duration: 0.3s;
+            transition-duration: 0.3s;
+            -webkit-transition-property: box-shadow;
+            transition-property: box-shadow;
+            -webkit-transform: translateZ(0);
+            transform: translateZ(0);
+            
+        }
+        .qqq{
+            width: 50px;
+            background: #51b7e6;
+            font-size: 9px;
+            padding: 6px 2px;
+            margin:0,0;
+            display: inline-block;
+            -webkit-transition-duration: 0.3s;
+            transition-duration: 0.3s;
+            -webkit-transition-property: box-shadow;
+            transition-property: box-shadow;
+            -webkit-transform: translateZ(0);
+            transform: translateZ(0);
+            box-sizing: border-box;
+            box-shadow: 2px 2px 2px #999999;
+            cursor : pointer;
+        }
+        .status:hover{
+            box-shadow: 2px 2px 2px #999999;
+            cursor : pointer;
+            background: #51b7e6;
+        }
+
+    </style>
+    <!-- JS 鏂规硶 -->
+    <script>
+        var j$ = jQuery.noConflict();
+
+        j$(document).ready(function() {
+                var status = '{!tsr.TSReportStatus__c}';
+                //alert(status);
+                if(status == '鑽夋涓�'){
+                    j$(escapeVfId('status1')).attr('class','qqq');
+                }else if(status == '鐢宠涓�'){
+                    j$(escapeVfId('status1')).attr('class','qqq');
+                    j$(escapeVfId('status2')).attr('class','qqq');
+                }else if(status == '纭'){
+                    j$(escapeVfId('status1')).attr('class','qqq');
+                    j$(escapeVfId('status2')).attr('class','qqq');
+                    j$(escapeVfId('status3')).attr('class','qqq');
+                    
+                }else{
+                    j$(escapeVfId('status1')).attr('class','qqq');
+                    j$(escapeVfId('status4')).attr('class','qqq');
+                }
+
+                isOncilck();
+            
+        });
+
+         // 鐜嬮箯浼� 璁剧疆鎸夐挳鏄惁鍙互鐐瑰嚮 寮�濮�
+        function isOncilck(){
+            var onclickType = '{!onclickType}';
+            var status = '{!tsr.TSReportStatus__c}';
+            //console.info("onclickType:"+onclickType);
+            if (onclickType == '-1') {
+                j$(escapeVfId('status1')).css("pointer-events","none");
+                j$(escapeVfId('status2')).css("pointer-events","none");
+                j$(escapeVfId('status3')).css("pointer-events","none");
+                j$(escapeVfId('status4')).css("pointer-events","none");
+            } else if(onclickType == '0'){
+                //onclickType == 0 鎵瑰噯锛岄┏鍥炶缃负涓嶅彲鐐瑰嚮
+                j$(escapeVfId('status3')).css("pointer-events","none");
+                j$(escapeVfId('status4')).css("pointer-events","none");
+            }else if(onclickType == '1'){
+                //onclickType == 1 鑽夋锛岀敵璇疯缃负涓嶅彲鐐瑰嚮
+                console.info("onclickType="+onclickType);
+                j$(escapeVfId('status1')).css("pointer-events","none");
+                j$(escapeVfId('status2')).css("pointer-events","none");
+
+                if(status == '纭' || status == '鑽夋涓�'){
+                    j$(escapeVfId('status1')).css("pointer-events","none");
+                    j$(escapeVfId('status2')).css("pointer-events","none");
+                    j$(escapeVfId('status3')).css("pointer-events","none");
+                    j$(escapeVfId('status4')).css("pointer-events","none");
+                }
+                if(status == '椹冲洖'){
+                    j$(escapeVfId('status3')).css("pointer-events","none");
+                    j$(escapeVfId('status4')).css("pointer-events","none");
+                }
+            } else {
+                if(status == '纭'){
+                    j$(escapeVfId('status1')).css("pointer-events","none");
+                    j$(escapeVfId('status2')).css("pointer-events","none");
+                    j$(escapeVfId('status3')).css("pointer-events","none");
+                    j$(escapeVfId('status4')).css("pointer-events","none");
+                }
+            }
+        }
+        // 鐜嬮箯浼� 璁剧疆鎸夐挳鏄惁鍙互鐐瑰嚮 缁撴潫
+        //<!-- 鐜嬮箯浼� 鐐瑰嚮鎸夐挳鏇存柊鐘舵�佸紑濮� -->
+        function setStatusJS(str){
+            var rId = '{!tsr.id}';
+            console.info(rId+"--------"+str);
+           blockme();
+           setStatus(str);
+           var status = '{!tsr.TSReportStatus__c}';
+                /*alert(status);*/
+            if(status == '鑽夋涓�'){
+                j$(escapeVfId('status1')).attr('class','qqq');
+                j$(escapeVfId('status2')).attr('class','status');
+                j$(escapeVfId('status3')).attr('class','status');
+                j$(escapeVfId('status4')).attr('class','status');
+            }else if(status == '鐢宠涓�'){
+                j$(escapeVfId('status1')).attr('class','qqq');
+                j$(escapeVfId('status2')).attr('class','qqq');
+                j$(escapeVfId('status3')).attr('class','status');
+                j$(escapeVfId('status4')).attr('class','status');
+        
+            }else if(status == '纭'){
+                j$(escapeVfId('status1')).attr('class','qqq');
+                j$(escapeVfId('status2')).attr('class','qqq');
+                j$(escapeVfId('status3')).attr('class','qqq');
+                j$(escapeVfId('status4')).attr('class','status');
+                
+            }else{
+                j$(escapeVfId('status1')).attr('class','qqq');
+                j$(escapeVfId('status2')).attr('class','status');
+                j$(escapeVfId('status3')).attr('class','status');
+                j$(escapeVfId('status4')).attr('class','qqq');
+            }
+        }
+        //<!-- 鐜嬮箯浼� 鐐瑰嚮鎸夐挳鏇存柊鐘舵�佺粨鏉� -->
+
+        function saveJs() {
+            if(confirm('鏄惁淇濆瓨淇敼?')==true){
+                blockme();
+                saveBtn();
+            }
+        }
+
+        function test(line){
+            
+            var managementCode = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':managementCode')).value();
+            var firstinputOriginalValue = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':firstinputOriginalValue')).value();
+            
+            var mark = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':firstinput')).value();
+            if (mark == ''){
+                alert('棣栨鐧婚檰妗堜欢涓嶈兘涓虹┖');
+                j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':firstinput')).val(firstinputOriginalValue);
+                return; 
+            } else {
+                if(managementCode != '' && mark == '鏄�' && firstinputOriginalValue == '鍚�'){
+                    if(confirm('纭畾瑕佽В闄や笌 [ '+managementCode+' ] 妗堜欢鐨勫叧鑱斿悧锛� 瑙i櫎鍏宠仈浼氭竻绌轰笌妗堜欢鐩稿叧鐨勫唴瀹�')==true){
+            
+                    } else {
+                        j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':firstinput')).val(firstinputOriginalValue); 
+                    }
+               } 
+            }
+            if(mark == '鏄�'){
+                j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':managementCode')).attr("disabled","disabled");
+            } 
+            else if(mark == '鍚�'){
+                setFirstinput(line);
+            } 
+        }
+
+        function ServiceType(line){
+
+            var TSRepairFirstSubmission = j$(escapeVfId("TSRepairFirstSubmission")).value();
+            var ServiceType = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':serviceType')).value();
+            var serviceTypeReference = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':serviceTypeReference')).value();
+            var baId = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':baId')).value();
+            var lineNo = Number(line) + Number(1); 
+            if (ServiceType == '' && baId != '') {
+                    if(confirm('纭畾瑕佸垹闄ょ [ '+lineNo+' ]涓� 涓氬姟娲诲姩鍚楋紵')==true){
+                    
+                    } else {
+                       j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':serviceType')).val(serviceTypeReference); 
+                    }
+            }
+            updateServiceCategory(line);
+        }
+
+        function timecheck(line){
+           
+            var end_minute = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idEndMinuteText')).value();
+            var end_hour = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idEndHourTextt')).value();
+            var start_minute = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idStartMinuteText')).value();
+            var start_hour = j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idActStartHour')).value();
+            
+            var em = parseInt(end_minute);
+            var eh = parseInt(end_hour);
+            var sm = parseInt(start_minute);
+            var sh = parseInt(start_hour);
+            
+            if(end_minute != '' && end_hour != '' && start_hour != '' && start_minute != ''){
+                var temp = em - sm;
+                temp = parseInt(temp);
+                if(temp != 30 && temp != -30 && temp != 0 ){
+                    alert('杈撳叆鏃堕棿蹇呴』鏃�30鍒嗛挓鐨勬暣鍊嶆暟');
+                    j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idEndMinuteText')).val(''); 
+                    j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idworkingHours')).val('');
+                    return;
+                }
+                var hour = eh - sh;
+                if (eh != 0 && sh != 0 &&  hour < 0) {
+                    alert('缁撴潫鏃堕棿蹇呴』澶т簬绛変簬璧峰鏃堕棿'); 
+                    j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idEndHourTextt')).val('');
+                    j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idworkingHours')).val('');
+                    return;   
+                } else if ((eh == 0 || sh == 0) &&  hour < 0) {
+                    j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idworkingHours')).val('');
+                    return;   
+                }
+                var timenumber = '';
+                if(temp == -30){
+                    timenumber = eh - sh - 1 + '.' + '50';
+                }else if(temp == 30){
+                    timenumber = eh - sh + "." + '50';
+                }else{
+                    timenumber = eh - sh + "." + '00';
+                }
+                j$(escapeVfId('allPage:allForm:RepairInfoList:' + line + ':idworkingHours')).val(timenumber);
+            }
+
+        }
+
+        //鎶ュ憡鏃ユ湡鏇存敼鏃惰皟鐢�
+        function reportDate(){
+            blockme();
+            reportDateChage();
+        }
+        // 鏌ユ壘涓氬姟娲诲姩
+        function openSelectWindow(line, baId,ufId) {
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            var repairId = j$(escapeVfId("repairId")).value();
+            window.open(baseUrl + '/apex/SearchManagementCode?lineno=' + line + '&baId=' + encodeURIComponent(baId) + '&repairId='+encodeURIComponent(repairId) + '&ufId='+encodeURIComponent(ufId),'pselect', 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+
+        function refreshPage(fromUserFaultInfoId,lineno){
+            initBusinessActivity(fromUserFaultInfoId,lineno);
+        }
+         
+        function setVisitorPlace(index){
+            try{
+                var businessACustomerUnit = 'allPage:allForm:RepairInfoList:'+index+':BusinessACustomerUnit';
+                var strPage = null;
+                var options = {};
+                var productSegmentf = '{!use.TSUserSegment__c}';
+                if ('NDT&ANI' == productSegmentf) {
+                    productSegmentf = 'NDT/ANI';
+                }
+                strPage = '/apex/TS_SearchAccount?r='+productSegmentf;
+                options = {minchars:3, minwords:2, resultsClass:'visitorplace_results'};
+                jQuery(escapeVfId(businessACustomerUnit)).unbind();
+                if (strPage != null) {
+                    jQuery(escapeVfId(businessACustomerUnit)).suggest(strPage,options);
+                }
+            }catch(e){
+                alert(e);
+            }
+        }
+
+        function vpClear2_delay(index){
+            var accountName = 'allPage:allForm:RepairInfoList:'+index+':BusinessACustomerUnit';
+            var accountNameVal = j$(escapeVfId(accountName)).value();
+            var accountId = 'allPage:allForm:RepairInfoList:'+index+':BusinessACustomerUnitId';
+            var accountIdVal = j$(escapeVfId(accountId)).value();
+            vpClear2(index);
+        }
+
+        function vpClear2(index){
+            resetValue('allPage:allForm:RepairInfoList:'+index+':BusinessACustomerUnit');
+        }
+
+
+        
+    </script>
+        <apex:form id="allForm">
+             <!-- 鐜嬮箯浼� 鐐瑰嚮鎸夐挳鏇存柊鐘舵�佸紑濮� -->
+            <apex:actionFunction name="setStatus" action="{!setStatus}" reRender="Activities,message,Activities1" oncomplete="unblockUI();">
+           
+                <apex:param name="status" assignTo="{!status}" value="" />
+            </apex:actionFunction>
+            <!-- 鐜嬮箯浼� 鐐瑰嚮鎸夐挳鏇存柊鐘舵�佺粨鏉� -->
+            <apex:actionFunction name="updateServiceCategory" action="{!updateServiceCategory}" rerender="Activities" onComplete="unblockUI();">
+                <apex:param name="num" assignTo="{!num}" value="" />
+            </apex:actionFunction>
+
+            <apex:actionFunction name="initBusinessActivity" action="{!initBusinessActivity}" rerender="allForm" onComplete="unblockUI();">
+                <apex:param name="fromUserFaultInfoId" assignTo="{!fromUserFaultInfoId}" value="" />
+                <apex:param name="lineno" assignTo="{!lineno}" value="" />
+            </apex:actionFunction>
+
+
+            <apex:actionFunction name="addBusinessActivity" action="{!addBusinessActivity}" reRender="allPanel" oncomplete="unblockUI();" ></apex:actionFunction>
+
+            <apex:actionFunction name="reportDateChage" action="{!checkReportDate}" reRender="allForm" oncomplete="unblockUI();" >
+            </apex:actionFunction>
+
+            <apex:actionFunction name="setFirstinput"  reRender="Activities" oncomplete="unblockUI();" >
+            </apex:actionFunction>
+
+            <apex:outputPanel >
+                
+            </apex:outputPanel>
+            <input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+            <input type="hidden" id="repairId" value="{!repairId}"/>
+            <input type="hidden" id="TSRepairFirstSubmission" value="{!tsr.TSRepairFirstSubmission__c}"/>
+            <input type="hidden" id="serviceCategoryJSON" value="{!serviceCategoryJSON}"/>
+            <apex:outputPanel id="message">
+
+                <apex:pagemessages />
+            </apex:outputPanel>
+
+            <apex:outputPanel id="allPanel">
+                <apex:pageBlock title="SSBG TS 鏃ユ姤" id="unEditable" rendered="true">
+                    <table class="formtable" width="100%" border="0">
+                         <colgroup>
+                            <col width="8%"/>
+                            <col width="8%"/>
+                            <col width="8%"/>
+                            <col width="8%"/>
+                            <col width="8%"/>
+                            <col width="12%"/>
+                            <col width="5%"/>
+                            <col width="5%"/>
+                            <col width="8%"/>
+                            <col width="14.4%"/>
+                        </colgroup>
+
+                        <tr>
+                            <td align="center" >鍛樺伐ID锛�</td>
+                            <td align="center" ><apex:outputField value="{!tsr.TSRepairEmployeeID__c}"/></td>
+                            <td align="center" >鎶ュ憡浜猴細</td>
+                            <td align="center" ><apex:outputField value="{!tsr.TSReportName__c}"/></td>
+                            <td align="center" >鎵�灞為儴/璇撅細</td>
+                            <td align="left" ><apex:outputField value="{!tsr.TSRepairDepartmenClass__c}"/></td>
+                            <td align="left" >鎵�灞炲尯鍩燂細</td>
+                            <td align="center" ><apex:outputField value="{!tsr.TSRepairUserArea__c}"/></td>
+                            <td align="center" >鏃ユ姤鐘舵�侊細</td>
+                             <td >
+                                <div class="status" id="status1" onclick="setStatusJS('鑽夋涓�');">鑽夋涓�</div>
+                                <div class="status" id="status2" onclick="setStatusJS('鐢宠涓�');">鐢宠涓�</div>
+                                <div class="status" id="status3" onclick="setStatusJS('纭');">纭�&nbsp;&nbsp;璁�</div>
+                                <div class="status" id="status4" onclick="setStatusJS('椹冲洖');">椹�&nbsp;&nbsp;鍥�</div>
+                                <div>
+                                    <input id="focus" value="" style="width:0px;height:0px;border: 0px;" />
+                                </div>
+                            </td>
+                            
+                        </tr>
+                        <tr>
+                            <td align="center" >鎶ュ憡鏃ユ湡锛�</td>
+                            <td align="center" ><apex:inputField id="reportDate" value="{!tsr.TSReportDate__c }" onchange="reportDate();"/>
+                            </td>
+                            <td align="center" >涓婄骇锛�</td>
+                            <td align="center" ><apex:outputField value="{!tsr.TSRepairSuperior__c}"/></td>
+                            <td align="center" >鎵瑰噯鏃ワ細</td>
+                            <td><apex:outputField value="{!tsr.TSApprovalDate__c}"/></td>
+                            <td></td>
+                            <td></td>
+                            <td align="center" >椹冲洖鐞嗙敱锛�</td>
+                            <td align="left" >
+                                <!-- 鐢宠涓� 涓婄骇 鍙紪杈�-->
+                                <apex:outputPanel id="tsrInput" rendered="{!IF( tsr.TSReportStatus__c = '鐢宠涓�' && onclickType = '1' , 'true' , 'false' )}">
+                                    <apex:inputField id="TSRepairDismissReason" value="{!tsr.TSRepairDismissReason__c }" style="width: 96%" >
+                                        
+                                    </apex:inputField>
+                                </apex:outputPanel>
+                                <!-- 闈炰笂绾� 鍙-->
+                                <apex:outputPanel id="tsrOutput" rendered="{!IF( onclickType != '1' , 'true' , 'false' )}">
+                                    <c:PDFWbr targetStr="{!tsr.TSRepairDismissReason__c}"/>
+                                </apex:outputPanel>
+                                <!-- 闈� 鐢宠涓� 涓婄骇 鍙-->
+                                <apex:outputPanel id="tsrOutput2" rendered="{!IF( tsr.TSReportStatus__c != '鐢宠涓�' && onclickType = '1', 'true' , 'false' )}">
+                                    <c:PDFWbr targetStr="{!tsr.TSRepairDismissReason__c}"/>
+                                </apex:outputPanel>
+                            </td>
+                        </tr>
+                    </table>
+                </apex:pageBlock>
+            </apex:outputPanel>
+
+                <apex:outputPanel id="Activities" rendered="{!IF( temp = '0' , 'true' , 'false' )}">
+                        <input type="hidden" id="idBusinessActivitySize" value="{!BusinessActivitySize}" />
+
+                        <apex:repeat id="RepairInfoList" value="{!RepairInfoList}" var="repairInfo">
+                            <div class="pbSubheader first tertiaryPalette">
+                        <h3>涓氬姟娲诲姩</h3>
+                        </div>
+                            <table class="formtable" width="100%" border="0" style="background-color:#E6E6FA">
+                                <colgroup>
+                                    <col width="8%"/>
+                                    <col width="14%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                </colgroup>
+                                <tr>
+                                    <th style="text-align: left;" border="2">宸ヤ綔鏃堕棿</th>
+                                    <td colspan="2"><span>
+                                        <apex:inputField id="idActStartHour" style="width:17%;ime-mode: disabled;ime-mode: disabled;text-align:left"  value="{!repairInfo.ba.StartTimeHour__c}" onchange="timecheck('{!repairInfo.lineNumber}');"></apex:inputField>
+                                    </span>
+                                    <b>锛�</b>
+                                    <span>
+                                        <apex:inputField id="idStartMinuteText" style="width:17%;ime-mode: disabled;ime-mode: disabled;text-align:left"  value="{!repairInfo.ba.StartTimeMinute__c}" onchange="timecheck('{!repairInfo.lineNumber}');"></apex:inputField>
+                                    </span>
+                                    锝�
+                                    
+                                   <span>
+                                    <apex:inputField id="idEndHourTextt" style="width:17%;ime-mode: disabled;ime-mode: disabled;text-align:left"  value="{!repairInfo.ba.EndTimeHour__c}" onchange="timecheck('{!repairInfo.lineNumber}');"></apex:inputField>
+                                    </span>
+                                    <b>锛�</b>
+                                    
+                                    <span>
+                                    <apex:inputField id="idEndMinuteText" style="width:17%;ime-mode: disabled;ime-mode: disabled;text-align:left"   value="{!repairInfo.ba.EndTimeMinute__c}" onchange="timecheck('{!repairInfo.lineNumber}');"></apex:inputField>
+                                    </span></td>
+                                    <th style="text-align: center;">鍚堣宸ユ椂</th>
+                                    <td><span><div class="requiredInput"><div class="requiredBlock"></div><apex:inputText id="idworkingHours" value="{!repairInfo.ba.workingHours__c}" style="width:150px;ime-mode: disabled;ime-mode: disabled;text-align:left" maxlength="2"/></div></span></td> 
+                                    <script>
+                                        j$(escapeVfId('allPage:allForm:RepairInfoList:{!repairInfo.lineNumber}:idworkingHours')).attr('readonly', true);
+                                    </script>                                   
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;">鏈嶅姟绫诲瀷</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.serviceType__c}" id="serviceType" onchange="ServiceType('{!repairInfo.lineNumber}');"/></td>
+                                    <td></td>
+                                    <th style="text-align: center;" >鏈嶅姟鑼冪暣</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAServiceCategory__c}" id="BusinessAServiceCategory"/></td>
+
+                                    <th style="text-align: center;">棣栨鐧婚檰妗堜欢</th>
+                                    <td align="left" ><apex:inputField id="firstinput" value="{!repairInfo.ba.firstInput__c}" onchange="test('{!repairInfo.lineNumber}');" style="width: 100%"/></td>
+                                    
+                                    <th style="text-align: center;">绠$悊缂栫爜</th>
+                                    <td align="center" ><apex:inputText id="managementCode" value="{!repairInfo.ba.FindManagementCode__c}" disabled="true" />
+                                    </td>
+                                    <td>
+                                    <apex:commandButton id="managementCodeSelect" disabled="{!IF(repairInfo.ba.firstInput__c = '鏄�',true,false)}" value="缂栫爜鎼滅储" onclick="openSelectWindow('{!repairInfo.lineNumber}','{!repairInfo.ba.Id}','{!repairInfo.uf.Id}');return false;"/>
+                                    </td>
+                                    <th></th>
+                                    <td>
+                                        <apex:inputHidden id="baId" value="{!repairInfo.BusinessActivityId}" />
+                                        <apex:inputHidden id="serviceTypeReference" value="{!repairInfo.baServiceType}" />
+                                        <apex:inputHidden id="firstinputOriginalValue" value="{!repairInfo.firstinputOriginalValue}" />
+                                    </td>
+                                </tr>
+                            </table>
+                            <table class="formtable" width="100%" border="0" style="background-color:#DCDCDC">
+                                
+                                <colgroup>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="12%"/>
+                                </colgroup>                               
+                                <tr>
+                                    <th colspan="9" style="text-align: left;">鐢ㄦ埛/鏁呴殰淇℃伅</th>
+                                </tr>
+                                 <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;" >鐢ㄦ埛锛嗕骇鍝佷俊鎭�</th>
+                                    <th style="text-align: center;" >瀹㈡埛鍗曚綅</th>
+                                    <td style="text-align: left;">
+                                        <apex:inputField id="BusinessACustomerUnit" value="{!repairInfo.ba.BusinessAAccount__c}" />
+                                    </td>
+                                    <th style="text-align: center;">鑱旂郴浜�</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAContact__c}" style="width: 80%"/></td>
+                                    <th style="text-align: center;">鑱旂郴鐢佃瘽</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAPhone_F__c}"/></td>
+                                </tr>
+                           
+                           
+                                <apex:repeat id="failureAssetList" value="{!repairInfo.failureAssetList}" var="failureAsset">
+                                        
+                                    <tr>
+                                        <th></th>
+                                        <th style="text-align: center;">鏈哄瀷</th>
+                                        <td align="left" ><apex:inputField value="{!failureAsset.model__c}" id="model"/></td>
+                                        <th style="text-align: center;">浜у搧绯诲垪</th>
+                                        <td align="left" ><apex:inputField value="{!failureAsset.FAProductSeries__c}" id="FAProductSeries"/></td>
+                                        <th style="text-align: center;">鏈鸿韩鍙�</th>
+                                        <td align="left" ><apex:inputField value="{!failureAsset.SerialNumber__c}" id="SerialNumber"/></td>
+                                        <th style="text-align: center;">淇濅慨鐘舵��</th>
+                                        <td align="left" ><apex:inputField value="{!failureAsset.WarrantyStatus__c}" id="WarrantyStatus" style="width: 100%"/></td>
+                                    </tr>
+                                </apex:repeat>
+                                <tr>
+                                    <th ></th>
+                                    <th style="text-align: center;">鍚堣鍙版暟</th>
+                                    <td align="left" ><apex:outputText value="{!repairInfo.ba.BusinessACombinedAmount__c}"/></td>
+                                    <th><apex:commandButton onclick="blockme();" id="addFailureAsset" action="{!addFailureAsset}" reRender="Activities" value="娣诲姞浜у搧" style="width: 70px;" oncomplete="unblockUI();" disabled="{!repairInfo.disabled}"><apex:param name="num" value="{!repairInfo.lineNumber}" assignTo="{!num}" /></apex:commandButton></th>
+                                </tr>
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                 <tr>
+                                    <th colspan="9" style="text-align: left;">闇�姹�/鏁呴殰淇℃伅</th>
+                                </tr>
+                                 
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鏁呴殰鍐呭</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAFaultContent__c}" id="UFFaultContent" style="width: 97%"/></td>
+                                    <th style="text-align: center;">鎶ヤ慨鏃ユ湡</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessARepairDate__c}" id="UFRepairDate" style="width: 96%" /></td>
+                                    <th style="text-align: center;">鍒ゆ柇鏃ユ湡</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessADetermineDate__c}" id="UFDetermineDate" style="width: 97%"/></td>
+                                    <th style="text-align: center;">瑕佹眰鏈嶅姟鏃ユ湡</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessADateRequest__c}" id="UFDateRequest" style="width: 95%"/></td>
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">淇℃伅鏉ユ簮</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAMessageSource__c}" id="UFMessageSource" style="width: 100%"/></td>
+                                    <th style="text-align: center;">鏈嶅姟鎬ц川</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessANatureService__c}" id="UFNatureService" style="width: 100%"/></td>
+                                    <th style="text-align: center;">鏃犲伩鍘熷洜</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAWithoutReason__c}" id="UFWithoutReason" style="width: 100%"/></td>        
+                                </tr>
+                        
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th colspan="9" style="text-align: left;">鏈涓氬姟娲诲姩鐨勫唴瀹�</th>
+                                    
+                                </tr>
+                                <tr> 
+                                    <th></th>                                   
+                                    
+                                    <th style="text-align: center;">鏈嶅姟鍐呭</th>
+                                    <td colspan="5" >
+                                        <apex:inputText value="{!repairInfo.ba.BusinessAServiceContentNew__c}" id="BusinessAServiceContentNew" style="width:99.5%; height:30px; resize:none;"/>
+                                    </td>
+                                    <th style="text-align: center;">鏈嶅姟鍚堝悓鍙�</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAServiceContractNo__c}" id="BusinessAServiceContractNo" /></td>          
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鏈嶅姟鍦烘墍</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAServicePlace__c}" id="BusinessAServicePlace" style="width: 100%"/>
+                                    </td>
+                                    <th style="text-align: center;">鍑哄樊鍦�</th>
+                                    <td align="left"><apex:inputField value="{!repairInfo.ba.BusinessABusinessTrip__c}" id="BusinessABusinessTrip" style="width: 96%"/>
+                                    </td>
+                                    <th style="text-align: center;">妗堜欢瀹屾垚鏃�</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessACompletionDate__c}" id="BusinessACompletionDate" style="width: 98%"/>
+                                    </td>
+                                    <th style="text-align: center;">涓嬫鏈嶅姟鏃堕棿</th> 
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessANextService__c}" id="BusinessANextService" style="width: 96%"/>
+                                    </td> 
+                                    
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">娲鹃仯鍛ㄦ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADispatchTime__c}" id="BusinessADispatchTime" style="width: 100%"/>
+                                    </td>
+                                    <th style="text-align: center;">缁翠慨鍛ㄦ湡</th>
+                                    <td align="left"><apex:outputField value="{!repairInfo.ba.BusinessAMaintainTime__c}" id="BusinessAMaintainTime" style="width: 96%"/>
+                                    </td>
+                                    <th style="text-align: center;">鍋滄満鏃堕棿</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADowntime__c}" id="BusinessADowntime" style="width: 98%"/>
+                                    </td>
+                                    <th style="text-align: center;">鏈嶅姟缁撴灉</th> 
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAServiceResult__c}" id="BusinessAServiceResult" style="width: 100%"/>
+                                    </td> 
+                                    
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鎶ヤ环鏃ユ湡</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessADateQuotation__c}" id="BusinessADateQuotation" style="width: 95%"/></td>
+                                    <th style="text-align: center;">鍚屾剰鎶ヤ环鏃ユ湡</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessADateApproval__c}" id="UFDateApproval" style="width: 95%"/></td>
+                                </tr>
+                                <tr>
+                                     <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th colspan="9" style="text-align: left;">寰�娆℃湇鍔″唴瀹�</th>
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鏈嶅姟鍐呭(姹囨��)</th>
+                                    <td colspan="8"><apex:outputField id="response" value="{!repairInfo.ba.BusinessAServiceContent__c
+                                    }" style="width:99.5%; height:120px; resize:none;"/>
+                                    </td>
+                                    <script>
+                                        j$(escapeVfId('allPage:allForm:RepairInfoList:{!repairInfo.lineNumber}:response')).attr('readonly', true);
+                                    </script>
+                                </tr>
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;">闄勪欢</th>
+                                    <th></th>
+                                    <th></th>
+                                    <th>
+                                        <apex:commandButton id="uploadingAttachment" reRender="message,allPanel,allForm"  value="闄勪欢涓婁紶" onclick="blockme();" action="{!uploadingAttachment}" oncomplete="unblockUI();" ><apex:param name="baIds" value="{!repairInfo.ba.Id}/{!repairInfo.lineNumber}" assignTo="{!baIds}"/>
+                                        </apex:commandButton>
+                                    </th>
+                                </tr>
+                                 <tr>
+                                        <th></th>
+                                        <th style="text-align: center;">鏍囬</th>
+                                        <th></th>
+                                        <th style="text-align: center;">涓婃淇敼鏃堕棿</th>
+                                        <th></th>
+                                        <th style="text-align: center;">鍒涘缓浜�</th>
+                                </tr>
+                                <apex:repeat id="attachmentLsit" value="{!repairInfo.attachmentLsit}" var="attachment" >
+                                        
+                                    <tr>
+                                        <th></th>
+                                        <td> <apex:outputLink value="/{!attachment.Id}" target="LINK_{!attachment.Id}"><c:PDFWbr targetStr="{!attachment.Name}" /></apex:outputLink>
+                                        </td>
+                                        <th></th>
+                                        <td align="center"><apex:outputField value="{!attachment.CreatedDate}"/></td>
+                                        <th></th>
+                                        <td align="center"><apex:outputField value="{!attachment.OwnerId}"/></td>
+                                    </tr>
+                                </apex:repeat>
+                                 <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;">瀹℃壒鎰忚</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAApprovalOpinion__c}" id="BusinessAApprovalOpinionOutput"  style="width: 100%"/>
+                                    </td>
+                                    <th></th>
+                                    <th style="text-align: center;">鎰忚</th>
+                                    <td align="left"><apex:outputField value="{!repairInfo.ba.BusinessAOpinion__c}" id="BusinessAOpinionOutput"/>
+                                    </td>
+                                </tr>
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+
+                                
+                            </table>
+                
+                            <br/>
+                            <br/>
+                            <hr/>
+                            <br/>
+                            <br/>
+                        </apex:repeat>
+
+                </apex:outputPanel>
+
+                <apex:outputPanel rendered="{!IF( temp = '1' , 'true' , 'false' )}" id="Activities1">
+                        <input type="hidden" id="idBusinessActivitySize" value="{!BusinessActivitySize}" />
+
+                        <apex:repeat value="{!RepairInfoList}" var="repairInfo">
+                            <div class="pbSubheader first tertiaryPalette">
+                        <h3>涓氬姟娲诲姩</h3>
+                        </div>
+                            <table class="formtable" width="100%" border="0" style="background-color:#E6E6FA">
+                                <colgroup>
+                                    <col width="8%"/>
+                                    <col width="14%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                </colgroup>
+                                <tr>
+                                    <th style="text-align: left;" border="2">宸ヤ綔鏃堕棿</th>
+                                    <td colspan="2"><span>
+                                        <apex:outputField id="idActStartHour" style="width:17%"  value="{!repairInfo.ba.StartTimeHour__c}" ></apex:outputField>
+                                    </span>
+                                    <b>锛�</b>
+                                    <span>
+                                        <apex:outputField id="idStartMinuteText" style="width:17%"  value="{!repairInfo.ba.StartTimeMinute__c}" ></apex:outputField>
+                                    </span>
+                                    锝�
+                                    
+                                   <span>
+                                    <apex:outputField id="idEndHourTextt" style="width:17%" value="{!repairInfo.ba.EndTimeHour__c}" ></apex:outputField>
+                                    </span>
+                                    <b>锛�</b>
+                                    
+                                    <span>
+                                    <apex:outputField id="idEndMinuteText" style="width:17%;"   value="{!repairInfo.ba.EndTimeMinute__c}"></apex:outputField>
+                                    </span></td>
+                                    <th style="text-align: center;">鍚堣宸ユ椂</th>
+                                    <td><span><div class="requiredInput"><div class="requiredBlock"></div><apex:outputText id="idworkingHours" value="{!repairInfo.ba.workingHours__c}" style="width:150px;ime-mode: disabled;ime-mode: disabled;text-align:left"/></div></span></td> 
+                                    <script>
+                                        j$(escapeVfId('allPage:allForm:RepairInfoList:{!repairInfo.lineNumber}:idworkingHours')).attr('readonly', true);
+                                    </script>                                   
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;">鏈嶅姟绫诲瀷</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.serviceType__c}" id="serviceType"/></td>
+                                    <td></td>
+                                    <th style="text-align: center;" >鏈嶅姟鑼冪暣</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAServiceCategory__c}" id="BusinessAServiceCategory"/></td>
+
+                                    <th style="text-align: center;">棣栨鐧婚檰妗堜欢</th>
+                                    <td align="left" ><apex:outputField id="firstinput" value="{!repairInfo.ba.firstInput__c}"  style="width: 100%"/></td>
+                                    
+                                    <th style="text-align: center;">绠$悊缂栫爜</th>
+                                    <td align="center" ><apex:outputText id="managementCode" value="{!repairInfo.ba.FindManagementCode__c}"/></td>
+                                    <th></th>
+                                </tr>
+                            </table>
+                            <table class="formtable" width="100%" border="0" style="background-color:#DCDCDC">
+                                
+                                <colgroup>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="11%"/>
+                                    <col width="12%"/>
+                                </colgroup>                               
+                                <tr>
+                                    <th colspan="9" style="text-align: left;">鐢ㄦ埛/鏁呴殰淇℃伅</th>
+                                </tr>
+                                 <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;" >鐢ㄦ埛锛嗕骇鍝佷俊鎭�</th>
+                                    <th style="text-align: center;" >瀹㈡埛鍗曚綅</th>
+                                    <td style="text-align: left;"><apex:outputField value="{!repairInfo.ba.BusinessAAccount__c}" style="width: 80%"/></td>
+                                    <th style="text-align: center;">鑱旂郴浜�</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAContact__c}" style="width: 80%"/></td>
+                                    <th style="text-align: center;">鑱旂郴鐢佃瘽</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAPhone_F__c}"/></td>
+                                </tr>
+                           
+                           
+                                <apex:repeat id="failureAssetList" value="{!repairInfo.failureAssetList}" var="failureAsset">
+                                        
+                                    <tr>
+                                        <th></th>
+                                        <th style="text-align: center;">鏈哄瀷</th>
+                                        <td align="left" ><apex:outputField value="{!failureAsset.model__c}" id="model"/></td>
+                                        <th style="text-align: center;">浜у搧绯诲垪</th>
+                                        <td align="left" ><apex:outputField value="{!failureAsset.FAProductSeries__c}" id="FAProductSeries"/></td>
+                                        <th style="text-align: center;">鏈鸿韩鍙�</th>
+                                        <td align="left" ><apex:outputField value="{!failureAsset.SerialNumber__c}" id="SerialNumber"/></td>
+                                        <th style="text-align: center;">淇濅慨鐘舵��</th>
+                                        <td align="left" ><apex:outputField value="{!failureAsset.WarrantyStatus__c}" id="WarrantyStatus" style="width: 100%"/></td>
+                                    </tr>
+                                </apex:repeat>
+                                <tr>
+                                    <th ></th>
+                                    <th style="text-align: center;">鍚堣鍙版暟</th>
+                                    <td align="left" ><apex:outputText value="{!repairInfo.ba.BusinessACombinedAmount__c}"/></td>
+                                   
+                                </tr>
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                 <tr>
+                                    <th colspan="9" style="text-align: left;">闇�姹�/鏁呴殰淇℃伅</th>
+                                </tr>
+                                 
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鏁呴殰鍐呭</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAFaultContent__c}" id="UFFaultContent" style="width: 97%"/></td>
+                                    <th style="text-align: center;">鎶ヤ慨鏃ユ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessARepairDate__c}" id="UFRepairDate" style="width: 96%"/></td>
+                                    <th style="text-align: center;">鍒ゆ柇鏃ユ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADetermineDate__c}" id="UFDetermineDate" style="width: 97%"/></td>
+                                    <th style="text-align: center;">瑕佹眰鏈嶅姟鏃ユ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADateRequest__c}" id="UFDateRequest" style="width: 95%"/></td>
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">淇℃伅鏉ユ簮</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAMessageSource__c}" id="UFMessageSource" style="width: 100%"/></td>
+                                    <th style="text-align: center;">鏈嶅姟鎬ц川</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessANatureService__c}" id="UFNatureService" style="width: 100%"/></td>
+                                    <th style="text-align: center;">鏃犲伩鍘熷洜</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAWithoutReason__c}" id="UFWithoutReason" style="width: 100%"/></td>        
+                                </tr>
+                        
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th colspan="9" style="text-align: left;">鏈涓氬姟娲诲姩鐨勫唴瀹�</th>
+                                    
+                                </tr>
+                                <tr> 
+                                    <th></th>                                   
+                                    <th style="text-align: center;">鏈嶅姟鍐呭</th>
+                                    <td align="left" >
+                                        <apex:outputText value="{!repairInfo.ba.BusinessAServiceContentNew__c}" id="BusinessAServiceContentNew"/>
+                                    </td>
+                                    <th></th>
+                                    <th></th>
+                                    <th></th>
+                                    <th></th>
+                                    <th style="text-align: center;">鏈嶅姟鍚堝悓鍙�</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAServiceContractNo__c}" id="BusinessAServiceContractNo" /></td>                
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鏈嶅姟鍦烘墍</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessAServicePlace__c}" id="BusinessAServicePlace" style="width: 100%"/>
+                                    </td>
+                                    <th style="text-align: center;">鍑哄樊鍦�</th>
+                                    <td align="left"><apex:outputField value="{!repairInfo.ba.BusinessABusinessTrip__c}" id="BusinessABusinessTrip" style="width: 96%"/>
+                                    </td>
+                                    <th style="text-align: center;">妗堜欢瀹屾垚鏃�</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessACompletionDate__c}" id="BusinessACompletionDate" style="width: 98%"/>
+                                    </td>
+                                    <th style="text-align: center;">涓嬫鏈嶅姟鏃堕棿</th> 
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessANextService__c}" id="BusinessANextService" style="width: 96%"/>
+                                    </td>
+
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">娲鹃仯鍛ㄦ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADispatchTime__c}" id="BusinessADispatchTime" style="width: 100%"/>
+                                    </td>
+                                    <th style="text-align: center;">缁翠慨鍛ㄦ湡</th>
+                                    <td align="left"><apex:outputField value="{!repairInfo.ba.BusinessAMaintainTime__c}" id="BusinessAMaintainTime" style="width: 96%"/>
+                                    </td>
+                                    <th style="text-align: center;">鍋滄満鏃堕棿</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADowntime__c}" id="BusinessADowntime" style="width: 98%"/>
+                                    </td>
+                                    <th style="text-align: center;">鏈嶅姟缁撴灉</th> 
+                                    <td align="left" ><apex:outputText value="{!repairInfo.ba.BusinessAServiceResult__c}" id="BusinessAServiceResult" style="width: 96%"/>
+                                    </td> 
+                                    
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鎶ヤ环鏃ユ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADateQuotation__c}" id="BusinessADateQuotation" style="width: 95%"/></td>
+                                    <th style="text-align: center;">鍚屾剰鎶ヤ环鏃ユ湡</th>
+                                    <td align="left" ><apex:outputField value="{!repairInfo.ba.BusinessADateApproval__c}" id="UFDateApproval" style="width: 95%"/></td>
+                                </tr>
+                                <tr>
+                                     <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th colspan="9" style="text-align: left;">寰�娆℃湇鍔″唴瀹�</th>
+                                </tr>
+                                <tr>
+                                    <th></th>
+                                    <th style="text-align: center;">鏈嶅姟鍐呭(姹囨��)</th>
+                                    <td colspan="8"><apex:outputField id="response" value="{!repairInfo.ba.BusinessAServiceContent__c
+                                    }" style="width:99.5%; height:120px; resize:none;"/>
+                                    </td>
+                                    <script>
+                                        j$(escapeVfId('allPage:allForm:RepairInfoList:{!repairInfo.lineNumber}:response')).attr('readonly', true);
+                                    </script>
+                                </tr>
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;">闄勪欢</th>
+                                    <th></th>
+                                    <th></th>
+                                    <th>
+                                        
+                                    </th>
+                                </tr>
+                                 <tr>
+                                        <th></th>
+                                        <th style="text-align: center;">鏍囬</th>
+                                        <th></th>
+                                        <th style="text-align: center;">涓婃淇敼鏃堕棿</th>
+                                        <th></th>
+                                        <th style="text-align: center;">鍒涘缓浜�</th>
+                                </tr>
+                                <apex:repeat id="attachmentLsit1" value="{!repairInfo.attachmentLsit}" var="attachment" >
+                                        
+                                    <tr>
+                                        <th></th>
+                                        <td> <apex:outputLink value="/{!attachment.Id}" target="LINK_{!attachment.Id}"><c:PDFWbr targetStr="{!attachment.Name}" /></apex:outputLink>
+                                        </td>
+                                        <th></th>
+                                        <td align="center"><apex:outputField value="{!attachment.CreatedDate}"/></td>
+                                        <th></th>
+                                        <td align="center"><apex:outputField value="{!attachment.OwnerId}"/></td>
+                                    </tr>
+                                </apex:repeat>
+                                 <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+                                <tr>
+                                    <th style="text-align: left;">瀹℃壒鎰忚</th>
+                                    <td align="left" ><apex:inputField value="{!repairInfo.ba.BusinessAApprovalOpinion__c}" id="BusinessAApprovalOpinion" style="width: 100%"/>
+                                    </td>
+                                    <th></th>
+                                    <th style="text-align: center;">鎰忚</th>
+                                    <td align="left"><apex:inputField value="{!repairInfo.ba.BusinessAOpinion__c}" id="BusinessAOpinion"/>
+                                    </td>
+                                </tr>
+                                
+                                <tr>
+                                    <td colspan="9"> <hr/></td>
+                                </tr>
+
+                                
+                            </table>
+                            <br/>
+                            <br/>
+                            <hr/>
+                            <br/>
+                            <br/>
+                        </apex:repeat>
+
+                </apex:outputPanel>
+            <apex:commandButton id="test" onclick="blockme();" action="{!addBusinessActivity}" reRender="Activities" value="娣诲姞涓氬姟娲诲姩"  oncomplete="unblockUI();" disabled="{!If(tsr.TSReportStatus__c = '鐢宠涓�' || tsr.TSReportStatus__c = '纭' ,true , If((tsr.TSReportStatus__c = '鑽夋涓�' || tsr.TSReportStatus__c = '椹冲洖') && onclickType != '0',true,false))}"></apex:commandButton>
+            <apex:commandButton id="save" onclick="blockme();" action="{!save}" reRender="message,allPanel,allForm" value="淇濆瓨" style="width: 70px;" oncomplete="unblockUI();" disabled="{!If(tsr.TSReportStatus__c = '鐢宠涓�' || tsr.TSReportStatus__c = '纭',true , If((tsr.TSReportStatus__c = '鑽夋涓�' || tsr.TSReportStatus__c = '椹冲洖') && onclickType != '0',true,false))}"></apex:commandButton>
+        </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TSRepair.page-meta.xml b/scr/pages/TSRepair.page-meta.xml
new file mode 100644
index 0000000..3cc89d1
--- /dev/null
+++ b/scr/pages/TSRepair.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TSRepair</label>
+</ApexPage>
diff --git a/scr/pages/TS_SearchAccount.page b/scr/pages/TS_SearchAccount.page
new file mode 100644
index 0000000..cbc8d89
--- /dev/null
+++ b/scr/pages/TS_SearchAccount.page
@@ -0,0 +1,8 @@
+<apex:page controller="TS_SearchAccountController" action="{!search}" contentType="plain/text">
+    <apex:outputPanel layout="none" rendered="{!IsOverLimit}">
+        <span class="result_name" style="color:red;">妫�绱㈢粨鏋滆秴杩囦簡50浠�</span><span class="result_id" style="display:none"></span><br/>
+    </apex:outputPanel>
+    <apex:repeat value="{!results}" var="result" rows="50">
+        <span class="result_name">{!result.Name}</span><span class="result_id" style="display:none">{!result.Id}</span><br/>
+    </apex:repeat>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TS_SearchAccount.page-meta.xml b/scr/pages/TS_SearchAccount.page-meta.xml
new file mode 100644
index 0000000..f8b134d
--- /dev/null
+++ b/scr/pages/TS_SearchAccount.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TS_SearchAccount</label>
+</ApexPage>
diff --git a/scr/pages/TradeCustomerManager.page b/scr/pages/TradeCustomerManager.page
new file mode 100644
index 0000000..90c5955
--- /dev/null
+++ b/scr/pages/TradeCustomerManager.page
@@ -0,0 +1,528 @@
+<apex:page id="page" standardController="TradeCustomerManager__c" extensions="TradeCustomerManagerController" sidebar="true" showHeader="true" action="{!init}">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+	<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"/>
+	<style type="text/css">
+		.divObj{
+			width: 90%;
+		}
+		.divObj input[type="text"],select{
+			/*border:none;
+			outline: none;*/
+			height: 25px;
+		}
+		.divObj input,textarea,select{
+			/*background-color: #F0E68C;*/
+		}
+		.errorMessage{
+    		font-size: 15px;
+    		color:#FF0000;
+    	}
+		.juzhong{
+			vertical-align:middle!important;
+    		text-align: center;
+		}
+		.trHeight{
+			width: 100%;
+			border: 2px solid #151515;
+			border-bottom: 0px;
+			border-collapse: collapse;
+		}
+		.trHeight tr{
+			height: 30px;
+			border: 0px;
+		}
+		.trHeight td{
+			vertical-align:middle!important;
+			border: 0px;
+    		/*text-align: center;*/
+		}
+		.isproject{
+			height: 30px;
+			width: 100%;
+			border: 2px solid #151515;
+			border-collapse: collapse;
+			border-bottom: 0px;
+		}
+		.isproject tr{
+			height: 30px;
+			border: 0px;
+		}
+		.isproject td{
+			vertical-align:middle!important;
+			border: 1px solid #151515;
+    		/*text-align: center;*/
+		}
+		.fileTable{
+			width: 100%;
+			border:2px solid #151515;
+			border-collapse: collapse;
+		}
+		.fileTable th{
+			text-align: center;
+			padding:1px 5px 1px 5px;
+			border:1px solid #151515;
+		}
+		.fileTable tr{
+			height: 30px;
+		}
+		.fileTable td{
+			vertical-align:middle!important;
+			text-align: center;
+			padding:1px 5px 1px 5px;
+			border:1px solid #151515;
+		}
+		.buttonCss input,button{
+			text-decoration-color:#696969;
+			width: 80px; 
+			line-height: 20px;
+		}
+	</style>
+	<script>
+		j$(document).ready(function() {
+			
+		});
+
+		function noUpdate(){
+			var isOnClick = j$(escapeVfId("isOnClick")).value();
+			//j$(escapeVfId("page:messageForm:opportunityCode")).attr("style","display:none");
+			//j$(escapeVfId("page:messageForm:opportunityCode")).attr("readonly","readonly");
+			//j$(escapeVfId("page:messageForm:opportunityCode")).attr("type","hidden");display:none
+		}
+
+		function statusChabge(str,type){
+			if(type == "yes"){
+				j$(escapeVfId("page:messageForm:"+str+"no")).attr("checked",false);
+			}
+			if(type == "no"){
+				j$(escapeVfId("page:messageForm:"+str+"yes")).attr("checked",false);
+			}
+		}
+		function tradeCustomerApplaySave(){
+			var errorMessageValue = j$(escapeVfId("errorMessageValue")).value();
+			if (errorMessageValue!="1") {
+				var strList = errorMessageValue.split("-");
+				var errorStr = "";
+				for(var i = 0 ; i<strList.length ; i++){
+					errorStr += strList[i] + "\n";
+				}
+				alert(errorStr);
+			}
+		}
+
+		function saveAndBank(){
+			var errorMessageValue = j$(escapeVfId("errorMessageValue")).value();
+			if (errorMessageValue!="1") {
+				var strList = errorMessageValue.split("-");
+				var errorStr = "";
+				for(var i = 0 ; i<strList.length ; i++){
+					errorStr += strList[i] + "\n";
+				}
+				if(confirm(errorStr + '鏄惁杩斿洖鍚堝悓椤碉紵') == true){
+					returnOrder();
+				}
+				//noUpdate();
+			}else{
+				returnOrder();
+			}
+		}
+
+		function deleteFormJS(){
+			if(confirm('鏄惁鍒犻櫎鐢宠琛紵') == true){
+					deleteForm();
+					returnOrder();
+			}
+		}
+
+		function refreshPage(code,oppId){
+			getOppCode(code,oppId);
+		}
+
+		function openSearchOpp(){
+			var baseUrl = j$(escapeVfId("baseUrl")).value();
+			var DealerId = j$(escapeVfId("DealerId")).value();
+            //var repairId = j$(escapeVfId("repairId")).value();
+            window.open(baseUrl + '/apex/TradeCustomerManagerSearchOpp?DealerId='+DealerId,'pselect', 'width=700,height=600,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+		}
+
+        function isDeleteFile(){
+            var isDeleteFile = j$(escapeVfId("isdeleteFile")).value();
+            if(isDeleteFile == "NO"){
+                alert("鍚堝悓宸叉彁浜わ紝鐢宠琛ㄩ檮浠朵笉鍙垹闄わ紒");
+            }
+        }
+	</script>
+	<div class="divObj">
+		<apex:form id="messageForm">
+			<input id="errorMessageValue" type="hidden" value="{!errorMessage}" />
+			<input type="hidden" id="baseUrl" value="{!baseUrl}"/>
+			<input type="hidden" id="isOnClick" value="{!isOnClick}"/>
+			<input type="hidden" id="DealerId" value="{!trade.DealerId__c}"/>
+            <input type="hidden" id="isdeleteFile" value="{!isdeleteFile}"/>
+			<apex:actionFunction name="returnOrder" action="{!returnOrder}" reRender="" oncomplete="">
+			</apex:actionFunction>
+			<apex:actionFunction name="deleteForm" action="{!deleteForm}" reRender="" oncomplete="">
+			</apex:actionFunction>
+			<apex:actionFunction name="getOppCode" action="{!getOppCode}" reRender="messageForm" oncomplete="">
+				<apex:param assignTo="{!trade.oppCodeLink__c}" name="code" value=""></apex:param>
+				<apex:param assignTo="{!trade.oppId__c}" name="oppId" value=""></apex:param>
+			</apex:actionFunction>
+			<table class="trHeight">
+				<tr>
+					<td class="juzhong" colspan="4">
+						<font style="font-size:25px;font-weight:bold;border-bottom:2px solid #000;">璐告槗绠$悊鎮康瀹㈡埛锛圔绫伙級鐢宠琛�</font>
+					</td>
+				</tr>
+				<tr>
+					<td colspan="4"></td>
+				</tr>
+				<tr>
+					<td class="juzhong">
+						<font style="font-size:15px;font-weight:bold;">閲嶅瀹㈡埛</font>
+					</td>
+					<td class="juzhong">
+						<apex:inputField value="{!trade.isAloneCustomer__c}"/>
+					</td>
+					<td colspan="2">
+						<font style="font-size: 5px;color: #FF0000;">濉啓鎻愮ず锛�</font><br/>
+						<font style="color: #FF0000;">閲嶅鐢ㄦ埛鐨勫畾涔夛細2骞村唴鏇捐OCSM-B绫诲鏍搁�氳繃鐨勭敤鎴凤紙鍏蜂綋鍒版渶缁堜娇鐢ㄤ汉锛夛紝涓斿悓鏃舵弧瓒充互涓媋,b,c鐨勬潯浠躲��</font><br/>
+						<font style="color: #FF0000;">a.浣跨敤鑰呯殑鎵�灞炲崟浣嶄笌閮ㄩ棬娌℃湁鍙戠敓鍙樺寲銆�</font><br/>
+						<font style="color: #FF0000;">b.浣跨敤鑰呬粎鐢ㄤ簬姘戠敤鐨勪娇鐢ㄧ洰鐨勬病鏈夊彉鍖栥��</font><br/>
+						<font style="color: #FF0000;">c.浣跨敤鑰呭強鍏舵墍灞炵殑鏈烘瀯锛堝ぇ瀛︺�佺爺绌舵満鍏炽�佷紒涓氱瓑锛夊湪涓婂洖瀹℃壒閫氳繃鍚庢棤杩濇硶琛屼负鍙婂悎瑙勮繚鍙嶇瓑闂鐨勫彂鐢熴��</font>
+					</td>
+				</tr>
+				<tr>
+					<td colspan="4"></td>
+				</tr>
+				<tr>
+					<td class="juzhong">
+						<font style="font-size:15px;font-weight:bold;">瀹㈡埛淇℃伅鏈夋洿鏂�</font>
+					</td>
+					<td class="juzhong">
+						<apex:inputField value="{!trade.customerInfoIsUpdate__c}"/>
+					</td>
+					<td class="juzhong" style="text-align:right;">
+						<font style="font-size:15px;font-weight:bold;">宸茶瀹℃牳閫氳繃鐨勮浠峰彿&nbsp;&nbsp;&nbsp;</font>
+					</td>
+					<td>
+
+						<apex:outputPanel layout="none" rendered="{!IF(trade.oppCodeLink__c != null, true, false)}">
+							&nbsp;
+							<apex:outputLink value="/{!trade.oppId__c}">{!trade.oppCodeLink__c}</apex:outputLink>&nbsp;&nbsp;
+						</apex:outputPanel>
+						<apex:commandButton onclick="openSearchOpp();return false;" value="閫夋嫨璇环" disabled="{!isOnClick}"/>
+						<apex:outputPanel layout="none" rendered="{!IF(trade.oppCodeLink__c == null, true, false)}">
+							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+						</apex:outputPanel>
+						<apex:outputPanel layout="none" rendered="{!IF(trade.oppCodeLink__c != null, true, false)}">
+							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+						</apex:outputPanel>
+					</td>
+				</tr>
+			</table>
+			<table class="trHeight">
+				<tr  style="height: 0px">
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+					<td style="width: 10%"></td>
+				</tr>
+				<tr>
+					<td class="juzhong" colspan="10">
+						<font style="font-size:15px;font-weight:bold;">浣跨敤鑰呭強鐢ㄩ�斾俊鎭�</font>
+					</td>
+				</tr>
+				<tr>
+					<td><font style="font-size:15px;">鏈�缁堢敤鎴�</font></td>
+					<td colspan="2"><apex:outputField value="{!trade.endUser__c}"/></td>
+					<td></td>
+					<td><font style="font-size:15px;">鑱屽姟</font></td>
+					<td colspan="2"><apex:inputField value="{!trade.work__c}" style="width: 96%;"/></td>
+					<td colspan="3"></td>
+				</tr>
+				<tr>
+					<td><font style="font-size:15px;">璐拱鐩殑</font></td>
+					<td colspan="2"><apex:inputField value="{!trade.buyTo__c}" style="width: 96%;"/></td>
+					<td></td>
+					<td><font style="font-size:15px;">瑙傚療瀵硅薄</font></td>
+					<td colspan="2"><apex:inputField value="{!trade.watchObject__c}" style="width: 96%;"/></td>
+					<td colspan="3"></td>
+				</tr>
+				<tr>
+					<td>
+						<font style="font-size:15px;">鐮旂┒鏂瑰悜</font>
+					</td>
+					<td colspan="2">
+						<apex:inputField value="{!trade.studyDirection__c}" style="width: 96%;"/>
+					</td>
+					<td></td>
+					<td>
+						<font style="font-size:15px;">搴旂敤棰嗗煙</font>
+					</td>
+					<td colspan="2">
+						<apex:inputField value="{!trade.application__c}" style="width: 96%;"/>
+					</td>
+					<td colspan="3"></td>
+				</tr>
+				<tr>
+					<td colspan="2">
+						<font style="font-size:15px;">鐢ㄦ埛鏄惁鏈変釜浜虹綉鍧�</font>
+					</td>
+					<td>
+						<apex:inputField id="isHaveLink__c" onchange="" value="{!trade.isHaveLink__c}"/>
+					</td>
+					<td colspan="7"></td>
+				</tr>
+				<tr>
+					<td colspan="2">
+						<font style="font-size:15px;">IF YES,涓汉缃戝潃閾炬帴淇℃伅</font>
+					</td>
+					<td colspan="8">
+						<apex:inputField value="{!trade.peopleLink__c}" style="width: 96%;" html-placeholder="LINK"/>
+					</td>
+				</tr>
+				<tr>
+					<td colspan="2">
+						
+					</td>
+					<td colspan="8">
+						<apex:commandButton id="uploadFileButton2" action="{!uploadFile}" style="" onclick="blockme();" value="涓婁紶鏂囦欢" disabled="{!isOnClick}"/>&nbsp;
+						<apex:outputPanel rendered="{!IF(personalListSize == 0,true,false)}">
+							鍚屾涓婁紶涓汉缃戝潃PDF鏂囦欢锛堥檮浠跺懡鍚嶈鍒欙細涓汉淇℃伅+璇环鍙�+浣跨敤鑰呬釜浜轰俊鎭級
+						</apex:outputPanel>
+					  	<apex:outputPanel rendered="{!IF(personalListSize != 0,true,false)}">
+					  		&nbsp;&nbsp;
+							<apex:repeat id="personalFileList" value="{!personalFileList}" var="att">
+								<apex:commandLink id="seePersonalFileLink" value="{!att.Name}" action="{!seeFile}" onclick="blockme();" oncomplete="unblockUI();" reRender="messageForm">
+									<apex:param name="fileIdSee" assignTo="{!fileIdSee}" value="{!att.Id}" />
+								</apex:commandLink>&nbsp;
+							</apex:repeat>
+						</apex:outputPanel>
+					</td>
+				</tr>
+				<tr class="" id="isHaveLinkNo">
+					<td colspan="2">
+						<font style="font-size:15px;">IF NO,鎵�鍦ㄥ崟浣嶇綉鍧�</font>
+					</td>
+					<td colspan="8">
+						<apex:inputField value="{!trade.companyLink__c}" style="width: 96%;" html-placeholder="濡傚崟浣嶆棤瀹樼綉锛岃鐢ㄦ枃瀛楀璇ヤ紒涓氳繘琛岀畝鍗曚粙缁�"/>
+					</td>
+				</tr>
+				<tr>
+					<td  colspan="2">
+						<font style="font-size:15px;">鏄惁鍗曠嫭閮ㄥ搧閲囪喘</font>
+					</td>
+					<td>
+						<apex:inputField value="{!trade.isAlone__c}"/>
+					</td>
+					<td>
+						<font style="font-size:15px;">IF YES,涓绘満鍨嬪彿锛�</font>
+					</td>
+					<td  colspan="3">
+						<apex:inputField value="{!trade.model__c}" style="width: 96%;"/>
+					</td>
+					<td>
+						<font style="font-size:15px;">IF YES,涓绘満鍚堝悓鍙凤細</font>
+					</td>
+					<td  colspan="2">
+						<apex:inputField value="{!trade.contractNum__c}" style="width: 96%;"/>
+					</td>
+				</tr>
+				<!-- <tr>
+					<td  colspan="2">
+						<font style="font-size:15px;">鏄惁PC/鏄剧ず鍣ㄩ噰璐�</font>
+					</td>
+					<td>
+						<apex:inputField value="{!trade.isPC__c}"/>
+					</td>
+					<td>
+						<font style="font-size:15px;">IF YES,涓绘満鍨嬪彿锛�</font>
+					</td>
+					<td  colspan="3">
+						<apex:inputField value="{!trade.PCmodel__c}" html-placeholder="涓绘満鍨嬪彿+SET+(鏈�缁堢敤鎴峰崟浣嶅悕锛�" style="width: 96%;"/>
+					</td>
+					<td>
+						<font style="font-size:15px;">IF YES,涓绘満鍚堝悓鍙凤細</font>
+					</td>
+					<td  colspan="2">
+						<apex:inputField value="{!trade.PCcontractNum__c}" style="width: 96%;"/>
+					</td>
+				</tr> -->
+			</table>
+
+			<table class="isproject" cellspacing="0" cellpadding="1">
+				<tr style="height: 0px;border: 0px;">
+					<td style="width: 10%;border: 0px"></td>
+					<td style="width: 10%;border: 0px"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+					<td style="width: 10%;border: 0px;"></td>
+				</tr>
+				<tr>
+					<td colspan="10" class="juzhong" style="border-top: 0px">
+						<span style="font-size:15px;">纭椤圭洰</span>
+					</td>
+				</tr>
+				<tr>
+					<td colspan="9" >
+						<span>鐢ㄩ�旂‘璁わ細</span><br/>
+						<span>鏄惁灞炰簬鏍告鍣�/鍐涚敤姝﹀櫒鐨勫紑鍙戙�佸埗閫犮�佷娇鐢ㄣ�佸偍瀛�</span>
+					</td>
+					<td>
+						<apex:inputField id="useyes" onchange="statusChabge('use','yes')" value="{!trade.useYes__c}" style="height: "/>YES<br/>
+						<apex:inputField id="useno" onchange="statusChabge('use','no')" value="{!trade.useNo__c}"/>NO
+					</td>
+				</tr>
+				<tr>
+					<td colspan="9" >
+						<span>鐢ㄩ�旂‘璁わ細</span><br/>
+						<span>鏄惁鏈夊弬涓庢牳鐕冩枡鐗╄川鎴栬�呮牳鍘熸枡鐗╄川銆佹牳鍙嶅簲鍫嗙殑寮�鍙戙�佸埗閫犮�佷娇鐢ㄣ�佸偍钘忓強鏍歌瀺鍚堢殑鍏宠仈鐮旂┒</span>
+					</td>
+					<td>
+						<apex:inputField id="fuelyes" onchange="statusChabge('fuel','yes')" value="{!trade.isFuelYes__c}" style="height: "/>YES<br/>
+						<apex:inputField id="fuelno" onchange="statusChabge('fuel','no')" value="{!trade.isFuelNo__c}"/>NO
+					</td>
+				</tr>
+				<tr>
+					<td colspan="9" >
+						<span>鐢ㄦ埛纭锛�</span><br/>
+						<span>鐢ㄦ埛褰撳墠鎴栬繃鍘绘槸鍚﹀叧鑱旀牳姝﹀櫒/鍐涚敤姝﹀櫒鐨勫紑鍙戙�佸埗閫犮�佷娇鐢ㄣ�佸偍瀛�</span>
+					</td>
+					<td>
+						<apex:inputField id="useryes" onchange="statusChabge('user','yes')" value="{!trade.userYes__c}"/>YES<br/>
+						<apex:inputField id="userno" onchange="statusChabge('user','no')" value="{!trade.userNo__c}"/>NO	
+					</td>
+				</tr>
+				<tr>
+					<td colspan="9" >
+						<span>鍦烘墍纭锛�</span><br/>
+						<span>瀹夎鍦烘墍鎴栦娇鐢ㄥ満鎵�鏄惁鍦ㄥ啗浜嬬鍖烘垨閭昏繎鍐涗簨鍐涘尯鎴栨満瀵嗙骇鍒姹傞珮鐨勫尯鍩�</span>
+					</td>
+					<td>
+						<apex:inputField id="placeyes" onchange="statusChabge('place','yes')" value="{!trade.placeYes__c}"/>YES<br/>
+						<apex:inputField id="placeno" onchange="statusChabge('place','no')" value="{!trade.placeNo__c}"/>NO	
+					</td>
+				</tr>
+				<tr>
+					<td colspan="9" >
+						<span>浜у搧閰嶄欢纭锛�</span><br/>
+						<span>閰嶄欢鏄惁瓒呭嚭浜嗗父瑙勯厤缃�</span>
+					</td>
+					<td>
+						<apex:inputField id="productyes" onchange="statusChabge('product','yes')" value="{!trade.productYes__c}"/>YES<br/>
+						<apex:inputField id="productno" onchange="statusChabge('product','no')" value="{!trade.productNo__c}"/>NO	
+					</td>
+				</tr>
+				<tr>
+					<td style="vertical-align:text-top!important;text-align: center;">
+						<span style="font-size:15px;">澶囨敞锛�</span>
+					</td>
+					<td colspan="9" >
+						<apex:inputField value="{!trade.remark__c}" style="width: 98%;" html-placeholder="纭椤圭洰鏈変换浣曚竴椤归�墆es锛屽娉ㄥ繀濉�" />
+					</td>
+				</tr>
+				<tr>
+					<td colspan="10">
+						<span style="font-size:15px;">浣跨敤鑰呯殑鍐涚敤鍏宠仈web妫�绱㈤摼鎺�</span>
+					</td>
+				</tr>
+				<tr>
+					<td colspan="10">
+						<apex:inputField value="{!trade.militaryLink__c}" style="width: 98%" html-placeholder="鎼滅储鍏抽敭璇嶆牸寮忥細鈥滃叕鍙稿悕 浣跨敤鑰呭鍚� 鍐涗簨鈥� 鍏抽敭璇嶄腑闂撮渶绌轰竴鏍笺�傞摼鎺ヨ涓嶈鍚腑鏂囧瓧绗︺��"/>
+					</td>
+				</tr>
+				<tr>
+					<td colspan="10" style="border-bottom: 0px;">
+						<!-- <apex:outputPanel rendered="{!IF(militaryListSize == 0,true,false)}"> -->
+							<span style="font-size:15px;">鍚屾涓婁紶鍐涗簨鍏宠仈web妫�绱DF鏂囦欢</span>&nbsp;&nbsp;
+							<span>闄勪欢鍛藉悕瑙勫垯锛氬啗浜�+璇环鍙�+鍐涗簨鍏宠仈web妫�绱�</span>
+						<!-- </apex:outputPanel> -->
+						
+						<apex:commandButton id="uploadFileButton3" action="{!uploadFile}" style="width: 80px; line-height: 20px;" onclick="blockme();" value="涓婁紶鏂囦欢" disabled="{!isOnClick}">
+					  	</apex:commandButton>
+
+					  	<apex:outputPanel rendered="{!IF(militaryListSize != 0,true,false)}">
+					  		&nbsp;&nbsp;
+							<apex:repeat id="militaryFileList" value="{!militaryFileList}" var="att">
+								<apex:commandLink id="militaryListSize" value="{!att.Name}" action="{!seeFile}" onclick="blockme();" oncomplete="unblockUI();" reRender="messageForm">
+									<apex:param name="fileIdSee" assignTo="{!fileIdSee}" value="{!att.Id}" />
+								</apex:commandLink>&nbsp;
+							</apex:repeat>
+						</apex:outputPanel>
+					</td>
+				</tr>
+			</table>
+			<table class="fileTable" cellspacing="0" cellpadding="1">
+				<tr>
+					<td colspan="4" style="text-align: left;">
+						<span style="font-size:15px;">鍏朵粬闄勪欢</span>&nbsp;&nbsp;
+						<apex:commandButton id="uploadFileButton1" action="{!uploadFile}" style="width: 80px; line-height: 20px;" onclick="blockme();" value="涓婁紶鏂囦欢" disabled="{!isOnClick}">
+					  	</apex:commandButton>
+					</td>
+				</tr>
+				<tr>
+					<th>鏂囦欢鍚�</th>
+					<th>涓婁紶鏃堕棿</th>
+					<th>鍒涘缓浜�</th>
+					<th>鎿嶄綔</th>
+				</tr>
+				<apex:repeat id="fileList" value="{!fileListNew}" var="att">
+					<tr>
+						<td>{!att.Name}</td>
+						<td><apex:inputField value="{!att.CreatedDate}" style="margin:1px 10px 1px 2px;"/></td>
+						<td><apex:inputField value="{!att.CreatedById}"/></td>
+						<td>
+							<apex:commandLink id="deleteFileLink" value="鍒犻櫎" action="{!deleteFile}" onclick="blockme();" oncomplete="unblockUI();isDeleteFile();" reRender="messageForm">
+								<apex:param name="fileIdDelete" assignTo="{!fileIdDelete}" value="{!att.Id}" />
+							</apex:commandLink>&nbsp;&nbsp;
+
+							<apex:commandLink id="seeFileLink" value="璇︽儏" action="{!seeFile}" onclick="blockme();" oncomplete="unblockUI();" reRender="messageForm">
+								<apex:param name="fileIdSee" assignTo="{!fileIdSee}" value="{!att.Id}" />
+							</apex:commandLink>
+						</td>
+					</tr>
+				</apex:repeat>
+			</table>
+			<div style="display: table;margin:0 auto;width:auto;">
+				<div style="display: table;margin:0 auto;width:auto;float: left;">
+				  	<apex:commandButton id="saveButton" action="{!send}" style="width: 80px; line-height: 20px;" value="淇濆瓨" onclick="blockme();"  oncomplete="unblockUI();tradeCustomerApplaySave();" reRender="messageForm" disabled="{!isOnClick}">
+				  		<apex:param name="saveSend" assignTo="{!sendType}" value="send"></apex:param>
+				  	</apex:commandButton>
+				</div>
+				<div style="display: table;margin:0 auto;width:auto;float: left;">
+					<apex:commandButton id="saveAndBankButton" action="{!send}" style="width: 80px; line-height: 20px;" onclick="blockme();" reRender="messageForm" oncomplete="unblockUI();saveAndBank();" value="淇濆瓨骞惰繑鍥�" disabled="{!isOnClick}">
+						<apex:param name="saveSend" value="send" assignTo="{!sendType}" />
+				  	</apex:commandButton>
+				</div>
+				<!-- action="{!deleteForm}" -->
+				<div style="display: table;margin:0 auto;width:auto;float: left;">
+				  	<apex:commandButton id="deleteButton" style="width: 80px; line-height: 20px;" value="鍒犻櫎鐢宠琛�" onclick="blockme();deleteFormJS();" disabled="{!isOnClick}">
+				  	</apex:commandButton>
+				</div>
+				
+			</div>
+			<!-- <div class="errorMessage" style="display: table;margin:0 auto;width:auto;">
+				<span id="errorMessage">{!errorMessage}</span>
+			</div> -->
+			<div class="errorMessage" style="display: table;margin:0 auto;width:auto;font-size: 15px;color:#00FF00;">
+				<span id="errorMessage">{!saveYes}</span>
+			</div>
+		</apex:form>
+	</div>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TradeCustomerManager.page-meta.xml b/scr/pages/TradeCustomerManager.page-meta.xml
new file mode 100644
index 0000000..ea3588e
--- /dev/null
+++ b/scr/pages/TradeCustomerManager.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TradeCustomerManager</label>
+</ApexPage>
diff --git a/scr/pages/TradeCustomerManagerSearchOpp.page b/scr/pages/TradeCustomerManagerSearchOpp.page
new file mode 100644
index 0000000..e451cd4
--- /dev/null
+++ b/scr/pages/TradeCustomerManagerSearchOpp.page
@@ -0,0 +1,75 @@
+<apex:page id="Page" Controller="TradeCustomerManagerSearchOppController" sidebar="false" showHeader="false" action="{!init}">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+
+	<style type="text/css">
+		
+	</style>
+	<script>
+		function returnTradeCustomerManager(code,oppId){
+			
+			window.opener.refreshPage(code,oppId); 
+            window.close();
+		}
+		function doSearchJS(){
+			var byName = j$(escapeVfId("byName")).value();
+			var byCode = j$(escapeVfId("byCode")).value();
+			doSearchA(byName,byCode);
+		}
+	</script>
+	<apex:form id="data">
+ 		<apex:actionFunction action="{!doSearch}" name="doSearchA">
+ 			<apex:param assignTo="{!byName}" name="byName" value=""></apex:param>
+ 			<apex:param assignTo="{!byCode}" name="byCode" value=""></apex:param>
+ 		</apex:actionFunction>
+ 		<!-- <apex:actionFunction></apex:actionFunction> -->
+ 		<div style="width: 100%;height: 500px;">
+ 			<!-- 璇环鍚嶇О锛�<input id="byName" value="{!byName}"></input>
+	 		璇环缂栧彿锛�<input id="byCode" value="{!byCode}"></input>
+	 				<apex:commandButton value="鏌ヨ" onclick="doSearchJS()"></apex:commandButton> -->
+	 		<table width="100%">
+	 			<colgroup>
+		            <col width="20%"/>
+		            <col width="20%"/>
+		            <col width="20%"/>
+		            <col width="20%"/>
+		            <col width="20%"/>
+		        </colgroup>
+		       <tr>
+	 				<td colspan="2">璇环鍚嶇О锛�<apex:inputText id="byName" value="{!byName}"></apex:inputText></td>
+	 				<td colspan="2">璇环缂栧彿锛�<apex:inputText id="byCode" value="{!byCode}"></apex:inputText></td>
+	 				<td><apex:commandButton onclick="blockme();" value="鏌ヨ" action="{!doSearch}" reRender="data" oncomplete="unblockUI();"></apex:commandButton>&nbsp;
+	 				<apex:commandButton onclick="returnTradeCustomerManager('','')" value="鍒犻櫎宸查�夎浠�" reRender="data" oncomplete="unblockUI();"></apex:commandButton></td>
+	 			</tr>
+	 			<tr>
+	 				<th colspan="2">璇环鍚�</th>
+	 				<th>璇环缂栧彿</th>
+	 				<th>瀹㈡埛</th>
+	 				<th>璐告槗绠$悊瀹㈡埛鍒嗙被</th>
+	 			</tr>
+	 		</table>
+	 		<div style="width: 100%;height: 100%;overflow:auto;">
+		 		<table width="100%">
+		 			<colgroup>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+			            <col width="20%"/>
+		        	</colgroup>
+		 			<apex:repeat value="{!oppList}" var="line" id="oppData">
+			 			<tr>
+			 				<td colspan="2"><apex:outputLink value="javascript:void(0)" onclick="returnTradeCustomerManager('{!line.InquiryNumber__c}','{!line.Id}')">{!line.Name}</apex:outputLink></td>
+			 				<td><apex:outputLink value="javascript:void(0)" onclick="returnTradeCustomerManager('{!line.InquiryNumber__c}','{!line.Id}')">{!line.InquiryNumber__c}</apex:outputLink></td>
+			 				<td>{!line.Account.Name}</td>
+			 				<td>{!line.customerType__c}</td>
+			 			</tr>
+		 			</apex:repeat>
+		 		</table>
+	 		</div>
+ 		</div>
+	 </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TradeCustomerManagerSearchOpp.page-meta.xml b/scr/pages/TradeCustomerManagerSearchOpp.page-meta.xml
new file mode 100644
index 0000000..87020de
--- /dev/null
+++ b/scr/pages/TradeCustomerManagerSearchOpp.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TradeCustomerManagerSearchOpp</label>
+</ApexPage>
diff --git a/scr/pages/TrialCustomerPortalHomePage.page b/scr/pages/TrialCustomerPortalHomePage.page
new file mode 100644
index 0000000..1d18ef7
--- /dev/null
+++ b/scr/pages/TrialCustomerPortalHomePage.page
@@ -0,0 +1,189 @@
+<apex:page controller="TrialCustomerPortalHomePageController" showHeader="false">
+<script type="text/javascript">
+
+var date1 = '{!TODAY() + 7}';
+var date2 = '{!TODAY() + 15}';
+var date3 = '{!TODAY() + 24}';
+
+</script>
+
+<apex:image value="{!URLFOR($Resource.TrialPortalBanner)}" width="804" style="margin-bottom: 3px;"/>
+<apex:form >   
+   <!-- This section shows the customer's recent cases in a table -->
+    <apex:pageBlock title="My Recent Cases">
+      <apex:pageBlockTable value="{!MyRecentCases}" var="currentCase" id="caseTable">
+         <apex:column >
+            <apex:facet name="header">
+                 <apex:commandLink value="Case Number" action="{!SortCases}" rerender="caseTable">
+                     <apex:param name="sortField2" value="CaseNumber" assignTo="{!sortField2}"/>
+                 </apex:commandLink>
+            </apex:facet>
+            <a href="/{!currentCase.id}" target="_top">{!currentCase.CaseNumber}</a>
+         </apex:column>
+         <apex:column >
+            <apex:facet name="header">
+                 <apex:commandLink value="Subject" action="{!SortCases}" rerender="caseTable">
+                     <apex:param name="sortField2" value="Subject" assignTo="{!sortField2}"/>
+                 </apex:commandLink>
+            </apex:facet>
+            <a href="/{!currentCase.id}" target="_top">{!currentCase.Subject}</a>
+         </apex:column>
+         <apex:column >
+            <apex:facet name="header">
+                 <apex:commandLink value="Status" action="{!SortCases}" rerender="caseTable">
+                     <apex:param name="sortField2" value="Status" assignTo="{!sortField2}"/>
+                 </apex:commandLink>
+            </apex:facet>
+            <apex:outputField value="{!currentCase.Status}" />
+         </apex:column> 
+
+      </apex:pageBlockTable>
+   </apex:pageBlock>
+    
+   <!-- This section shows the top solutions in a table -->
+    <div class="apexp">
+        <div class="bPageBlock brandSecondaryBrd apexDefaultPageBlock secondaryPalette">
+            <div class="pbHeader">
+                <table border="0" cellpadding="0" cellspacing="0">
+                    <tbody>
+                        <tr>
+                            <td class="pbTitle">
+                                <h2 class="mainTitle">Popular Articles</h2>
+                            </td>
+                            <td>&nbsp;</td>
+                        </tr>
+                    </tbody>
+                </table>
+            </div>
+            <div class="pbBody">
+                <table class="list " border="0" cellpadding="0" cellspacing="0">
+                    <colgroup span="2"></colgroup>
+                    <thead class="rich-table-thead">
+                        <tr class="headerRow ">
+                            <th class="headerRow  " scope="col" colspan="1">
+                                <div>
+                                    Article Title
+                                </div>
+                            </th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        <knowledge:articleList articleVar="article" sortBy="mostViewed" pageSize="10">
+                            <tr class="dataRow odd" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
+                                <td class="dataCell" colspan="1">
+                                    <a href="{!URLFOR($Action.KnowledgeArticle.View, article.id)}">{!article.title}</a>
+                                </td>
+                            </tr>      
+                        </knowledge:articleList>
+                    </tbody>
+                </table>
+            </div>
+            <div class="pbFooter secondaryPalette">
+                <div class="bg"></div>
+            </div>
+        </div>
+    </div>
+
+
+   <!-- This section shows the most popular ideas (uncomment it to show) -->
+   <!--
+   <apex:pageBlock title="Popular Ideas">
+      <apex:pageBlockTable value="{!PopularIdeas}" var="currentIdea" id="ideaTable">
+         <apex:column >
+            <apex:facet name="header">
+                 <apex:commandLink value="Idea Name" action="{!SortIdeas}" rerender="ideaTable">
+                     <apex:param name="sortField4" value="Title" assignTo="{!sortField4}"/>
+                 </apex:commandLink>
+            </apex:facet>
+            <a href="/{!currentIdea.id}" target="_top">{!currentIdea.Title}</a>
+         </apex:column>
+         <apex:column >
+            <apex:facet name="header">
+                 <apex:commandLink value="Category" action="{!SortIdeas}" rerender="ideaTable">
+                     <apex:param name="sortField4" value="Category" assignTo="{!sortField4}"/>
+                 </apex:commandLink>
+            </apex:facet>         
+            <apex:outputField value="{!currentIdea.Categories}" />
+         </apex:column>
+         <apex:column >
+            <apex:facet name="header">
+                 <apex:commandLink value="Votes" action="{!SortIdeas}" rerender="ideaTable">
+                     <apex:param name="sortField4" value="VoteTotal" assignTo="{!sortField4}"/>
+                 </apex:commandLink>
+            </apex:facet>         
+            <apex:outputField value="{!currentIdea.VoteTotal}" />         
+         </apex:column>
+      </apex:pageBlockTable>
+   </apex:pageBlock>
+    -->
+</apex:form>  
+<style>
+   .welcome_marketingheaderimage {
+        width:30%;
+        padding:10px 0;
+   }
+   body{
+    /*
+        background-color: transparent;
+    */      
+    }
+    #intro {
+        font-size: 12px;
+        font-weight: bold;
+        text-align: center;
+    }
+    
+    .text{
+        font-size: 12px;
+        text-align: top left;
+    }
+    
+    .list .headerRow th, .list .headerRow th a {
+        font-size: 12px;
+    }
+    
+    .list tr.even th, .list tr.odd th, .list tr.even td, .list tr.odd td {
+        font-size: 12px;
+    }
+    
+    .bPageBlock .pbTitle {
+        font-size: 12px;
+    }
+    
+    .bPageBlock .pbHeader { /*Header section*/
+        padding: 4px;
+    }
+    
+/** Uncomment below for Rounded Data Tables on Homepage **/
+    
+    /*
+    .bPageBlock .pbHeader { 
+        padding: 4px;
+        
+            -webkit-border-top-left-radius: 6px;
+            -moz-border-radius-topright: 6px;
+            -webkit-border-top-right-radius: 6px;
+        box-shadow: 0px 2px 6px #ccc;
+        -moz-border-radius-topleft:6px;
+        -moz-border-radius-topright:6px;
+        border-left:1px solid #C1C1C1;
+        border-right:1px solid #C1C1C1;
+        border-top:1px solid #C1C1C1;
+    }
+    .bPageBlock .pbBody {
+        -moz-border-radius-bottomleft:6px;
+        -moz-border-radius-bottomright:6px;
+        background:none repeat scroll 0 0 white;
+        border-bottom:1px solid #C1C1C1;
+        border-left:1px solid #C1C1C1;
+        border-right:1px solid #C1C1C1;
+        background-color:#FFFFFF;
+    }
+    .bPageBlock, .individualPalette .bPageBlock {
+        background:none repeat scroll 0 0 transparent;
+        border:medium none;
+        background-color:#FFFFFF;
+    }
+   */     
+</style>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TrialCustomerPortalHomePage.page-meta.xml b/scr/pages/TrialCustomerPortalHomePage.page-meta.xml
new file mode 100644
index 0000000..63e8c02
--- /dev/null
+++ b/scr/pages/TrialCustomerPortalHomePage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>Trial - Customer Portal Home Page</label>
+</ApexPage>
diff --git a/scr/pages/Trial_Tour.page b/scr/pages/Trial_Tour.page
new file mode 100644
index 0000000..7e85686
--- /dev/null
+++ b/scr/pages/Trial_Tour.page
@@ -0,0 +1,5 @@
+<apex:page >
+    <apex:includeScript value="/support/console/27.0/integration.js"/>
+    <input type="button" value="Tour - 1" onclick="sforce.console.openPrimaryTab(null, '/apex/scc_tour_main', true, 'Service Cloud Console Tour', null, 'Service Cloud Console Tour');return false;" />
+    <input type="button" value="Tour - 2" onclick="sforce.console.openPrimaryTab(null, '/apex/ca_tour_main', true, 'Communities Tour', null, 'Communities Tour');return false;" />
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/Trial_Tour.page-meta.xml b/scr/pages/Trial_Tour.page-meta.xml
new file mode 100644
index 0000000..afd7aaa
--- /dev/null
+++ b/scr/pages/Trial_Tour.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>Trial Tour</label>
+</ApexPage>
diff --git a/scr/pages/TydelikeAC.page b/scr/pages/TydelikeAC.page
new file mode 100644
index 0000000..742350d
--- /dev/null
+++ b/scr/pages/TydelikeAC.page
@@ -0,0 +1,282 @@
+<apex:page Controller="TydelikeACController" sidebar="false" action="{!init}" id="Page">
+<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+<apex:includeScript value="{!URLFOR($Resource.NewQuoteEntryJS)}"/>
+<apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+<apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+<script type="text/javascript">
+    function searchTy1(){
+        blockme();
+        searchTy();
+    }
+	function OfSkrap(linenum) {
+        var accName = j$(escapeVfId('Page:mainForm:lines:' + linenum + ':aCName')).value();
+        if(accName != ''){
+            if(confirm('瀹㈡埛宸茬粡閫夋嫨,璇烽棶鐪熺殑鍒犻櫎鍚�?')==true){
+                /*check();*/
+                blockme();
+                setOfSkrapBtn();
+            }
+        }else {
+    		if(confirm('鏄惁鍒犻櫎?')==true){
+                /*check();*/
+                blockme();
+                setOfSkrapBtn();
+    		}
+        }
+	}
+    function OfSkrap1() {
+        var bon = 0;
+        var bom = 0;
+        var tysize = j$(escapeVfId('linesize')).value();
+        for (var i = 0; i < tysize; i++) {
+            if (j$(escapeVfId('Page:mainForm:lines:' + i + ':aCbon')).attr('checked') == 'checked' && 
+                j$(escapeVfId('Page:mainForm:lines:' + i + ':aCName')).value() != '') {
+                bon += 1;
+            }
+            if (j$(escapeVfId('Page:mainForm:lines:' + i + ':aCbon')).attr('checked') == 'checked'){
+                bom += 1;
+            }
+        }
+        if (bom == 0) {
+            alert('鎮ㄦ病鏈夐�夋嫨闇�瑕佹壒閲忓垹闄ょ殑璁板綍');
+        }else if (bon == 0) {
+                if(confirm('鏄惁鎵归噺鍒犻櫎?')==true){
+                    blockme();
+                    setOfSkrapBtn();
+                    for (var i = 0; i < tysize; i++) {
+                        j$(escapeVfId('Page:mainForm:lines:' + i + ':aCbon')).attr("checked",false);
+                    }
+                }else {
+                    for (var i = 0; i < tysize; i++) {
+                        j$(escapeVfId('Page:mainForm:lines:' + i + ':aCbon')).attr("checked",false);
+                    }
+                }
+            }else {
+                if (bon == 1 && bom == 1) {
+                    if(confirm('瀹㈡埛宸茬粡閫夋嫨,璇烽棶鐪熺殑鎵归噺鍒犻櫎鍚�?')==true){
+                    blockme();
+                    setOfSkrapBtn();
+                    }else {
+                        for (var i = 0; i < tysize; i++) {
+                            j$(escapeVfId('Page:mainForm:lines:' + i + ':aCbon')).attr("checked",false);
+                        } 
+                    }
+                }else {
+                    alert('瀹㈡埛宸茬粡閫夋嫨,涓旇褰曞浜庝竴鏉�,涓嶈兘鎵归噺鍒犻櫎');
+                    for (var i = 0; i < tysize; i++) {
+                       j$(escapeVfId('Page:mainForm:lines:' + i + ':aCbon')).attr("checked",false);
+                    }
+                }
+            }
+    }
+    function gespoel() {
+        window.top.location.reload();
+    }
+    function setall(linenum) {
+        j$(escapeVfId('Page:mainForm:lines:' + linenum + ':aCbon')).attr("checked",true);
+    }
+    function setall1(linenum) {
+        j$(escapeVfId('Page:mainForm:lines:' + linenum + ':aCbon')).attr("checked",false);
+    }
+    function breakId(linenum) {
+        var baseUrl = '{!baseUrl}';
+        var accName = j$(escapeVfId('Page:mainForm:lines:' + linenum + ':aCName')).value();
+        var tycoId = j$(escapeVfId('Page:mainForm:lines:' + linenum + ':cooid')).value();
+        var tyacId = j$(escapeVfId('Page:mainForm:lines:' + linenum + ':acoid')).value();
+        if (tycoId == '') {
+            alert('娌℃湁鍙悎骞剁殑鑱旂郴浜�');
+        }else if (accName == '') {
+            alert('娌℃湁閫夋嫨闇�瑕佸悎骞惰仈绯讳汉鐨勫鎴�');
+        }else{
+            var url = baseUrl +'/apex/TydelikeCon?' + 
+            'accName=' + encodeURIComponent(accName) + 
+            '&tyacId=' + encodeURIComponent(tyacId) +
+            '&tycoId=' + encodeURIComponent(tycoId);
+            window.top.location.href = url;
+        }
+        
+    }
+    function createId(linenum) {
+        var baseUrl = '{!baseUrl}';
+        var tycoId = j$(escapeVfId('Page:mainForm:lines:' + linenum + ':cooid')).value();
+        var tyacId = j$(escapeVfId('Page:mainForm:lines:' + linenum + ':acoid')).value();
+        if (tycoId == '') {
+            var url = baseUrl +'/apex/TydelikeAcc?' + 
+            'tyacId=' + encodeURIComponent(tyacId);
+            window.top.location.href = url;
+        }else {
+            var url = baseUrl +'/apex/TydelikeAcc?' + 
+            'tyacId=' + encodeURIComponent(tyacId) + 
+            '&tycoId=' + encodeURIComponent(tycoId);
+            window.top.location.href = url;
+        }
+        
+    }
+    
+    </script>
+
+    <style type="text/css">
+        div#iframelike {
+            color: #fff;
+            height: 300px;
+            overflow: auto;
+        }
+        div#iframelikeheader {
+            color: #fff;
+            height: 23px;
+            overflow: auto;
+        }
+        .errorMessage{
+            font-size: 15px;
+            color:#FF0000;
+        }
+        input {
+            font-size: 10.5px;
+        }
+        body {
+            font-size: 10.5px;
+        }
+
+        hr {
+            height: 15px;
+            color: #fff;
+            margin: 0px;
+            padding: 0px;
+            border: 0px;
+        }
+
+    </style>
+
+    <apex:form id="mainForm">
+    	<apex:actionFunction name="setOfSkrapBtn" action="{!setOfSkrapBtn}" onComplete="unblockUI();gespoel();" rerender="mainForm,message,allPanel"></apex:actionFunction>
+        <apex:actionFunction name="searchTy" action="{!searchTy}" onComplete="unblockUI();" rerender="mainForm,message,allPanel"></apex:actionFunction>
+        <div style="width: 100%">
+            <div class="errorMessage" style="margin-left: 39%">
+                <span id="errorMessage">{!errorMessage}</span>
+            </div>
+        </div>
+        <input type="hidden" id='linesize' value="{!datalineSize}"/>
+        <apex:outputPanel id="allPanel">
+
+        <table style="width:1280px;" border="0">
+            <tr>
+                <td style="text-align:right;width:35px;">鑱旂郴浜�</td>
+                <td class="dataCell" style="text-align:center;width:150px;">
+                    <apex:inputText id="tycontactname" style="width:90%;text-align:center;" value="{!tycontactname}"/>
+                </td>
+
+                <td style="text-align:right;width:40px;">瀹㈡埛鍚嶇О</td>
+                <td class="dataCell" style="text-align:center;width:150px;">
+                    <apex:inputText id="tycountname" style="width:90%;text-align:center;" value="{!tycountname}"/>
+                </td>
+
+                <td style="text-align:right;width:20px;">鍩庡競</td>
+                <td class="dataCell" style="text-align:center;width:60px;">
+                    <apex:inputText id="tycountcity" style="width:85%;text-align:center;" value="{!tycountcity}"/>
+                </td>
+
+                <td class="dataCell" style="text-align:left;width:50px;">
+                    <apex:commandButton onclick="searchTy1();return false;" value="妫�绱�" rerender="mainForm">
+                    </apex:commandButton>
+                </td>
+                <td class="dataCell" style="text-align:center;width:560px;"></td>
+
+                <td class="dataCell" style="text-align:right;width:30px;">
+                    <apex:commandButton onclick="OfSkrap1();return false;" value="鎵归噺鍒犻櫎" rerender="mainForm">
+                    </apex:commandButton>
+                </td>
+            </tr>
+        </table>
+
+	    <table style="width:1300px;" border="0">
+	    	<tr>
+                <th style="text-align:center;width:10px;">&nbsp;&nbsp;&nbsp;鎵归噺</th>
+                <th style="text-align:center;width:210px;">{!$ObjectType.TydelikeAccount__c.fields.Name.label}</th>
+                <th style="text-align:center;width:70px;">{!$ObjectType.TydelikeAccount__c.fields.TyCity__c.label}</th>
+                <th style="text-align:center;width:150px;">{!$ObjectType.TydelikeAccount__c.fields.TyAddress__c.label}</th>
+                <th style="text-align:center;width:75px;">{!$ObjectType.TydelikeAccount__c.fields.TyPostCode__c.label}</th>
+                <th style="text-align:center;width:80px;">{!$ObjectType.TydelikeContact__c.fields.Name.label}</th>
+                <th style="text-align:center;width:150px;">{!$ObjectType.TydelikeContact__c.fields.TyAddress__c.label}</th>
+                <th style="text-align:center;width:75px;">{!$ObjectType.TydelikeContact__c.fields.TyPostcode__c.label}</th>
+                <th style="text-align:center;width:120px;">{!$ObjectType.TydelikeContact__c.fields.TyPhoneD__c.label}</th>
+                <th style="text-align:center;width:190px;">{!$ObjectType.TydelikeAccount__c.fields.Account1__c.label}</th>
+                <th style="text-align:center;width:120px;">鎿� 浣�</th>
+            </tr>
+	    </table>
+
+	    <div id="iframelike" style="width:1338px;">
+                <table class="list" style="border-bottom-width: 0px; font-size:11px; border-spacing:0; width:1200px; border-collapse: collapse; table-layout: fixed;" border="0">
+                    <apex:repeat value="{!dataLines}" var="line" id="lines">
+                    <apex:outputPanel layout="none" rendered="{!IF(line.tyacof == true || line.tycoof == true, false, true)}">
+            		<tr>
+            			<apex:inputHidden id="acoid" value="{!line.tyacId}"/>
+            			<apex:inputHidden id="cooid" value="{!line.tycoId}"/>
+            			<apex:inputHidden id="tynum" value="{!line.lineNum}"/>
+                        <apex:inputHidden id="accfs" value="{!line.tyacof}"/>
+                        <apex:inputHidden id="acofs" value="{!line.tycoof}"/>
+                        <apex:inputHidden id="acFax" value="{!line.tycofax}"/>
+                        <apex:inputHidden id="baseUrl" value="{!baseUrl}"/>
+                        <td class="dataCell" style="text-align:center;width:30px;">
+                            <apex:inputCheckbox id="aCbon" style="width:25px;text-align:center;" value="{!line.bondel}"/>
+                        </td>
+                        <td class="dataCell" style="text-align:center;width:200px;">
+                            <apex:outputText id="tAName" style="width:90%;text-align:center;" value="{!line.tyacName}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:75px;">
+                            <apex:outputText id="tACity" style="width:90%;text-align:center;" value="{!line.tyaccity}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:140px;">
+                            <apex:outputText id="tAAddress" style="width:90%;text-align:center;" value="{!line.tyacadd}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:70px;">
+                            <apex:outputText id="tAPostCode" style="width:90%;text-align:center;" value="{!line.tyacpost}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:80px;">
+                            <apex:outputText id="tYName" style="width:90%;text-align:center;" value="{!line.tycoName}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:145px;">
+                            <apex:outputText id="tYAddress" style="width:90%;text-align:center;" value="{!line.tycoadd}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:70px;">
+                            <apex:outputText id="tYPostcode" style="width:90%;text-align:center;" value="{!line.tycopost}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:110px;">
+                            <apex:outputText id="tYPhoneD" style="width:90%;text-align:center;" value="{!line.tycophone}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:190px;">
+                            <apex:inputField id="aCName" style="width:160px;text-align:left;" value="{!tya.Account1__c}"/>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:28px;">
+                        	<apex:commandButton value="鍚堝苟" onclick="breakId({!line.lineNum}); return false;">
+                            </apex:commandButton>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:28px;">
+                        	<apex:commandButton value="鍒涘缓" onclick="createId({!line.lineNum}); return false;">   
+                            </apex:commandButton>
+                        </td>
+
+                        <td class="dataCell" style="text-align:center;width:28px;">
+                        	<apex:commandButton onclick="setall({!line.lineNum}); OfSkrap({!line.lineNum}); setall1({!line.lineNum}); return false;" value="鍒犻櫎" rerender="mainForm">
+                            </apex:commandButton>
+                        </td>
+
+                    </tr>
+                </apex:outputPanel>
+                </apex:repeat>
+                </table>
+            </div>
+        </apex:outputPanel>
+	</apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TydelikeAC.page-meta.xml b/scr/pages/TydelikeAC.page-meta.xml
new file mode 100644
index 0000000..31b3419
--- /dev/null
+++ b/scr/pages/TydelikeAC.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TydelikeAC</label>
+</ApexPage>
diff --git a/scr/pages/TydelikeAcc.page b/scr/pages/TydelikeAcc.page
new file mode 100644
index 0000000..bf011eb
--- /dev/null
+++ b/scr/pages/TydelikeAcc.page
@@ -0,0 +1,321 @@
+<apex:page Controller="TydelikeAccController" sidebar="false" action="{!init}" id="Page">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <script>
+    function saveJs() {
+        blockme();
+        save();
+    }
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+    	url =baseUrl + '/apex/TydelikeAC';
+        window.top.location.href = url;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!save}" name="save" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+        <apex:inputHidden id="baseUrl" value="{!baseUrl}"/>
+
+        <apex:pageBlock id="saamvoegCon" title="鍒涘缓" tabStyle="Contact">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px"  value="淇濆瓨" onclick="saveJs(); return false;"/>
+                <apex:commandButton style="width:50px"  value="鍙栨秷" onclick="cancelJs(); return false;"/>
+            </apex:pageBlockButtons>
+
+            <apex:pageBlockSection title="瀹㈡埛淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛/浠g悊鍟嗗悕绉�." for="acc_accName"/>
+                    <apex:inputField value="{!acc.FacilityNameD__c}" id="acc_accName" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="SAP缂栫爜" for="acc_Account"/>
+                    <apex:outputField value="{!acc.ManagementCode_Ext__c}" id="acc_Account"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑻辨枃鍚嶇О." for="acc_CurrencyIsoCode"/>
+                    <apex:inputField value="{!acc.EnglishNameD__c}" id="acc_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閮ㄩ棬鍚嶇О." for="acc_Type"/>
+                    <apex:inputField value="{!acc.DivisionName_D__c}" id="acc_Type2" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绉戝." for="acc_BudgetAmount"/>
+                    <apex:inputField value="{!acc.DepartmentNameD__c}" id="acc_BudgetAmount" required="true"/>
+                </apex:pageBlockSectionItem>
+				<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="OCSM 鏈嶅姟鎷呭綋濮撳悕" for="acc_Amount1"/>
+                    <apex:inputField value="{!acc.OCNServiceStaff__c}" id="acc_Amount1"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏ㄧ悆瀹㈡埛鍚嶇О	" for="acc_Amount"/>
+                    <apex:inputField value="{!acc.GlobalAccountName__c}" id="acc_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒浜�" for="acc_DealerSelectOwner1"/>
+                    <apex:inputField value="{!acc.DealerSelectOwner__c}" id="acc_DealerSelectOwner1" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鏄惁涓篛EM瀹㈡埛" for="compo_acc2"/>
+                    <apex:inputField value="{!acc.Whether_OEM__c}" id="compo_acc2"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="瀹㈡埛鍦板潃淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐪�" for="acc_accName"/>
+                    <apex:inputField value="{!acc.Province__c}" id="acc_accName" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閭紪." for="acc_Account"/>
+                    <apex:inputField value="{!acc.PostCodeD__c}" id="acc_Account"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍩庡競." for="acc_CurrencyIsoCode"/>
+                    <apex:inputField value="{!acc.CityD__c}" id="acc_CurrencyIsoCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢佃瘽." for="acc_Type"/>
+                    <apex:inputField value="{!acc.PhoneD__c}" id="acc_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃1." for="acc_BudgetAmount"/>
+                    <apex:inputField value="{!acc.Address1D__c}" id="acc_BudgetAmount" required="true"/>
+                </apex:pageBlockSectionItem>
+				<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浼犵湡." for="acc_Amount1"/>
+                    <apex:inputField value="{!acc.FaxD__c}" id="acc_Amount1"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="缃戝潃." for="acc_Amount"/>
+                    <apex:inputField value="{!acc.WebsiteD__c}" id="acc_Amount"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="瀹㈡埛闄勫姞淇℃伅" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢ㄦ埛灞炴��" for="acc_accName"/>
+                    <apex:inputField value="{!acc.UserType__c}" id="acc_accName" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏抽敭瀹㈡埛" for="acc_Account"/>
+                    <apex:inputField value="{!acc.KeyAccount__c}" id="acc_Account"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浜у搧鍒嗙被" for="acc_CurrencyIsoCode"/>
+                    <apex:inputField value="{!acc.ProductSegment__c}" id="acc_CurrencyIsoCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍑哄彛闄愬埗鐢ㄦ埛" for="acc_Type"/>
+                    <apex:inputField value="{!acc.ExportRegulatedCustomer__c}" id="acc_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="甯傚満鍒嗙被." for="acc_BudgetAmount"/>
+                    <apex:inputField value="{!acc.MarketVerticalsD__c}" id="acc_BudgetAmount" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                &nbsp;
+                </apex:pageBlockSectionItem>
+				<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢ㄩ��." for="acc_Amount1"/>
+                    <apex:inputField value="{!acc.UseD__c}" id="acc_Amount1" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="琛屼笟1." for="acc_Amount"/>
+                    <apex:inputField value="{!acc.IndustryBD__c}" id="acc_Amount" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                &nbsp;
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="Sub Use." for="acc_Amount"/>
+                    <apex:outputField value="{!acc.Sub_UseD__c}" id="acc_Amount"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="瀹㈡埛淇濇湁BS浜у搧" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="Leica." for="acc_accName"/>
+                    <apex:inputField value="{!acc.AssetBS3D__c}" id="acc_accName"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="Nikon." for="acc_Account"/>
+                    <apex:inputField value="{!acc.AssetBS2D__c}" id="acc_Account"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="OLYMPUS." for="acc_CurrencyIsoCode"/>
+                    <apex:inputField value="{!acc.AssetBS1D__c}" id="acc_CurrencyIsoCode"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="Others." for="acc_Type"/>
+                    <apex:inputField value="{!acc.AssetBS5D__c}" id="acc_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="Zeiss." for="acc_BudgetAmount"/>
+                    <apex:inputField value="{!acc.AssetBS4D__c}" id="acc_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="瀹㈡埛绯荤粺淇℃伅" columns="2">
+            	<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�"/>
+                    <apex:inputField value="{!acc.Name}" id="acc_CompetitorProduct3"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒鐘舵��."/>
+                    <apex:outputField value="{!acc.stautesD__c}" id="acc_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="璐︽埛鐘舵��." for="acc_CompetitorProductCode"/>
+                    <apex:inputField value="{!acc.AccountStatusD__c}" id="acc_CompetitorProductCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍙栨秷鍘熷洜." for="acc_CompetitorProduct2"/>
+                    <apex:inputField value="{!acc.CancelReasonD__c}" id="acc_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏ㄥ浗浼佷笟鐢ㄦ埛." for="acc_CompetitorProduct2"/>
+                    <apex:outputField value="{!acc.NationalEnterpriseUser__c}" id="acc_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="瀹㈡埛澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="acc_Remark"/>
+                    <apex:inputField value="{!acc.Remark__c}" id="acc_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+             <apex:outputPanel layout="none" rendered="{!if(tycoId == null || tycoId == '', false,true)}">
+            <apex:pageBlockSection title="鑱旂郴浜轰俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绉戝" for="con_Account"/>
+                    <apex:inputField value="{!con.Department}" id="con_Account"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鎵嬫満." for="con_CurrencyIsoCode"/>
+                    <apex:inputField value="{!con.MobilePhoneD__c}" id="con_CurrencyIsoCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑱屽姟." for="con_Type"/>
+                    <apex:inputField value="{!con.TitleD__c}" id="con_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢佃瘽." for="con_BudgetAmount"/>
+                    <apex:inputField value="{!con.PhoneD__c}" id="con_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+				<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绉拌皳" for="con_Amount1"/>
+                    <apex:inputField value="{!con.Salutation}" id="con_Amount1"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浼犵湡." for="con_Amount"/>
+                    <apex:inputField value="{!con.FaxD__c}" id="con_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="濮撴皬" for="con_DealerSelectOwner1"/>
+                    <apex:inputField value="{!con.lastname}" id="con_DealerSelectOwner1" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏朵粬鐢佃瘽." for="compo_con2"/>
+                    <apex:inputField value="{!con.OtherPhoneD__c}" id="compo_con2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍚嶅瓧" for="con_DealerSelectOwner"/>
+                    <apex:inputField value="{!con.firstname}" id="con_DealerSelectOwner"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢靛瓙閭欢." for="compo_con1"/>
+                    <apex:inputField value="{!con.EmailD__c}" id="compo_con1"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑻辨枃鍚�" for="co123o_con1"/>
+                    <apex:inputField value="{!con.ContactEnglishName__c}" id="yingwen_con1"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="鑱旂郴浜哄湴鍧�淇℃伅" columns="1">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閭斂缂栫爜." for="con_ExpctedOrdrDate"/>
+                    <apex:inputField value="{!con.PostcodeD__c}" id="con_ExpectdOrdeDate" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃1." for="con_ExpctedDeliveryDte"/>
+                    <apex:inputField value="{!con.Address1D__c}" id="on_ExpctedDeliveyDate" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃2(鍏朵粬鍦板潃)." for="con_EpectedDeliveryDate"/>
+                    <apex:inputField value="{!con.Address2D__c}" id="con_ExpectedDeleryDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃3(鍏朵粬鍦板潃)." for="con_ExpecteDelivryDate"/>
+                    <apex:inputField value="{!con.Address3D__c}" id="con_ExpeedDeliveryDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑻辨枃鍦板潃" for="con_yingeliveryDate"/>
+                    <apex:inputField value="{!con.EnglishAddress__c}" id="con_eliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="鑱旂郴浜轰骇鍝侀儴鍒�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="BS" for="con_LeadSource"/>
+                    <apex:inputField value="{!con.ProductSegmentBS__c}" id="con_LeadSource" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="RVI" for="con_TradeType"/>
+                    <apex:inputField value="{!con.ProductSegmentRVI__c}" id="con_TradeType" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="IE" for="con_SalesChannel"/>
+                    <apex:inputField value="{!con.ProductSegmentIE__c}" id="con_SalesChannel" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="NDT" for="con_SalesChannel"/>
+                    <apex:inputField value="{!con.ProductSegmentNDT__c}" id="con_SalesChannel" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="ANI" for="con_SalesChannel"/>
+                    <apex:inputField value="{!con.ProductSegmentANI__c}" id="con_SalesChannel" />
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="鑱旂郴浜虹郴缁熶俊鎭�" columns="1">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒鐘舵��."/>
+                    <apex:outputField value="{!con.StatusD__c}" id="con_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐘舵��" for="con_CompetitorProductCode"/>
+                    <apex:inputField value="{!con.ContactStatus__c}" id="con_CompetitorProductCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍙栨秷鍘熷洜." for="con_CompetitorProduct2"/>
+                    <apex:inputField value="{!con.CancelReasonD__c}" id="con_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="鑱旂郴浜哄娉�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="con_Remark"/>
+                    <apex:inputField value="{!con.Remark__c}" id="con_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+        </apex:outputPanel>
+
+            <apex:pageBlockButtons location="bottom">
+                <apex:commandButton style="width:50px"  value="淇濆瓨" onclick="saveJs(); return false;"/>
+                <apex:commandButton style="width:50px"  value="鍙栨秷" onclick="cancelJs(); return false;"/>
+            </apex:pageBlockButtons>
+        </apex:pageBlock>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TydelikeAcc.page-meta.xml b/scr/pages/TydelikeAcc.page-meta.xml
new file mode 100644
index 0000000..017584f
--- /dev/null
+++ b/scr/pages/TydelikeAcc.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TydelikeAcc</label>
+</ApexPage>
diff --git a/scr/pages/TydelikeCon.page b/scr/pages/TydelikeCon.page
new file mode 100644
index 0000000..e6da563
--- /dev/null
+++ b/scr/pages/TydelikeCon.page
@@ -0,0 +1,158 @@
+<apex:page Controller="TydelikeConController" sidebar="false" action="{!init}" id="Page">
+	<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
+    <script>
+    function saveJs() {
+        /*var MobilePhoneD = j$(escapeVfId('Page:mainForm:saamvoegCon:' + ':con_CursoCode')).value();
+        if (MobilePhoneD == '') {
+            alert('鎵嬫満鍙风爜涓嶈兘涓虹┖');
+        }else{*/
+            blockme();
+            save();  
+        /*}*/
+        
+    }
+    function cancelJs() {
+        var baseUrl = '{!baseUrl}';
+    	url =baseUrl + '/apex/TydelikeAC';
+        window.top.location.href = url;
+    }
+    </script>
+
+    <apex:form id="mainForm">
+        <apex:actionFunction action="{!save}" name="save" reRender="mainForm,message" oncomplete="unblockUI();"/>
+
+        <apex:outputPanel id="message">
+            <apex:messages styleClass="editListError"/>
+        </apex:outputPanel>
+        <apex:inputHidden id="baseUrl" value="{!baseUrl}"/>
+
+        <apex:pageBlock id="saamvoegCon" title="鍚堝苟鑱旂郴浜�" tabStyle="Contact">
+            <apex:pageBlockButtons location="top">
+                <apex:commandButton style="width:50px"  value="淇濆瓨" onclick="saveJs(); return false;"/>
+                <apex:commandButton style="width:50px"  value="鍙栨秷" onclick="cancelJs(); return false;"/>
+            </apex:pageBlockButtons>
+
+            <apex:pageBlockSection title="鑱旂郴浜轰俊鎭�" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹㈡埛鍚�" for="con_accName"/>
+                    <apex:inputField value="{!con.AccountId}" id="con_accName" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绉戝" for="con_Account"/>
+                    <apex:inputField value="{!con.Department}" id="con_Account"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鎵嬫満." for="con_CurrencyIsoCode"/>
+                    <apex:inputField value="{!con.MobilePhoneD__c}" id="con_CursoCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑱屽姟." for="con_Type"/>
+                    <apex:inputField value="{!con.TitleD__c}" id="con_Type"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢佃瘽." for="con_BudgetAmount"/>
+                    <apex:inputField value="{!con.PhoneD__c}" id="con_BudgetAmount"/>
+                </apex:pageBlockSectionItem>
+				<apex:pageBlockSectionItem >
+                    <apex:outputLabel value="绉拌皳" for="con_Amount1"/>
+                    <apex:inputField value="{!con.Salutation}" id="con_Amount1"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="浼犵湡." for="con_Amount"/>
+                    <apex:inputField value="{!con.FaxD__c}" id="con_Amount"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="濮撴皬" for="con_DealerSelectOwner1"/>
+                    <apex:inputField value="{!con.lastname}" id="con_DealerSelectOwner1" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍏朵粬鐢佃瘽." for="compo_con2"/>
+                    <apex:inputField value="{!con.OtherPhoneD__c}" id="compo_con2"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍚嶅瓧" for="con_DealerSelectOwner"/>
+                    <apex:inputField value="{!con.firstname}" id="con_DealerSelectOwner"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐢靛瓙閭欢." for="compo_con1"/>
+                    <apex:inputField value="{!con.EmailD__c}" id="compo_con1"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑻辨枃鍚�" for="co123o_con1"/>
+                    <apex:inputField value="{!con.ContactEnglishName__c}" id="yingwen_con1"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="鍦板潃淇℃伅" columns="1">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="閭斂缂栫爜." for="con_ExpectedOrderDate"/>
+                    <apex:inputField value="{!con.PostcodeD__c}" id="con_ExpectedOrderDate" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃1." for="con_ExpectedDeiveryDae"/>
+                    <apex:inputField value="{!con.Address1D__c}" id="cn_xpectedeliveryDate" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃2(鍏朵粬鍦板潃)." for="con_ExpectedDeliverate"/>
+                    <apex:inputField value="{!con.Address2D__c}" id="con_ExpectedliveryDate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍦板潃3(鍏朵粬鍦板潃)." for="con_ExpecteDeliveryDate"/>
+                    <apex:inputField value="{!con.Address3D__c}" id="con_ExpectedDeliveryate"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鑻辨枃鍦板潃" for="con_yingeliveryDate"/>
+                    <apex:inputField value="{!con.EnglishAddress__c}" id="con_eliveryDate"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="浜у搧閮ㄥ垎" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="BS" for="con_LeadSource"/>
+                    <apex:inputField value="{!con.ProductSegmentBS__c}" id="con_LeadSource" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="RVI" for="con_TradeType"/>
+                    <apex:inputField value="{!con.ProductSegmentRVI__c}" id="con_TradeType" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="IE" for="con_SalesChannel"/>
+                    <apex:inputField value="{!con.ProductSegmentIE__c}" id="con_SalesChannel" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="NDT" for="con_SalesChannel"/>
+                    <apex:inputField value="{!con.ProductSegmentNDT__c}" id="con_SalesChannel" />
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="ANI" for="con_SalesChannel"/>
+                    <apex:inputField value="{!con.ProductSegmentANI__c}" id="con_SalesChannel" />
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="绯荤粺淇℃伅" columns="1">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="瀹℃壒鐘舵��."/>
+                    <apex:outputField value="{!con.StatusD__c}" id="con_CompetitorProduct"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鐘舵��" for="con_CompetitorProductCode"/>
+                    <apex:inputField value="{!con.ContactStatus__c}" id="con_CompetitorProductCode" required="true"/>
+                </apex:pageBlockSectionItem>
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="鍙栨秷鍘熷洜." for="con_CompetitorProduct2"/>
+                    <apex:inputField value="{!con.CancelReasonD__c}" id="con_CompetitorProduct2"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+            <apex:pageBlockSection title="澶囨敞" columns="2">
+                <apex:pageBlockSectionItem >
+                    <apex:outputLabel value="澶囨敞" for="con_Remark"/>
+                    <apex:inputField value="{!con.Remark__c}" id="con_Remark" style="width: 75%;"/>
+                </apex:pageBlockSectionItem>
+            </apex:pageBlockSection>
+
+        </apex:pageBlock>
+    </apex:form>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/TydelikeCon.page-meta.xml b/scr/pages/TydelikeCon.page-meta.xml
new file mode 100644
index 0000000..3d6dab3
--- /dev/null
+++ b/scr/pages/TydelikeCon.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>TydelikeCon</label>
+</ApexPage>
diff --git a/scr/pages/Unauthorized.page b/scr/pages/Unauthorized.page
new file mode 100644
index 0000000..b0e4ff2
--- /dev/null
+++ b/scr/pages/Unauthorized.page
@@ -0,0 +1,38 @@
+<apex:page showHeader="false" title="{!$Label.site.authorization_required}" id="Unauthorized" cache="false">
+  <apex:composition template="{!$Site.Template}">
+    <apex:define name="body">
+      <center>
+        <apex:panelGrid bgcolor="white" columns="1">
+          <br/>
+          <br/>
+          <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="1" styleClass="topPanelContainer">
+            <br/>
+            <apex:outputPanel layout="block" styleClass="topPanel">
+              <apex:panelGrid width="758" cellpadding="0" cellspacing="0" bgcolor="white" columns="3">
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/clock.png')}"/>
+                <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/unauthorized.png')}"/>
+                <apex:panelGroup >
+                  <apex:outputText styleClass="title" value="{!$Label.site.authorization_required}"/>
+                  <br/>
+                  <br/>
+                  <apex:outputText value="{!$Label.site.login_or_register_first}"/>
+                  <br/>
+                  <apex:outputText value="{!$Label.site.click_forget_password}"/>
+                  <br/>
+                  <br/>
+                </apex:panelGroup>
+                <apex:outputText value=""/>
+                <apex:outputText value=""/>
+                <c:SiteLogin rendered="{!$Site.LoginEnabled && ISPICKVAL($User.UserType,'Guest')}" id="siteLogin"/>
+                <br/>
+              </apex:panelGrid>
+            </apex:outputPanel>
+            <c:SitePoweredBy />
+          </apex:panelGrid>
+        </apex:panelGrid>
+      </center>
+      <br/>
+    </apex:define>
+  </apex:composition>
+  <site:previewAsAdmin />
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/Unauthorized.page-meta.xml b/scr/pages/Unauthorized.page-meta.xml
new file mode 100644
index 0000000..c46f60f
--- /dev/null
+++ b/scr/pages/Unauthorized.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 闇�瑕佹巿鏉冮〉闈�</description>
+    <label>Unauthorized</label>
+</ApexPage>
diff --git a/scr/pages/UnderConstruction.page b/scr/pages/UnderConstruction.page
new file mode 100644
index 0000000..357aa2d
--- /dev/null
+++ b/scr/pages/UnderConstruction.page
@@ -0,0 +1,19 @@
+<apex:page showHeader="false" title="{!$Label.site.site_under_construction}">
+  <apex:composition template="StdExceptionTemplate">
+    <apex:define name="icon">
+      <apex:image url="{!URLFOR($Resource.SiteSamples, 'img/tools.png')}"/>
+    </apex:define>
+    <apex:define name="error">
+      <apex:outputText escape="false" styleClass="title" value="{!$Label.site.under_construction}">
+        <apex:param value="{!$Site.BaseUrl}"/>
+      </apex:outputText>
+      <br/>
+      <br/>
+      <apex:outputText value="{!$Label.site.stay_tuned}"/>
+      <apex:outputText escape="false" value=" {!$Label.site.get_in_touch}">
+      <apex:param value="mailto:{!$Site.AdminEmailAddress}"/>
+      <apex:param value="{!$Label.site.email_us}"/>
+    </apex:outputText>
+   </apex:define>
+  </apex:composition>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/UnderConstruction.page-meta.xml b/scr/pages/UnderConstruction.page-meta.xml
new file mode 100644
index 0000000..d20e226
--- /dev/null
+++ b/scr/pages/UnderConstruction.page-meta.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <description>榛樿 Force.com 姝e湪寤鸿涓〉闈�</description>
+    <label>UnderConstruction</label>
+</ApexPage>
diff --git a/scr/pages/ca_tour_main.page b/scr/pages/ca_tour_main.page
new file mode 100644
index 0000000..5ae44c6
--- /dev/null
+++ b/scr/pages/ca_tour_main.page
@@ -0,0 +1,162 @@
+<apex:page >
+    <apex:stylesheet value="/apex/ca_tour_style"/>
+    <apex:includeScript value="/support/console/25.0/integration.js"/>
+    <script type="text/javascript">   
+        /***** Box Currently Showing Variable Controller *****/
+        var boxIsShowing = 0;
+        
+        /***** Set Tab Title Below In Single Quotes *****/
+        //sforce.console.getFocusedPrimaryTabId(function(result){
+        //  sforce.console.setTabTitle('Tour Agent Console', result.id);
+        //});
+        
+        /***** Function to Move Forward in Tour *****/
+        function tourNext(num){
+            var nextNum = num + 1;
+            document.getElementById('pop' + num).style.display="none";
+            document.getElementById('pop' + nextNum).style.display="block";
+        }
+        
+        /***** Function to Move Back in Tour *****/
+        function tourBack(num){
+            var backNum = num - 1;
+            document.getElementById('pop' + num).style.display="none";
+            document.getElementById('pop' + backNum).style.display="block";
+        }
+        
+        /***** Box Show Functionality *****/       
+        function showTour(num){
+            hideTour();
+            document.getElementById('pop' + num).style.display="block";
+            hoverIsOn = 0;
+        }
+        
+        /***** Hides All Boxes *****/
+        function hideTour(){
+            for(i = 1 ; i < 11 ; i++){
+                document.getElementById('pop' + i).style.display="none";
+            }
+        }
+    </script>
+    <body>
+        <div id="container">
+            <div id="content">
+                <!-- All Popup Information Boxes -->
+                
+                <!-- Welcome Box -->
+                <div id="pop1" class="popUps" style="">
+                    <h3>Welcome&#33;</h3>
+                    <p>Welcome to Service Communities, a complete self-service community portal that lets you  deliver better web-based service to your customers.</p>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup_about.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(1)">Next&nbsp;&#62;&#62;</a>
+                    <span class="" title=""></span>
+                </div>
+                <!-- My Profile Box -->
+                <div id="pop2" class="popUps" style="">
+                    <h3>My Profile</h3>
+                    <p>Your customer鈥檚 profile page allows them to view all their open questions in one place, personalize their profile with a picture, and edit their privacy and security settings.</p>
+                    <a href="" class="" onclick="tourBack(2)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_about_users.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(2)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">1/9</div>
+                    <span class="pointLeft" title=""></span>
+                </div>
+                <!-- Search Bar Box -->
+                <div id="pop3" class="popUps" style="">
+                    <h3>Search Bar</h3>
+                    <p>Customers use the search bar to ask questions in their own words and receive answers from your knowledge base as well as the community.</p>
+                    <a href="" class="" onclick="tourBack(3)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(3)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">2/9</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+                <!-- Suggested Results Box -->
+                <div id="pop4" class="popUps" style="">
+                    <h3>Suggested Results</h3>
+                    <p>Before your customer posts a question, we suggest possible solutions to take advantage of the knowledge base and eliminate duplicate questions in the community.</p>
+                    <a href="" class="" onclick="tourBack(4)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(4)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">3/9</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+                <!-- Customer Posts Box -->
+                <div id="pop5" class="popUps" style="">
+                    <h3>Customer Posts</h3>
+                    <p>When a customer posts a question, other customers can respond with helpful suggestions or information.</p>
+                    <a href="" class="" onclick="tourBack(5)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(5)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">4/9</div>
+                    <span class="pointRight" title=""></span>
+                </div>
+                <!-- Agent Posts Box -->
+                <div id="pop6" class="popUps" style="">
+                    <h3>Agent Posts</h3>
+                    <p>With tight integration into the Service Cloud console, agents can search through unanswered questions and jump in with solutions so no question goes unanswered.</p>
+                    <a href="" class="" onclick="tourBack(6)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(6)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">5/9</div>
+                    <span class="pointRight" title=""></span>
+                </div>
+                <!-- Best Answers Box -->
+                <div id="pop7" class="popUps" style="">
+                    <h3>Best Answers</h3>
+                    <p>Customers can mark posts as a 'Best Answer' to indicate their issue was resolved.</p>
+                    <a href="" class="" onclick="tourBack(7)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(7)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">6/9</div>
+                    <span class="pointRight" title=""></span>
+                </div>
+                <!-- Categories Box -->
+                <div id="pop8" class="popUps" style="">
+                    <h3>Categories</h3>
+                    <p>The community can be categorized into topics so customers can quickly navigate to relevant information.</p>
+                    <a href="" class="" onclick="tourBack(8)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=questions_portal_setup.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(8)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">7/9</div>
+                    <span class="pointLeftBottom" title=""></span>
+                </div>
+                <!-- Portal Tabs Box -->
+                <div id="pop9" class="popUps" style="">
+                    <h3>Portal Tabs</h3>
+                    <p>You can also use the Customer Portal if you need to securely share information with your customers, including accounts, cases, orders, opportunities, and ideas.</p>
+                    <a href="" class="" onclick="tourBack(9)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=customer_portal_setting_up.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(9)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">8/9</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+            </div>
+        </div>
+        <!-- Close tab Box -->
+        <div id="pop10" class="popUps" style="">
+            <h3>That's It!</h3>
+            <p>You鈥檙e done exploring the self-service community. Close this tab to return to the Getting Started tab and learn more about the Service Cloud.</p>
+            <a href="" class="" onclick="tourBack(10)">&#60;&#60;&nbsp;Back</a>
+            <div class="tourNum">9/9</div>
+            <span class="pointTop" title=""></span>
+        </div>
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ca_tour_main.page-meta.xml b/scr/pages/ca_tour_main.page-meta.xml
new file mode 100644
index 0000000..dc3ae25
--- /dev/null
+++ b/scr/pages/ca_tour_main.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>ca_tour_main</label>
+</ApexPage>
diff --git a/scr/pages/ca_tour_style.page b/scr/pages/ca_tour_style.page
new file mode 100644
index 0000000..c3ede27
--- /dev/null
+++ b/scr/pages/ca_tour_style.page
@@ -0,0 +1,224 @@
+<apex:page cache="false" showHeader="false" contentType="text/css">
+     #container{
+        width:960px;       
+        padding:25px;
+        margin:0px auto;
+    }
+    #content{
+        position:relative;
+        border:3px solid white;
+        -moz-border-radius: 5px;
+        -webkit-border-radius: 5px;
+        border-radius: 5px;
+        -moz-box-shadow:0px 0px 5px 1px #333;
+        -webkit-box-shadow:0px 0px 5px 1px #333;
+        box-shadow:0px 0px 5px 1px #333;
+        width: 950px;
+        height: 690px;
+        background-image:url(/resource/scc_tour_images/Tour_Images/chatter-answers-950.png);
+        background-repeat: no-repeat;
+        background-attachment:scroll;
+    }
+    
+    #pop1{
+        width: 214px;
+        position: absolute;
+        top: 200px;
+        left: 358px;
+        margin: 0;
+    }
+    
+    #pop2{
+        width: 275px;
+        position: absolute;
+        top: 103px;
+        left: 330px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop3{
+        width: 275px;
+        position: absolute;
+        top: 146px;
+        left: 335px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop4{
+        width: 207px;
+        position: absolute;
+        top: 273px;
+        left: 413px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop5{
+        width: 238px;
+        position: absolute;
+        top: 377px;
+        left: 118px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop6{
+        width: 238px;
+        position: absolute;
+        top: 495px;
+        left: 118px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop7{
+        width: 238px;
+        position: absolute;
+        top: 503px;
+        left: 65px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop8{
+        width: 238px;
+        position: absolute;
+        top: 205px;
+        left: 283px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop9{
+        width: 275px;
+        position: absolute;
+        top: 90px;
+        left: 120px;
+        margin: 0;
+        display:none;
+    }   
+    
+    #pop10{
+        width: 275px;
+        position: absolute;
+        top: 22px;
+        left: 290px;
+        margin: 0;
+        display:none;
+    }   
+    
+    .pointTop{
+        display: block;
+        width: 36px;
+        height: 29px;
+        position: absolute;
+        top: -29px;
+        left: 11px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -3px -236px no-repeat;
+    }
+    
+    .pointTopRight{
+        display: block;
+        width: 36px;
+        height: 29px;
+        position: absolute;
+        top: -29px;
+        left: 151px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -3px -236px no-repeat;
+    }
+    
+    .pointLeft{
+        display: block;
+        width: 29px;
+        height: 29px;
+        position: absolute;
+        top: 15px;
+        left: -30px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -11px -88px no-repeat;
+    }
+    
+    .pointLeftBottom{
+        display: block;
+        width: 29px;
+        height: 29px;
+        position: absolute;
+        top: 55px;
+        left: -30px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -11px -88px no-repeat;
+    }
+    
+    .pointRight{
+        display: block;
+        width: 28px;
+        height: 29px;
+        position: absolute;
+        top: 15px;
+        left: 263px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -3px -5px no-repeat;
+    }
+    
+    .popUps{
+        display: block;
+        position: absolute;
+        max-width: none;
+        margin: 0;
+        border: 2px solid white;
+        padding: 12px;
+        z-index: 1000;
+        background: #FFE5A7 url(/resource/scc_tour_images/Tour_Images/bg_tour.png) repeat-x;
+        font-weight: normal;
+        -webkit-box-shadow: 0 2px 5px #ACACAC;
+        -moz-box-shadow: 0 0 5px #acacac;
+        box-shadow: 0 0 5px #ACACAC;
+        -moz-border-radius: 5px;
+        -webkit-border-radius: 5px;
+        border-radius: 5px;
+    }
+    
+    .popUps h3{
+        padding: 0;
+        border-bottom: none;
+        margin: 0 0 8px;
+        font-size: 1.1em;
+        font-weight: 700;
+        display: block;
+        line-height: 1em;
+        font-family: Arial,Helvetica,sans-serif;
+        color: #333;
+    }
+    
+    .popUps p {
+        margin: 0 0 8px;
+        line-height: 16px;    
+        color:#333;
+        font-family: arial;
+    }
+    
+    .midLinks{
+        text-decoration:none;
+    }
+    
+    .popUps span{
+        padding:0px 3px;
+    }
+    
+    .popUps a, .popUps a:hover{
+        color: #015BA7;
+        cursor: default;
+    }
+    
+    .popUps .tourNum{
+        display: block;
+        width: 23px;
+        position: absolute;
+        outline: none;
+        font-size: 10px;
+        bottom: 5px;
+        right: 3px;
+        height: 20px;
+        color: #666;
+        font-weight: bold;
+    }
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/ca_tour_style.page-meta.xml b/scr/pages/ca_tour_style.page-meta.xml
new file mode 100644
index 0000000..1c64a74
--- /dev/null
+++ b/scr/pages/ca_tour_style.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>ca_tour_style</label>
+</ApexPage>
diff --git a/scr/pages/orderPage.page b/scr/pages/orderPage.page
new file mode 100644
index 0000000..9eb00b7
--- /dev/null
+++ b/scr/pages/orderPage.page
@@ -0,0 +1,58 @@
+<apex:page standardController="Order" showHeader="false" sidebar="false">
+    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
+    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
+    <script type="text/javascript">
+        var check = '{!Order.check__c}';
+        var checknum = '{!Order.checkNumber__c}'
+        if(checknum != '1' && check != '1' && check != null && check != ''){
+            alert(check);
+            var rac = new sforce.SObject("Order"); 
+            rac.Id = "{!Order.Id}"; 
+            rac.checkNumber__c = '1';
+            //rac.OwnerId = '{!Order.OpportunityOwnerId__c}';
+            var result = sforce.connection.update([rac]);
+            var messages = getConnectDMLErrorMessages(result);
+            if (messages.length > 0) { 
+                alert(messages.join("\n")); 
+            } else {
+                window.top.location.reload();
+            }
+        }
+
+
+        function getConnectDMLErrorMessages(results) { 
+var messages = [], 
+i = 0, 
+len = results.length, 
+r; 
+for (; i < len; i++) { 
+r = results[i]; 
+if (! r.getBoolean("success")) { 
+messages = messages.concat(getConnectDMLMessagesOfAResult(r)); 
+} 
+} 
+return messages; 
+}; 
+function getConnectDMLMessagesOfAResult(res) { 
+var messages = [], 
+errors = res.getArray("errors"), 
+i = 0, 
+len = errors.length, 
+e; 
+for (; i < len; i++) { 
+e = errors[i]; 
+messages.push(e.message + " " + getConnectDMLErrorFields(e)); 
+} 
+return messages; 
+}; 
+function getConnectDMLErrorFields(error) { 
+var fields = error.getArray('fields'); 
+if (fields.length > 0) { 
+return "[" + fields.join(",") + "]" 
+} else { 
+return ""; 
+} 
+}; 
+
+    </script>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/orderPage.page-meta.xml b/scr/pages/orderPage.page-meta.xml
new file mode 100644
index 0000000..b2b7302
--- /dev/null
+++ b/scr/pages/orderPage.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>orderPage</label>
+</ApexPage>
diff --git a/scr/pages/scc_tour_main.page b/scr/pages/scc_tour_main.page
new file mode 100644
index 0000000..0fa834b
--- /dev/null
+++ b/scr/pages/scc_tour_main.page
@@ -0,0 +1,174 @@
+<apex:page >
+    <apex:stylesheet value="/apex/scc_tour_style"/>
+    <apex:includeScript value="/support/console/25.0/integration.js"/>
+    <script type="text/javascript">   
+        /***** Box Currently Showing Variable Controller *****/
+        var boxIsShowing = 0;
+        
+        /***** Set Tab Title Below In Single Quotes *****/
+        //sforce.console.getFocusedPrimaryTabId(function(result){
+        //  sforce.console.setTabTitle('Tour Agent Console', result.id);
+        //});
+        
+        /***** Function to Move Forward in Tour *****/
+        function tourNext(num){
+            var nextNum = num + 1;
+            document.getElementById('pop' + num).style.display="none";
+            document.getElementById('pop' + nextNum).style.display="block";
+        }
+        
+        /***** Function to Move Back in Tour *****/
+        function tourBack(num){
+            var backNum = num - 1;
+            document.getElementById('pop' + num).style.display="none";
+            document.getElementById('pop' + backNum).style.display="block";
+        }
+        
+        /***** Box Show Functionality *****/       
+        function showTour(num){
+            hideTour();
+            document.getElementById('pop' + num).style.display="block";
+            hoverIsOn = 0;
+        }
+        
+        /***** Hides All Boxes *****/
+        function hideTour(){
+            for(i = 1 ; i < 11 ; i++){
+                document.getElementById('pop' + i).style.display="none";
+            }
+        }
+    </script>
+    <body>
+        <div id="container">
+            <div id="content">
+                <!-- All Popup Information Boxes -->
+                
+                <!-- Welcome Box -->
+                <div id="pop1" class="popUps" style="">
+                    <h3>Welcome&#33;</h3>
+                    <p>Welcome to the Service Cloud console tour. The console is the agent&#39;s primary case management interface.</p>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=console2_about.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(1)">Next&nbsp;&#62;&#62;</a>
+                    <span class="" title=""></span>
+                </div>
+                <!-- Customer Information Box -->
+                <div id="pop2" class="popUps" style="">
+                    <h3>Highlight Panel: Customer Information</h3>
+                    <p>This is where agents see important customer information. You can customize all the sections in the highlight panel for your business.</p>
+                    <a href="" class="" onclick="tourBack(2)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_layoutcustomize_highlights_panel_config.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(2)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">1/10</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+                <!-- Case Summary Box -->
+                <div id="pop3" class="popUps" style="">
+                    <h3>Highlight Panel: Case Summary</h3>
+                    <p>The case summary gives your agents a quick snapshot of what this case is about.</p>
+                    <a href="" class="" onclick="tourBack(3)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_layoutcustomize_highlights_panel_config.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(3)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">2/10</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+                <!-- Case Status Box -->
+                <div id="pop4" class="popUps" style="">
+                    <h3>Highlight Panel: Case Status</h3>
+                    <p>The case status lets agents see the case priority and where this case is in the resolution process.</p>
+                    <a href="" class="" onclick="tourBack(4)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_layoutcustomize_highlights_panel_config.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(4)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">3/10</div>
+                    <span class="pointTopRight" title=""></span>
+                </div>
+                <!-- Knowledge Box -->
+                <div id="pop5" class="popUps" style="">
+                    <h3>Knowledge</h3>
+                    <p>Knowledge automatically searches for answers to agents鈥� questions so they can close cases quickly -- no more time wasted looking for answers.</p>
+                    <a href="" class="" onclick="tourBack(5)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=knowledge_whatis.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(5)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">4/10</div>
+                    <span class="pointRight" title=""></span>
+                </div>
+                <!-- Case Feed Box -->
+                <div id="pop6" class="popUps" style="">
+                    <h3>Case Feed</h3>
+                    <p>The feed shows the history of this case across channels in an easy-to-view format.</p>
+                    <a href="" class="" onclick="tourBack(6)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=case_interaction_overview.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(6)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">5/10</div>
+                    <span class="pointLeft" title=""></span>
+                </div>
+                <!-- Case Publisher Box -->
+                <div id="pop7" class="popUps" style="">
+                    <h3>Case Publisher</h3>
+                    <p>The case publisher gives agents a single place to respond to all cases, whether they were logged through email, by phone, or on the web.</p>
+                    <a href="" class="" onclick="tourBack(7)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=case_interaction_overview.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(7)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">6/10</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+                <!-- Feed Filters Box -->
+                <div id="pop8" class="popUps" style="">
+                    <h3>Feed Filters</h3>
+                    <p>The feed filters let agents view specific activities on a case, such as email, call logs, or case notes.</p>
+                    <a href="" class="" onclick="tourBack(8)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=case_interaction_overview.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(8)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">7/10</div>
+                    <span class="pointLeftBottom" title=""></span>
+                </div>
+                <!-- Publisher Actions Box -->
+                <div id="pop9" class="popUps" style="">
+                    <h3>Case Actions</h3>
+                    <p>The case action lets agents perform different actions on a case, such as writing an internal note or changing the status.</p>
+                    <a href="" class="" onclick="tourBack(9)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=case_interaction_overview.htm&language=en_US" class="midLinks" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(9)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">8/10</div>
+                    <span class="pointTop" title=""></span>
+                </div>              
+                <!-- Primary Tabs Box -->                                               
+                <div id="pop10" class="popUps" style="">
+                    <h3>Primary Tabs</h3>
+                    <p>Primary tabs help agents work on multiple cases at the same time. They also supply other important information, such as relevant account and contact details.</p>
+                    <a href="" class="" onclick="tourBack(10)">&#60;&#60;&nbsp;Back</a>
+                    <span>|</span>
+                    <a href="https://help.salesforce.com/apex/HTViewHelpDoc?id=console2_tabs.htm&language=en_US" target="_blank">Learn More</a>
+                    <span>|</span>
+                    <a href="" class="" onclick="tourNext(10)">Next&nbsp;&#62;&#62;</a>
+                    <div class="tourNum">9/10</div>
+                    <span class="pointTop" title=""></span>
+                </div>
+            </div>
+        </div>
+        <!-- Close tab Box -->
+        <div id="pop11" class="popUps" style="">
+            <h3>That's It!</h3>
+            <p>You鈥檙e done exploring the agent console. Close this tab to return to the Getting Started tab and learn more about the Service Cloud.</p>
+            <a href="" class="" onclick="tourBack(11)">&#60;&#60;&nbsp;Back</a>
+            <div class="tourNum">10/10</div>
+            <span class="pointTop" title=""></span>
+        </div>
+    </body>
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/scc_tour_main.page-meta.xml b/scr/pages/scc_tour_main.page-meta.xml
new file mode 100644
index 0000000..9aded08
--- /dev/null
+++ b/scr/pages/scc_tour_main.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>scc_tour_main</label>
+</ApexPage>
diff --git a/scr/pages/scc_tour_style.page b/scr/pages/scc_tour_style.page
new file mode 100644
index 0000000..3ff554d
--- /dev/null
+++ b/scr/pages/scc_tour_style.page
@@ -0,0 +1,234 @@
+<apex:page cache="false" showHeader="false" contentType="text/css">
+     #container{
+        width:960px;       
+        padding:25px;
+        margin:0px auto;
+    }
+    #content{
+        position:relative;
+        border:3px solid white;
+        -moz-border-radius: 5px;
+        -webkit-border-radius: 5px;
+        border-radius: 5px;
+        -moz-box-shadow:0px 0px 5px 1px #333;
+        -webkit-box-shadow:0px 0px 5px 1px #333;
+        box-shadow:0px 0px 5px 1px #333;
+        width: 950px;
+        height: 690px;
+        background-image:url(/resource/scc_tour_images/Tour_Images/console-950.png);
+        background-repeat: no-repeat;
+        background-attachment:scroll;
+    }
+    
+    #pop1{
+        width: 214px;
+        position: absolute;
+        top: 200px;
+        left: 358px;
+        margin: 0;
+    }
+    
+    #pop2{
+        width: 275px;
+        position: absolute;
+        top: 153px;
+        left: 18px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop3{
+        width: 275px;
+        position: absolute;
+        top: 153px;
+        left: 335px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop4{
+        width: 207px;
+        position: absolute;
+        top: 153px;
+        left: 613px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop5{
+        width: 238px;
+        position: absolute;
+        top: 177px;
+        left: 388px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop6{
+        width: 275px;
+        position: absolute;
+        top: 277px;
+        left: 620px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop7{
+        width: 275px;
+        position: absolute;
+        top: 243px;
+        left: 205px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop8{
+        width: 239px;
+        position: absolute;
+        top: 415px;
+        left: 183px;
+        margin: 0;
+        display:none;
+    }
+    
+    #pop9{
+        width: 275px;
+        position: absolute;
+        top: 330px;
+        left: 20px;
+        margin: 0;
+        display:none;
+    }   
+    
+    #pop10{
+        width: 275px;
+        position: absolute;
+        top: 80px;
+        left: 202px;
+        margin: 0;
+        display:none;
+    }
+
+    #pop11{
+        width: 275px;
+        position: absolute;
+        top: 22px;
+        left: 290px;
+        margin: 0;
+        display:none;
+    }   
+    
+    
+    .pointTop{
+        display: block;
+        width: 36px;
+        height: 29px;
+        position: absolute;
+        top: -29px;
+        left: 11px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -3px -236px no-repeat;
+    }
+    
+    .pointTopRight{
+        display: block;
+        width: 36px;
+        height: 29px;
+        position: absolute;
+        top: -29px;
+        left: 151px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -3px -236px no-repeat;
+    }
+    
+    .pointLeft{
+        display: block;
+        width: 29px;
+        height: 29px;
+        position: absolute;
+        top: 15px;
+        left: -30px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -11px -88px no-repeat;
+    }
+    
+    .pointLeftBottom{
+        display: block;
+        width: 29px;
+        height: 29px;
+        position: absolute;
+        top: 55px;
+        left: -30px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -11px -88px no-repeat;
+    }
+    
+    .pointRight{
+        display: block;
+        width: 28px;
+        height: 29px;
+        position: absolute;
+        top: 15px;
+        left: 263px;
+        background: url(/resource/scc_tour_images/Tour_Images/tourArrows.png) -3px -5px no-repeat;
+    }
+    
+    .popUps{
+        display: block;
+        position: absolute;
+        max-width: none;
+        margin: 0;
+        border: 2px solid white;
+        padding: 12px;
+        z-index: 1000;
+        background: #FFE5A7 url(/resource/scc_tour_images/Tour_Images/bg_tour.png) repeat-x;
+        font-weight: normal;
+        -webkit-box-shadow: 0 2px 5px #ACACAC;
+        -moz-box-shadow: 0 0 5px #acacac;
+        box-shadow: 0 0 5px #ACACAC;
+        -moz-border-radius: 5px;
+        -webkit-border-radius: 5px;
+        border-radius: 5px;
+    }
+    
+    .popUps h3{
+        padding: 0;
+        border-bottom: none;
+        margin: 0 0 8px;
+        font-size: 1.1em;
+        font-weight: 700;
+        display: block;
+        line-height: 1em;
+        font-family: Arial,Helvetica,sans-serif;
+        color: #333;
+    }
+    
+    .popUps p {
+        margin: 0 0 8px;
+        line-height: 16px;    
+        color:#333;
+        font-family: arial;
+    }
+    
+    .midLinks{
+        text-decoration:none;
+    }
+    
+    .popUps span{
+        padding:0px 3px;
+    }
+    
+    .popUps a, .popUps a:hover{
+        color: #015BA7;
+        cursor: default;
+    }
+    
+    .popUps .tourNum{
+        display: block;
+        width: 23px;
+        position: absolute;
+        outline: none;
+        font-size: 10px;
+        bottom: 5px;
+        right: 3px;
+        height: 20px;
+        color: #666;
+        font-weight: bold;
+    }
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/scc_tour_style.page-meta.xml b/scr/pages/scc_tour_style.page-meta.xml
new file mode 100644
index 0000000..fe4c110
--- /dev/null
+++ b/scr/pages/scc_tour_style.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>scc_tour_style</label>
+</ApexPage>
diff --git a/scr/pages/test001.page b/scr/pages/test001.page
new file mode 100644
index 0000000..1898369
--- /dev/null
+++ b/scr/pages/test001.page
@@ -0,0 +1,6 @@
+<apex:page id="test" >
+
+
+
+
+</apex:page>
\ No newline at end of file
diff --git a/scr/pages/test001.page-meta.xml b/scr/pages/test001.page-meta.xml
new file mode 100644
index 0000000..65a480a
--- /dev/null
+++ b/scr/pages/test001.page-meta.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <availableInTouch>false</availableInTouch>
+    <confirmationTokenRequired>false</confirmationTokenRequired>
+    <label>test001</label>
+</ApexPage>
diff --git a/scr/staticresources/CommonUtilJs.js b/scr/staticresources/CommonUtilJs.js
new file mode 100644
index 0000000..72814f3
--- /dev/null
+++ b/scr/staticresources/CommonUtilJs.js
@@ -0,0 +1,64 @@
+function keyCheck(keyCodes, num, str){
+    if(keyCodes == 46 || keyCodes == 8 || keyCodes == 37 || keyCodes == 39 || keyCodes == 9){
+        return true;
+    }
+    else if(str.value.length < num && ((keyCodes >= 48 && keyCodes <= 57) || (keyCodes >= 95 && keyCodes <= 105))){
+        return true;
+    }
+    else{
+        return false;
+    }
+}
+function keyCheckAmount(keyCodes, num, str){
+    if(keyCodes == 46 || keyCodes == 8 || keyCodes == 37 || keyCodes == 39 || keyCodes == 9){
+        return true;
+    }
+    else if(str.value.length < num && ((keyCodes >= 48 && keyCodes <= 57) || (keyCodes >= 95 && keyCodes <= 105) || keyCodes == 110 || keyCodes == 190)){
+        return true;
+    }
+    else{
+        return false;
+    }
+}
+function onKeyEvent(e) {
+    e = e || window.event;
+    if(e.keyCode == 13){ //Enter 銈兗
+        if (e.target.type.toUpperCase() != "TEXTAREA") {
+            return false;   //鐒″姽
+        }
+    }
+    return true;
+}
+var getConnectDMLErrorMessages = function (results) {
+    var messages = [],
+        i = 0,
+        len = results.length,
+        r;
+    for (; i < len; i++) {
+        r = results[i];
+        if (! r.getBoolean("success")) {
+            messages = messages.concat(getConnectDMLMessagesOfAResult(r));
+        }
+    }
+    return messages;
+};
+var getConnectDMLMessagesOfAResult = function (res) {
+    var messages = [],
+        errors = res.getArray("errors"),
+        i = 0,
+        len = errors.length,
+        e;
+    for (; i < len; i++) {
+        e = errors[i];
+        messages.push(e.message + "  " + getConnectDMLErrorFields(e));
+    }
+    return messages;
+};
+var getConnectDMLErrorFields = function (error) {
+    var fields = error.getArray('fields');
+    if (fields.length > 0) {
+        return "[" + fields.join(",") + "]"
+    } else {
+        return "";
+    }
+};
\ No newline at end of file
diff --git a/scr/staticresources/CommonUtilJs.resource-meta.xml b/scr/staticresources/CommonUtilJs.resource-meta.xml
new file mode 100644
index 0000000..7922331
--- /dev/null
+++ b/scr/staticresources/CommonUtilJs.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Public</cacheControl>
+    <contentType>application/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/NewQuoteEntryJS.bin b/scr/staticresources/NewQuoteEntryJS.bin
new file mode 100644
index 0000000..a23db37
--- /dev/null
+++ b/scr/staticresources/NewQuoteEntryJS.bin
@@ -0,0 +1,85 @@
+
+
+var searchSetProductWindow = null;
+
+function searchSetProduct(){
+    var quoid = j$(escapeVfId("quoid")).value();
+    var quoteLineSetNameDiscountJson = j$(escapeVfId("quoteLineSetNameDiscountJson")).value();
+    var gainQuoteSetNameAndSetQty = '';
+    if (quoteLineSetNameDiscountJson != '') {
+        var quoteLineSetNameDiscountMap = JSON.parse(quoteLineSetNameDiscountJson); 
+        
+        for (var i =1;i<30;i++) {
+            var SetQty = j$(escapeVfId("Page:mainForm:block:SetQty" + i)).value();
+            var SetName = j$(escapeVfId("Page:mainForm:block:SetName" + i)).value();
+
+            if (SetName != '' ) {
+                
+                if (gainQuoteSetNameAndSetQty == '') {
+                    gainQuoteSetNameAndSetQty = SetName + ',' + SetQty + ',' + quoteLineSetNameDiscountMap[SetName]
+                } else {
+                   gainQuoteSetNameAndSetQty = gainQuoteSetNameAndSetQty + ';' + SetName + ',' + SetQty + ',' + quoteLineSetNameDiscountMap[SetName]
+                }
+
+                //document.getElementById("Page:mainForm:block:SetQty" + i).value = '';
+                //document.getElementById("Page:mainForm:block:SetName" + i).value = '';
+            }
+        }
+    } else {
+        for (var i =1;i<30;i++) {
+            var SetQty = j$(escapeVfId("Page:mainForm:block:SetQty" + i)).value();
+            var SetName = j$(escapeVfId("Page:mainForm:block:SetName" + i)).value();
+
+            if (SetName != '' ) {
+                
+                if (gainQuoteSetNameAndSetQty == '') {
+                    gainQuoteSetNameAndSetQty = SetName + ',' + SetQty + ',' + ''
+                } else {
+                   gainQuoteSetNameAndSetQty = gainQuoteSetNameAndSetQty + ';' + SetName + ',' + SetQty + ',' + ''
+                }
+
+                //document.getElementById("Page:mainForm:block:SetQty" + i).value = '';
+                //document.getElementById("Page:mainForm:block:SetName" + i).value = '';
+            }
+        }
+    }
+    
+    for (var i =1;i<30;i++) {
+        var SetQty = j$(escapeVfId("Page:mainForm:block:SetQty" + i)).value();
+        var SetName = j$(escapeVfId("Page:mainForm:block:SetName" + i)).value();
+
+        if (SetName != '' ) {
+            
+            if (gainQuoteSetNameAndSetQty == '') {
+                gainQuoteSetNameAndSetQty = SetName + ',' + SetQty + ',' + quoteLineSetNameDiscountMap[SetName]
+            } else {
+               gainQuoteSetNameAndSetQty = gainQuoteSetNameAndSetQty + ';' + SetName + ',' + SetQty + ',' + quoteLineSetNameDiscountMap[SetName]
+            }
+
+            //document.getElementById("Page:mainForm:block:SetQty" + i).value = '';
+            //document.getElementById("Page:mainForm:block:SetName" + i).value = '';
+        }
+    }
+    
+    if ( searchSetProductWindow == null || searchSetProductWindow.closed) {
+        
+        if (baseUrl.indexOf("production") != -1) {
+            searchSetProductWindow = window.open('/production/apex/SearchSetProduct?gainQuoteSetNameAndSetQty='+ encodeURIComponent(gainQuoteSetNameAndSetQty), 'SearchSetProduct', 'width=950,height=450');
+        } else {
+            searchSetProductWindow = window.open('/apex/SearchSetProduct?gainQuoteSetNameAndSetQty='+ encodeURIComponent(gainQuoteSetNameAndSetQty), 'SearchSetProduct', 'width=950,height=450');
+        }
+        
+    }
+    else {
+    searchSetProductWindow.focus();
+    }
+}
+
+function setProductEntryGateway(str) {
+    blockme();
+    setProductEntry(str);
+    
+}
+
+
+
diff --git a/scr/staticresources/NewQuoteEntryJS.resource-meta.xml b/scr/staticresources/NewQuoteEntryJS.resource-meta.xml
new file mode 100644
index 0000000..f1bbfbd
--- /dev/null
+++ b/scr/staticresources/NewQuoteEntryJS.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>application/octet-stream</contentType>
+</StaticResource>
diff --git a/scr/staticresources/PleaseWaitDialog.bin b/scr/staticresources/PleaseWaitDialog.bin
new file mode 100644
index 0000000..f739ef3
--- /dev/null
+++ b/scr/staticresources/PleaseWaitDialog.bin
@@ -0,0 +1,201 @@
+function escapeVfId(vfId) {
+    return '#' + vfId.replace(/(:|\.)/g,'\\$1');
+}
+
+function scrollbarWidth() {
+    var $inner = jQuery('<div style="width: 100%; height:200px;">test</div>'),
+        $outer = jQuery('<div style="width:200px;height:150px; position: absolute; top: 0; left: 0; visibility: hidden; overflow:hidden;"></div>').append($inner),
+        inner = $inner[0],
+        outer = $outer[0];
+     
+    jQuery('body').append(outer);
+    var width1 = inner.offsetWidth;
+    $outer.css('overflow', 'scroll');
+    var width2 = outer.clientWidth;
+    $outer.remove();
+ 
+    return (width1 - width2);
+}
+
+function setButtonDisable(object, status){
+	if(!(object.id == 'idGetActive' || object.id == 'Page:mainForm:idDayEdit:idReportDate')) {
+    	object.disabled = status;
+	}
+    if(object.id != 'idGetActive' && object.tagName.toLowerCase() == "input" && (object.type.toLowerCase() == "button" || object.type.toLowerCase() == "submit")) {
+		if(status == true) {
+			object.style.cursor = "default";
+			object.style.backgroundPosition = "0 -90px";
+    		object.style.borderColor = "#C4C4C4";
+    		object.style.color = "#909090";
+    		
+	    } else {
+			object.style.backgroundPosition = "";
+    		object.style.color = "";
+			object.style.cursor = "pointer";
+    		object.style.borderColor = "#B5B5B5 #B5B5B5 #7F7F7F";
+	    }
+    }
+}
+
+function setButtonsDisable(jObj, status){
+    jObj.each(function(index) {
+        setButtonDisable(this, status);
+    });
+}
+
+function number_format_common (number, decimals, dec_point, thousands_sep) {
+  number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
+  var n = !isFinite(+number) ? 0 : +number,
+    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
+    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
+    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
+    s = '',
+    toFixedFix = function (n, prec) {
+      var k = Math.pow(10, prec);
+      return '' + Math.round(n * k) / k;
+    };
+  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
+  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
+  if (s[0].length > 3) {
+    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
+  }
+  if ((s[1] || '').length < prec) {
+    s[1] = s[1] || '';
+    s[1] += new Array(prec - s[1].length + 1).join('0');
+  }
+  return ( s.join(dec));
+}
+function toNum( input) {
+    return number_format_common( input, 2, ".", "");
+}
+function toNumComma( input) {
+    return number_format_common( input, 2, ".", ",");
+}
+
+function localParseFloat( input) {
+    input += "";
+    input = input.split(" ");
+    if (input.length > 1) {
+        input = input[1];
+    } else {
+        input = input[0];
+    }
+    input = input.replace(/,/g, "");
+    input = input.replace(/ /g, "");
+    input = input.replace(/^\s+/, '').replace(/\s+$/, '');
+    if ( input == '' || isNaN( input)) {
+        input = 0.00;
+    }
+    input = parseFloat(input);
+    return input;
+}
+function localParseInt( input) {
+    input += "";
+    input = input.split(" ");
+    if (input.length > 1) {
+        input = input[1];
+    } else {
+        input = input[0];
+    }
+    input = input.replace(/,/g, "");
+    input = input.replace(/ /g, "");
+    input = input.replace(/^\s+/, '').replace(/\s+$/, '');
+    if ( input == '' || isNaN( input)) {
+        input = 0;
+    }
+    input = parseInt(input);
+    return input;
+}
+
+/*************************************************
+ * prototypeを拡張
+ *************************************************/
+(function($) {
+    /**
+     * TODO 値セットのところも対応
+     * fromのvalueを取得、radioの場合書き方が違うため、吸収します
+     * valueが取れない場合、空文字を返す
+     */
+    $.fn.value = function() {
+        var jQueryObj = this;
+        var rtn = [];
+        jQueryObj.each(function(i) {
+            if (this.tagName.toLowerCase() == "input"
+                    || this.tagName.toLowerCase() == "textarea"
+                    || this.tagName.toLowerCase() == "select") {
+                if (this.type.toLowerCase() == "radio" || this.type.toLowerCase() == "checkbox") {
+                    if (this.checked) {
+                        rtn.push(this.value);
+                    }
+                } else {
+                    rtn.push($(this).val());
+                }
+            }
+            else if (this.tagName.toLowerCase() == "span") {
+                rtn.push($(this).text());
+            }
+        });
+        if (rtn.length == 0) {
+            rtn = '';
+        }
+        else if (rtn.length == 1) {
+            rtn = rtn[0];
+        }
+        return rtn;
+    };
+})(jQuery);
+
+j$ = jQuery.noConflict();
+
+function blockme(){
+	j$("body").prepend("<div id='sbArea'><div id='sbArea_contentsArea'><div id='sbArea_contentsArea_msg'>Please wait...</div></div><div id='sbArea_backArea'></div></div>");
+	j$("#sbArea_contentsArea").css({"opacity":"0"}).fadeTo(500, 0.8);
+	j$("#sbArea_backArea").css({"opacity":"0"}).fadeTo(500, 0.4);
+	resizeShadowBox();
+}
+
+//ウィンドのサイズにあわせて位置を調整
+function resizeShadowBox(){
+	var h = j$(document);
+	var winH = j$(window).height();
+	var winW = j$(window).width();
+	var screanWidth = window.screen.width;
+	if (screanWidth < winW) {
+		winH = winH * winW / screanWidth;
+		winW = winW * winW / screanWidth;
+	}
+	var contents = j$("#sbArea_contentsArea")
+	contents.css({"width":"auto","height":"auto"});
+	var iSaBoxH = contents.outerHeight();
+	var iSaBoxW = contents.outerWidth();
+	
+	if(winH >= iSaBoxH+10*2){
+		var innerT = (winH-iSaBoxH)/2;
+	}else{
+		var innerT = 10;
+		iSaBoxH = winH-10*2;
+		iSaBoxW += 20;
+	}
+	if(winW >= iSaBoxW+10*2){
+		var innerL = (winW-iSaBoxW)/2;
+	}else{
+		var innerL =10;
+		iSaBoxW = winW-10*2;
+	}
+	var sbTop = h.scrollTop()
+	
+	var IE6browser = (navigator.userAgent.indexOf("MSIE 6")>=0) ? true : false;
+	if(!IE6browser){
+		j$("#sbArea").css({"width":winW+"px","height":winH+"px","position":"fixed"});
+	}else{
+		j$("#sbArea").css({"width":winW+"px","height":winH+"px","top":h.scrollTop()+"px","left":h.scrollLeft()+"px"});
+	}
+	j$("#sbArea_contentsArea").css({"left":innerL+"px","top":innerT+"px","height":iSaBoxH+"px","width":iSaBoxW+"px"});
+	j$("#sbArea_backArea").css({"width":winW+"px","height":winH+"px"});
+}
+
+function unblockUI(){
+	j$("#sbArea").fadeOut(500, function(){
+		j$("#sbArea").remove();
+	});
+}
diff --git a/scr/staticresources/PleaseWaitDialog.resource-meta.xml b/scr/staticresources/PleaseWaitDialog.resource-meta.xml
new file mode 100644
index 0000000..f1bbfbd
--- /dev/null
+++ b/scr/staticresources/PleaseWaitDialog.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>application/octet-stream</contentType>
+</StaticResource>
diff --git a/scr/staticresources/SWO.jpeg b/scr/staticresources/SWO.jpeg
new file mode 100644
index 0000000..630c483
--- /dev/null
+++ b/scr/staticresources/SWO.jpeg
Binary files differ
diff --git a/scr/staticresources/SWO.resource-meta.xml b/scr/staticresources/SWO.resource-meta.xml
new file mode 100644
index 0000000..6958acb
--- /dev/null
+++ b/scr/staticresources/SWO.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>image/jpeg</contentType>
+</StaticResource>
diff --git a/scr/staticresources/SWOJS.js b/scr/staticresources/SWOJS.js
new file mode 100644
index 0000000..5bbb8d6
--- /dev/null
+++ b/scr/staticresources/SWOJS.js
@@ -0,0 +1,549 @@
+function openPDF(){
+            var baseUrl = j$(escapeVfId("baseUrl")).value();
+            var Id = j$(escapeVfId("Id")).value();
+            if (Id == '') {
+                alert('Please save first Quotes');
+                return;
+            }
+            window.open(baseUrl + '/apex/SendEmail?type=Quotes&typeid=' + Id);
+            window.close();
+
+        }
+        function searchProduct(i,str){
+           var baseUrl = '{!baseUrl}';
+           
+            openPopup(baseUrl + '/apex/SWOSearchProduct?Type=Quotes&lineno=' + i + '&val=' + encodeURIComponent(str), 'setsearch', 950, 450, 'width=950,height=450,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,resizable=1', true);
+        }
+        function sum(i){
+
+            var price = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':RATE')).value().trim();
+            var count = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':quantity')).value().trim();
+            // var regPos = /^[0-9]*$/ ;/// ^\d+$/; // 闈炶礋鏁存暟
+            var regPos = /^(0\.(?!0+$)\d{1,4}|^[0-9][0-9]{0,11}(\.\d{0,4})?)$/;
+            // var regNeg = /^\-[1-9][0-9]*$/; // 璐熸暣鏁�
+    
+            if ( price !=  "" && !regPos.test(price)) {
+
+                alert('RATE has to be a Nonnegative number');
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':RATE')).val(0);
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':AMOUNT')).text(0);
+                return;
+            }
+            if ( count !=  "" && !regPos.test(count)) {
+            
+                alert('quantity has to be a Nonnegative number');
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':quantity')).val(0);
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':AMOUNT')).text(0);
+                return;
+            }
+            if(price != null && price != '' && count != null && count != ''){
+                var sum = price * count;
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':AMOUNT')).text(sum);
+
+
+                var  TAX_RATE = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_RATEDisplay')).value();
+                var TAX_AMT = (sum * TAX_RATE) /100;
+                var GROSS_AMT = sum + TAX_AMT;
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_AMTDisplay')).val(TAX_AMT);
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_AMT')).text(TAX_AMT);
+
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':GROSS_AMTDisplay')).val(GROSS_AMT);
+                j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':GROSS_AMT')).text(GROSS_AMT);
+            }
+        }
+
+        function getLastLineNoNext(doc) {
+            var hasRecordFlg = false;
+            var lastLineNo = 0;
+            for(var i=99; i>=0; i--){
+                if (j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + i + ':ProductName')).value() != ''){
+                    if (!hasRecordFlg) {
+                        lastLineNo = i;
+                    }
+                    hasRecordFlg = true;
+                }
+                if (hasRecordFlg == true) {
+                    if (j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + i + ':ProductName')).value() == ''){
+                        var moveCheckbox = true;
+                        lastLineNo = i;
+                    }
+                }
+            }
+            if (hasRecordFlg) {
+                lastLineNo = lastLineNo + 1;
+            }
+            return lastLineNo;
+        }
+
+        function save2btn() {
+            blockme();
+            checkchangedAfterPrint();
+            Save.call();
+        }
+
+        function checkchangedAfterPrint(){
+            var productInfoList = [];
+            for(var i=0; i<150; i++){
+                var item = new Object();
+                var basic = 'Page:allForm:allBlock:ProductInfoList:theTable_content:';
+                item.productId = j$(escapeVfId(basic + i + ':productId')).value();
+                item.lineNumber = j$(escapeVfId(basic + i + ':lineNumber')).value();
+                productInfoList.push(item);
+            }
+            // alert(productInfoList);
+        }
+
+        function StatusChangeFunction(){
+                var status = j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:STATUS')).value();
+                  var rtn = '';
+                  if (status =='Closed - Budget only' || status =='Closed - Lost to Competition' 
+                      || status =='Closed - No need for our product' || status =='Closed - Opportunity Cancelled'){
+                        rtn = 0.0;
+                  }
+                
+                  if (status =='Prospect' || status =='Qualifying'){
+                       rtn = 25.0;
+                  }
+                  if (status =='Funding in Progress') {
+                       rtn = 30.0 ;
+                  }
+                  if (status =='Decision Makers Identified') {
+                       rtn = 35.0 ;
+                  }
+                  if (status =='Funding Received') {
+                       rtn = 40.0;
+                  }
+                  if (status =='In Purchasing') {
+                       rtn = 75.0;
+                  }
+                  if (status =='Closing') {
+                       rtn = 90.0 ;
+                  }
+                  // alert(rtn);
+                  j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:PROBABILITY')).text(rtn);
+                  
+                  j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:DisplayPROBABILITY')).val(rtn);
+        }
+
+        function QuotesTypeChangeFunction(){
+            var quotesType = j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:QuotesType')).value();
+            var message01 = '';
+            var message02 = '';
+            var message03 = '';
+            var message04 = '';
+            var message05 = '';
+            var message06 = '';
+            var message07 = '';
+            if ('缁翠慨鎶ヤ环鍗�' == quotesType) {
+                // var message01 = 'Test';
+                // var message01 = '鍦ㄧ淮淇殑杩囩▼涓紝鑻ュ彂鐜版柊鏁呴殰锛屾垜浠皢鍙﹀缁欐偍鎶ヤ环銆�';
+               
+                var message01 = '-缁翠慨璐ㄤ繚鏈熶负浠櫒鍙戣揣鍚庝笁涓湀鍔犲叓澶┿��';
+                var message02 = '-濡傛偍纭姝ゆ姤浠峰苟鍚屾剰缁翠慨锛屾暚璇锋偍鍦�90澶╀箣鍐呭畬鎴愪粯娆俱�傚惁鍒欐偍鐨勪华鍣ㄨ灏嗚涓烘斁寮冪淮淇紝鎴戜滑浼氫互杩愯垂鍒颁粯鐨勬柟寮忔妸浠櫒缁欐偍瀵勫洖,骞跺悜鎮ㄦ敹鍙�1000鍏冪殑妫�娴嬭垂鐢ㄣ��';
+                var message03 = '-鐢ㄦ埛鍦ㄦ纭鍚屾剰姝ゆ缁翠慨鎶ヤ环锛�';
+                var message04 = '瀹㈡埛绛惧瓧鎴栫洊绔狅細';
+                var message05 = '鏃ユ湡锛�';
+                var message06 = '';
+                var message07 = '';
+                
+            } else if ('闆朵欢鎶ヤ环鍗�' == quotesType) {
+                var message01 = '-濂ユ灄宸存柉鏈嶅姟閮ㄥ敭鍑虹殑缁翠慨閰嶄欢纭繚涓鸿川閲忕鍚堝ゥ鏋楀反鏂弬鏁版寚鏍囩殑鏂板搧锛屽ゥ鏋楀反鏂鍞嚭鐨勭淮淇厤浠朵笉鎻愪緵淇濅慨鏈嶅姟锛屽悓鏃朵篃涓嶆彁渚涢��銆佹崲璐ф湇鍔°�傛暚璇锋偍璋ㄦ厧璐拱銆�';
+                var message02 = '-鐢ㄦ埛鍦ㄦ纭姝ゆ鎶ヤ环锛屽喅瀹氳喘涔帮細';
+                var message03 = '瀹㈡埛绛惧瓧鎴栫洊绔狅細';
+                var message04 = '鏃ユ湡锛�';
+                var message05 = '';
+                var message06 = '';
+                var message07 = '';
+                
+            } else if (null == quotesType) {
+	var message02 = '7889';
+            }
+
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message01')).text(message01);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message02')).text(message02);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message03')).text(message03);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message04')).text(message04);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message05')).text(message05);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message06')).text(message06);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:message07')).text(message07);
+            
+        }
+
+        function DISCOUNTITEMChangeFunction(){
+            var discount = j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:DISCOUNT_ITEM')).value();
+            var rtn = '';
+            if (discount == 'ANI Prom Discount 2'){
+                rtn = -500 ;
+            }
+
+            if (discount == 'Education Discount - Adv' || 
+                discount == 'Education Discount - ANI' || 
+                discount == 'Education Discount - Pana' || 
+                discount == 'Education Discount - RVI' ||
+                discount == 'Education Discount -Nortec,Sonic' || 
+                discount == 'Special Discount ANI' ||
+                discount == 'Special Discount ANI Service' || 
+                discount == 'Trainers Discount 鈥� ADVANCED NDT' || 
+                discount == 'Special Discount ANI Service TPP' || 
+                discount == 'Distributor\'s discount'){
+                rtn = -10;
+            }
+            if (discount == 'Global Trade-In Discount - C-Series' ||
+                discount == 'Global Trade-In Discount - C-Series w/ Camera' ||
+                discount == 'Global Trade-In Discount - C-Series w/ Multi-Cameras' ||
+                discount == 'Global Trade-In Discount - M-Series w/ Camera' ||
+                discount == 'Global Trade-In Discount - C-Series w/ Multi-Cameras & Collimator' ||
+                discount == 'Global Trade-In Discount - M-Series' ||
+                discount == 'Global Trade-In Discount - M-Series w/ Multi-Cameras' ||
+                discount == 'Global Trade-In Discount - M-Series w/ Multi-Cameras & Collimator' ){
+                rtn = -25; 
+            }
+            if (discount == 'Special Discount-Non-Olympus Products' ||
+                discount == 'Special Disctount' ) {
+                rtn = -5;
+            } 
+            if (discount == 'special discount 2') {
+                rtn = -15;
+            }
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:RATE')).text(rtn);
+            j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:RATEDisplay')).val(rtn);
+
+        }
+
+        function TAXCODEChangeFunction(i){
+            var price = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':RATE')).value().trim();
+            var count = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':quantity')).value().trim();
+
+            var TAX_CODE = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_CODE')).value();
+            var rtn = '';
+            if (TAX_CODE == 'VAT_CN:CN_S 5') {
+                rtn = 5;
+            }
+            if (TAX_CODE == 'VAT_CN:S-CN 13') {
+                rtn = 13;
+            }
+            if (TAX_CODE == 'VAT_CN:S-CN 16') {
+                rtn = 16;
+            }
+            if (TAX_CODE == 'VAT_CN:UNDEF_CN') {
+                rtn = 0;
+            }
+            var TAX_AMT = (price * count * rtn)/100;
+
+            var GROSS_AMT = (price * count) + TAX_AMT;
+            
+            j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_RATEDisplay')).val(rtn);
+            j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_RATE')).text(rtn);
+            j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_AMTDisplay')).val(TAX_AMT);
+            j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':TAX_AMT')).text(TAX_AMT);
+
+            j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':GROSS_AMTDisplay')).val(GROSS_AMT);
+            j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + (i-1) + ':GROSS_AMT')).text(GROSS_AMT);
+            
+        }
+
+        function focusFunction(){
+             j$(escapeVfId('Page:allForm:allBlock:Quotes:unEditable:CURRENCY')).focus();
+        }
+        function replaceErrorClass(){
+
+            var div=document.getElementsByTagName('div');
+            for(var e in div){
+                if(div[e].className=='errorMsg'){
+                    div[e].className = 'dataCell';
+                    //div[e].innerHTML=div[e].innerHTML.replace(/Error_Message40/g,'');
+                    div[e].innerHTML=div[e].innerHTML.replace(Error_Message40,'');
+                    //div[e].innerHTML=div[e].innerHTML.replace(/Error_Message3/g,'');
+                    div[e].innerHTML=div[e].innerHTML.replace(Error_Message3,'');
+                }
+            }
+            var input=document.getElementsByTagName('input');
+            for(var i in input){
+                if(input[i].className=='error'){
+                    input[i].className = 'dataCell';
+                }
+            }
+
+        }
+        function getLastLineNoNext(doc) {
+            // Page:allForm:allBlock:ProductInfoList:theTable_content:0:ProductName
+            var hasRecordFlg = false;
+            var lastLineNo = 0;
+            for(var i=149; i>=0; i--){
+                if (j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + i + ':ProductName')).value() != ''){
+                    if (!hasRecordFlg) {
+                        lastLineNo = i;
+                    }
+                    hasRecordFlg = true;
+                }
+                if (hasRecordFlg == true) {
+                    if (j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + i + ':ProductName')).value() == ''){
+                        // var moveCheckbox = true;
+                        // deletelist(i, doc, moveCheckbox);
+                        lastLineNo = i;
+                    }
+                }
+            }
+            if (hasRecordFlg) {
+                lastLineNo = lastLineNo + 1;
+            }
+            return lastLineNo;
+        }
+
+        function radioChecker2(str){
+            
+            j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:Btn_RowUp")).attr("disabled", true);
+            j$(escapeVfId("Page:allForm:allBlock:ProductInfoList:Btn_RowDown")).attr("disabled", true);
+
+            //error鍒濇湡鍖�
+            replaceErrorClass.call();
+            var lastLineNoNext = getLastLineNoNext(document);
+            try {
+                var hasCheckedCnt = 0;
+                for(var i=0; i<lastLineNoNext; i++){
+                    
+                    var iChecked = document.forms['Page:allForm']['checklist'][i].checked;
+                    if (iChecked) {
+                        hasCheckedCnt++;
+                        if (hasCheckedCnt > 1) {
+                            // 瑜囨暟浠躲儊銈с儍銈仌銈屻仸銇勩倠銇嬨�併倧銇嬨倢銇癰reak;
+                            break;
+                        }
+                    }
+                }
+                if (hasCheckedCnt == 0) {
+                    throw '璇烽�夋嫨鍙互鎿嶄綔鐨勮';
+                }
+
+                var hasCheckedCnt1 = 0;                      // 瀹熼殯澶夋洿銇с亶銇熶欢鏁�
+                if (str=='up'){
+                    for(var i=0; i<lastLineNoNext; i++){
+                        var iChecked = document.forms['Page:allForm']['checklist'][i].checked;
+                        if (!iChecked) { continue; }
+                        if (i==0){
+                            throw '绗竴琛屼笉鍙互Up銆�';
+                        } else {
+                            if (setlists(str,i)) {
+                                hasCheckedCnt1++;
+                            } else {
+                                if (hasCheckedCnt1 == 0) {
+                                    // 绉诲嫊銇с亶銇亜
+                                    throw '绗竴琛屼笉鍙互Up銆�';
+                                }
+                            }
+                        }
+                    }
+                }else if(str=='down'){
+                    for(var i=lastLineNoNext-1; i>=0; i--){
+                        var iChecked = document.forms['Page:allForm']['checklist'][i].checked;
+                        if (!iChecked) { continue; }
+                        if (i==149 && iChecked){
+                            throw '鏈�鍚庝竴琛屼笉鍙互Down銆�';
+                        }else{
+                            if (setlists(str,i)) {
+                                hasCheckedCnt1++;
+                            } else {
+                                if (hasCheckedCnt1 == 0) {
+                                    // 绉诲嫊銇с亶銇亜
+                                    throw '鏈�鍚庝竴琛屼笉鍙互Down銆�';
+                                }
+                            }
+                        }
+                    }
+                }else{
+                    throw 'Unknow Operation';
+                }
+            } catch(e) {
+                alert(e);
+            }
+    
+            document.getElementById("Page:allForm:allBlock:ProductInfoList:Btn_RowUp").disabled = false;
+            document.getElementById("Page:allForm:allBlock:ProductInfoList:Btn_RowDown").disabled = false;
+            return true;
+        }
+
+        function setlists(str, i){
+            var iChecked = document.forms['Page:allForm']['checklist'][i].checked;
+
+            if (!iChecked) {
+                return false;
+            }
+            var j = 0;
+            if (str=='up'){
+                j = parseInt(i) - 1;
+                var b = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + j + ':ProductName')).value();
+                if (b==null || b==''){
+                    return false;
+                }
+            }else{
+                //down
+                j = parseInt(i) + 1;
+                var b = j$(escapeVfId('Page:allForm:allBlock:ProductInfoList:theTable_content:' + j + ':ProductName')).value();
+                if (b==null || b==''){
+                    return false;
+                }
+            }
+            var jChecked = j$(escapeVfId('checklist')[j]).checked;
+            
+            var basic = 'Page:allForm:allBlock:ProductInfoList:theTable_content:';
+
+            var quotesItemIdDisplayDown = j$(escapeVfId(basic + j + ':quotesItemIdDisplay')).value();
+            var quotesItemIdDisplayUp = j$(escapeVfId(basic + i + ':quotesItemIdDisplay')).value();
+            j$(escapeVfId(basic + j + ':quotesItemIdDisplay')).val(quotesItemIdDisplayUp);
+            j$(escapeVfId(basic + i + ':quotesItemIdDisplay')).val(quotesItemIdDisplayDown);
+            // productId
+            var productIdDown = j$(escapeVfId(basic + j + ':productId')).value();
+            var productIdUp = j$(escapeVfId(basic + i + ':productId')).value();
+            j$(escapeVfId(basic + j + ':productId')).val(productIdUp);
+            j$(escapeVfId(basic + i + ':productId')).val(productIdDown);
+
+
+            var QuotesItemNameLinkDown = j$(escapeVfId(basic + j + ':QuotesItemNameLink')).html();
+            var QuotesItemNameLinkUp = j$(escapeVfId(basic + i + ':QuotesItemNameLink')).html();
+            j$(escapeVfId(basic + j + ':QuotesItemNameLink')).html(QuotesItemNameLinkUp);
+            j$(escapeVfId(basic + i + ':QuotesItemNameLink')).html(QuotesItemNameLinkDown);
+
+            var ProductNameDown = j$(escapeVfId(basic + j + ':ProductName')).value();
+            var ProductNameUp = j$(escapeVfId(basic + i + ':ProductName')).value();
+            j$(escapeVfId(basic + j + ':ProductName')).val(ProductNameUp);
+            j$(escapeVfId(basic + i + ':ProductName')).val(ProductNameDown);
+            //PART_NUMBER
+            var PART_NUMBERDown = j$(escapeVfId(basic + j + ':PART_NUMBER')).value();
+            var PART_NUMBERUp = j$(escapeVfId(basic + i + ':PART_NUMBER')).value();
+            j$(escapeVfId(basic + j + ':PART_NUMBER')).text(PART_NUMBERUp);
+            j$(escapeVfId(basic + i + ':PART_NUMBER')).text(PART_NUMBERDown);
+
+            //quantity
+            var quantityDown = j$(escapeVfId(basic + j + ':quantity')).value();
+            var quantityUp = j$(escapeVfId(basic + i + ':quantity')).value();
+            j$(escapeVfId(basic + j + ':quantity')).val(quantityUp);
+            j$(escapeVfId(basic + i + ':quantity')).val(quantityDown);
+            //Description
+            var DescriptionDown = j$(escapeVfId(basic + j + ':Description')).value();
+            var DescriptionUp = j$(escapeVfId(basic + i + ':Description')).value();
+            j$(escapeVfId(basic + j + ':Description')).val(DescriptionUp);
+            j$(escapeVfId(basic + i + ':Description')).val(DescriptionDown);
+            // PRICE_LEVEL
+            var PRICE_LEVELDown = j$(escapeVfId(basic + j + ':PRICE_LEVEL')).value();
+            var PRICE_LEVELUp = j$(escapeVfId(basic + i + ':PRICE_LEVEL')).value();
+            j$(escapeVfId(basic + j + ':PRICE_LEVEL')).val(PRICE_LEVELUp);
+            j$(escapeVfId(basic + i + ':PRICE_LEVEL')).val(PRICE_LEVELDown);
+            // RATE
+            var RATEDown = j$(escapeVfId(basic + j + ':RATE')).value();
+            var RATEUp = j$(escapeVfId(basic + i + ':RATE')).value();
+            j$(escapeVfId(basic + j + ':RATE')).val(RATEUp);
+            j$(escapeVfId(basic + i + ':RATE')).val(RATEDown);
+
+            var AMOUNTDown = j$(escapeVfId(basic + j + ':AMOUNT')).value();
+            var AMOUNTUp = j$(escapeVfId(basic + i + ':AMOUNT')).value();
+            if(AMOUNTDown == ''){
+               AMOUNTDown = '0.00'; 
+            }
+            if(AMOUNTUp == ''){
+               AMOUNTUp = '0.00'; 
+            }
+            j$(escapeVfId(basic + j + ':AMOUNT')).text(AMOUNTUp);
+            j$(escapeVfId(basic + i + ':AMOUNT')).text(AMOUNTDown);
+
+            var PRE_APPROVED_DISCOUNTDown = j$(escapeVfId(basic + j + ':PRE-APPROVED_DISCOUNT')).value();
+            var PRE_APPROVED_DISCOUNTUp = j$(escapeVfId(basic + i + ':PRE-APPROVED_DISCOUNT')).value();
+            j$(escapeVfId(basic + j + ':PRE-APPROVED_DISCOUNT')).val(PRE_APPROVED_DISCOUNTUp);
+            j$(escapeVfId(basic + i + ':PRE-APPROVED_DISCOUNT')).val(PRE_APPROVED_DISCOUNTDown);
+
+            var DISCOUNTED_RATEDown = j$(escapeVfId(basic + j + ':DISCOUNTED_RATE')).value();
+            var DISCOUNTED_RATEUp = j$(escapeVfId(basic + i + ':DISCOUNTED_RATE')).value();
+            j$(escapeVfId(basic + j + ':DISCOUNTED_RATE')).val(DISCOUNTED_RATEUp);
+            j$(escapeVfId(basic + i + ':DISCOUNTED_RATE')).val(DISCOUNTED_RATEDown);
+
+
+            var EST_COSTDown = j$(escapeVfId(basic + j + ':EST_COST')).value();
+            var EST_COSTUp = j$(escapeVfId(basic + i + ':EST_COST')).value();
+            j$(escapeVfId(basic + j + ':EST_COST')).val(EST_COSTUp);
+            j$(escapeVfId(basic + i + ':EST_COST')).val(EST_COSTDown);
+
+
+            var EST_GROSS_MARGINDown = j$(escapeVfId(basic + j + ':EST_GROSS_MARGIN')).value();
+            var EST_GROSS_MARGINUp = j$(escapeVfId(basic + i + ':EST_GROSS_MARGIN')).value();
+            j$(escapeVfId(basic + j + ':EST_GROSS_MARGIN')).val(EST_GROSS_MARGINUp);
+            j$(escapeVfId(basic + i + ':EST_GROSS_MARGIN')).val(EST_GROSS_MARGINDown);
+
+            var TAX_CODEDown = j$(escapeVfId(basic + j + ':TAX_CODE')).value();
+            var TAX_CODEUp = j$(escapeVfId(basic + i + ':TAX_CODE')).value();
+            j$(escapeVfId(basic + j + ':TAX_CODE')).val(TAX_CODEUp);
+            j$(escapeVfId(basic + i + ':TAX_CODE')).val(TAX_CODEDown);
+
+            var TAX_RATEDown = j$(escapeVfId(basic + j + ':TAX_RATE')).value();
+            var TAX_RATEUp = j$(escapeVfId(basic + i + ':TAX_RATE')).value();
+            if(TAX_RATEDown == ''){
+               TAX_RATEDown = '0.00'; 
+            }
+            if(TAX_RATEUp == ''){
+               TAX_RATEUp = '0.00'; 
+            }
+            
+            j$(escapeVfId(basic + j + ':TAX_RATE')).text(TAX_RATEUp);
+            j$(escapeVfId(basic + i + ':TAX_RATE')).text(TAX_RATEDown);
+            j$(escapeVfId(basic + j + ':TAX_RATEDisplay')).val(TAX_RATEUp);
+            j$(escapeVfId(basic + i + ':TAX_RATEDisplay')).val(TAX_RATEDown);
+
+            var TAX_AMTDown = j$(escapeVfId(basic + j + ':TAX_AMT')).value();
+            var TAX_AMTUp = j$(escapeVfId(basic + i + ':TAX_AMT')).value();
+            if(TAX_AMTDown == ''){
+               TAX_AMTDown = '0.00'; 
+            }
+            if(TAX_AMTUp == ''){
+               TAX_AMTUp = '0.00'; 
+            }
+            j$(escapeVfId(basic + j + ':TAX_AMT')).text(TAX_AMTUp);
+            j$(escapeVfId(basic + i + ':TAX_AMT')).text(TAX_AMTDown);
+            // TAX_AMTDisplay
+            j$(escapeVfId(basic + j + ':TAX_AMTDisplay')).val(rMoney(TAX_AMTUp));
+            j$(escapeVfId(basic + i + ':TAX_AMTDisplay')).val(rMoney(TAX_AMTDown));
+
+            var GROSS_AMTDown = j$(escapeVfId(basic + j + ':GROSS_AMT')).value();
+            var GROSS_AMTUp = j$(escapeVfId(basic + i + ':GROSS_AMT')).value();
+            if(GROSS_AMTDown == ''){
+               GROSS_AMTDown = '0.00'; 
+            }
+            if(GROSS_AMTUp == ''){
+               GROSS_AMTUp = '0.00'; 
+            }
+            j$(escapeVfId(basic + j + ':GROSS_AMT')).text(rMoney(GROSS_AMTUp));
+            j$(escapeVfId(basic + i + ':GROSS_AMT')).text(rMoney(GROSS_AMTDown));
+            
+            j$(escapeVfId(basic + j + ':GROSS_AMTDisplay')).val(rMoney(GROSS_AMTUp));
+            j$(escapeVfId(basic + i + ':GROSS_AMTDisplay')).val(rMoney(GROSS_AMTDown)); 
+            
+            var LOCATIONDown = j$(escapeVfId(basic + j + ':LOCATION')).value();
+            var LOCATIONUp = j$(escapeVfId(basic + i + ':LOCATION')).value();
+            j$(escapeVfId(basic + j + ':LOCATION')).val(LOCATIONUp);
+            j$(escapeVfId(basic + i + ':LOCATION')).val(LOCATIONDown);
+
+            var OPTIONSDown = j$(escapeVfId(basic + j + ':OPTIONS')).value();
+            var OPTIONSUp = j$(escapeVfId(basic + i + ':OPTIONS')).value();
+            j$(escapeVfId(basic + j + ':OPTIONS')).val(OPTIONSUp);
+            j$(escapeVfId(basic + i + ':OPTIONS')).val(OPTIONSDown);
+
+            var EXPECTED_SHIP_DATEDown = j$(escapeVfId(basic + j + ':EXPECTED_SHIP_DATE')).value();
+            var EXPECTED_SHIP_DATEUp = j$(escapeVfId(basic + i + ':EXPECTED_SHIP_DATE')).value();
+            j$(escapeVfId(basic + j + ':EXPECTED_SHIP_DATE')).val(EXPECTED_SHIP_DATEUp);
+            j$(escapeVfId(basic + i + ':EXPECTED_SHIP_DATE')).val(EXPECTED_SHIP_DATEDown);
+
+            var ITEM_NOTEDown = j$(escapeVfId(basic + j + ':ITEM_NOTE')).value();
+            var ITEM_NOTEUp = j$(escapeVfId(basic + i + ':ITEM_NOTE')).value();
+            j$(escapeVfId(basic + j + ':ITEM_NOTE')).val(ITEM_NOTEUp);
+            j$(escapeVfId(basic + i + ':ITEM_NOTE')).val(ITEM_NOTEDown);
+
+            var SERIALIZEDDown = j$(escapeVfId(basic + j + ':SERIALIZED')).value();
+            var SERIALIZEDUp = j$(escapeVfId(basic + i + ':SERIALIZED')).value();
+            j$(escapeVfId(basic + j + ':SERIALIZED')).val(SERIALIZEDUp);
+            j$(escapeVfId(basic + i + ':SERIALIZED')).val(SERIALIZEDDown);
+   
+            document.forms['Page:allForm']['checklist'][i].checked=jChecked;
+            document.forms['Page:allForm']['checklist'][j].checked=true;
+            return true;
+        }
+
+        function rMoney(num){
+            return parseFloat(num.replace(/[^\d\\.-]/g,''));
+        }
\ No newline at end of file
diff --git a/scr/staticresources/SWOJS.resource-meta.xml b/scr/staticresources/SWOJS.resource-meta.xml
new file mode 100644
index 0000000..168f589
--- /dev/null
+++ b/scr/staticresources/SWOJS.resource-meta.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Public</cacheControl>
+    <contentType>application/x-javascript</contentType>
+    <description>SWO椤圭洰鍏辩敤</description>
+</StaticResource>
diff --git a/scr/staticresources/ServiceCloudLogo.png b/scr/staticresources/ServiceCloudLogo.png
new file mode 100644
index 0000000..e4fca4d
--- /dev/null
+++ b/scr/staticresources/ServiceCloudLogo.png
Binary files differ
diff --git a/scr/staticresources/ServiceCloudLogo.resource-meta.xml b/scr/staticresources/ServiceCloudLogo.resource-meta.xml
new file mode 100644
index 0000000..f7d6923
--- /dev/null
+++ b/scr/staticresources/ServiceCloudLogo.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>image/png</contentType>
+</StaticResource>
diff --git a/scr/staticresources/SiteSamples.resource-meta.xml b/scr/staticresources/SiteSamples.resource-meta.xml
new file mode 100644
index 0000000..150a578
--- /dev/null
+++ b/scr/staticresources/SiteSamples.resource-meta.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Public</cacheControl>
+    <contentType>application/zip</contentType>
+    <description>绔欑偣绀轰緥椤甸潰鐨勯潤鎬佽祫婧�</description>
+</StaticResource>
diff --git a/scr/staticresources/SiteSamples/SiteStyles.css b/scr/staticresources/SiteSamples/SiteStyles.css
new file mode 100644
index 0000000..c61cbc0
--- /dev/null
+++ b/scr/staticresources/SiteSamples/SiteStyles.css
@@ -0,0 +1,28 @@
+.topPanelContainer {
+	text-align:left;
+	border:1px solid #ccc;
+}
+
+.topPanel {
+    background-color: white;
+    border: 1px solid #ccc;
+    padding: 0px;
+    margin-top: 10px;
+    margin-bottom: 0px;
+    margin-left: 10px;
+    margin-right: 10px;
+}
+
+.title {
+    font-size: larger;
+    font-weight: bold;
+}
+
+.poweredByImage {
+	vertical-align: middle;
+	margin:12px 8px 8px 0;
+}
+
+img {
+    border: none;
+}
\ No newline at end of file
diff --git a/scr/staticresources/SiteSamples/img/clock.png b/scr/staticresources/SiteSamples/img/clock.png
new file mode 100644
index 0000000..dc1cbec
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/clock.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/construction.png b/scr/staticresources/SiteSamples/img/construction.png
new file mode 100644
index 0000000..236ead9
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/construction.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/force_logo.png b/scr/staticresources/SiteSamples/img/force_logo.png
new file mode 100644
index 0000000..9612228
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/force_logo.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/maintenance.png b/scr/staticresources/SiteSamples/img/maintenance.png
new file mode 100644
index 0000000..45b636a
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/maintenance.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/poweredby.png b/scr/staticresources/SiteSamples/img/poweredby.png
new file mode 100644
index 0000000..806fba8
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/poweredby.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/tools.png b/scr/staticresources/SiteSamples/img/tools.png
new file mode 100644
index 0000000..e428853
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/tools.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/unauthorized.png b/scr/staticresources/SiteSamples/img/unauthorized.png
new file mode 100644
index 0000000..d0d07e2
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/unauthorized.png
Binary files differ
diff --git a/scr/staticresources/SiteSamples/img/warning.png b/scr/staticresources/SiteSamples/img/warning.png
new file mode 100644
index 0000000..b49fd8f
--- /dev/null
+++ b/scr/staticresources/SiteSamples/img/warning.png
Binary files differ
diff --git a/scr/staticresources/StageMapJs.js b/scr/staticresources/StageMapJs.js
new file mode 100644
index 0000000..d0522b6
--- /dev/null
+++ b/scr/staticresources/StageMapJs.js
@@ -0,0 +1,69 @@
+锘�/*
+ * 鍚勮銆佷竴鐣洰銇従鍦ㄣ伄Stage銆佷簩鐣洰銇嬨倝銇偗銉儍銈仹銇嶃倠Stage
+ * 
+ * 琛屻倰瀹氱京銇椼仾銇勫牬鍚堛�佷簩鐣洰銇嬨倝Stage銈掑畾缇┿仐銇亜鍫村悎銆併偗銉儍銈笉鑳姐伀銇倠
+ */
+var SSBD =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_Approval =
+[["Prospect Created"]
+,["Phase1"]
+,["Phase2"]
+,["Phase3"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_Service =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+/*
+ * 姣忚绗竴涓」鐩槸鐜板湪鐨勭姸鎬侊紝绗簩涓」鐩紑濮嬫槸鍙樿壊鐨勭姸鎬�
+ * 
+ * 娌℃湁瀹氫箟鐨勮锛岀涓�涓」鐩箣鍚庢病鏈夊叾浠栭」鐩紝鐘舵�佷笉鍙樿壊
+ */
+var SSBDCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_ApprovalCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_ServiceCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
\ No newline at end of file
diff --git a/scr/staticresources/StageMapJs.resource-meta.xml b/scr/staticresources/StageMapJs.resource-meta.xml
new file mode 100644
index 0000000..2754b4b
--- /dev/null
+++ b/scr/staticresources/StageMapJs.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>application/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/StageMapJsNew.js b/scr/staticresources/StageMapJsNew.js
new file mode 100644
index 0000000..8aa11ad
--- /dev/null
+++ b/scr/staticresources/StageMapJsNew.js
@@ -0,0 +1,89 @@
+/*
+ * 鍚勮銆佷竴鐣洰銇従鍦ㄣ伄Stage銆佷簩鐣洰銇嬨倝銇偗銉儍銈仹銇嶃倠Stage
+ * 
+ * 琛屻倰瀹氱京銇椼仾銇勫牬鍚堛�佷簩鐣洰銇嬨倝Stage銈掑畾缇┿仐銇亜鍫村悎銆併偗銉儍銈笉鑳姐伀銇倠
+ */
+var SSBD =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_Approval =
+[["Prospect Created"]
+,["Phase1"]
+,["Phase2"]
+,["Phase3"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_Service =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+/*
+ * 姣忚绗竴涓」鐩槸鐜板湪鐨勭姸鎬侊紝绗簩涓」鐩紑濮嬫槸鍙樿壊鐨勭姸鎬�
+ * 
+ * 娌℃湁瀹氫箟鐨勮锛岀涓�涓」鐩箣鍚庢病鏈夊叾浠栭」鐩紝鐘舵�佷笉鍙樿壊
+ */
+var SSBDCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_Replacement =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_ReplacementCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_ApprovalCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_ServiceCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
\ No newline at end of file
diff --git a/scr/staticresources/StageMapJsNew.resource-meta.xml b/scr/staticresources/StageMapJsNew.resource-meta.xml
new file mode 100644
index 0000000..6adb110
--- /dev/null
+++ b/scr/staticresources/StageMapJsNew.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/StageMapJsNew1.js b/scr/staticresources/StageMapJsNew1.js
new file mode 100644
index 0000000..1f963f0
--- /dev/null
+++ b/scr/staticresources/StageMapJsNew1.js
@@ -0,0 +1,170 @@
+锘�/*
+ * 鍚勮銆佷竴鐣洰銇従鍦ㄣ伄Stage銆佷簩鐣洰銇嬨倝銇偗銉儍銈仹銇嶃倠Stage
+ * 
+ * 琛屻倰瀹氱京銇椼仾銇勫牬鍚堛�佷簩鐣洰銇嬨倝Stage銈掑畾缇┿仐銇亜鍫村悎銆併偗銉儍銈笉鑳姐伀銇倠
+ */
+var SSBD =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_Approval =
+[["Prospect Created"]
+,["Phase1"]
+,["Phase2"]
+,["Phase3"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_Service =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+/*
+ * 姣忚绗竴涓」鐩槸鐜板湪鐨勭姸鎬侊紝绗簩涓」鐩紑濮嬫槸鍙樿壊鐨勭姸鎬�
+ * 
+ * 娌℃湁瀹氫箟鐨勮锛岀涓�涓」鐩箣鍚庢病鏈夊叾浠栭」鐩紝鐘舵�佷笉鍙樿壊
+ */
+var SSBDCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_Replacement =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_ReplacementCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var Cross_regional_sales =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var Cross_regional_salesCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var HighendCross_regional_sales =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var HighendCross_regional_salesCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+
+var SSBD_ApprovalCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_ServiceCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var SSBD_HighendProducts =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var SSBD_HighendProductsCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
+
+var IE_SSBD =
+[["Prospect Created","Phase1","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase1","Phase2","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase2","Phase3","Closed Lost","Closed Cancel","澶辫触","鍙栨秷"]
+,["Phase3","Closed Won","Closed Lost","Closed Cancel","瀹屾垚","澶辫触","鍙栨秷"]
+,["Closed Won"]
+,["Closed Lost"]
+,["Closed Cancel"]
+];
+
+var IE_SSBDCOLOR =
+[["Prospect Created","Prospect Created"]
+,["Phase1","Prospect Created","Phase1"]
+,["Phase2","Prospect Created","Phase1","Phase2"]
+,["Phase3","Prospect Created","Phase1","Phase2","Phase3"]
+,["Closed Won","Prospect Created","Phase1","Phase2","Phase3","Closed Won","瀹屾垚"]
+,["Closed Lost","Prospect Created","Phase1","Phase2","Phase3","Closed Lost","澶辫触"]
+,["Closed Cancel","Prospect Created","Phase1","Phase2","Phase3","Closed Cancel","鍙栨秷"]
+];
\ No newline at end of file
diff --git a/scr/staticresources/StageMapJsNew1.resource-meta.xml b/scr/staticresources/StageMapJsNew1.resource-meta.xml
new file mode 100644
index 0000000..4b411f2
--- /dev/null
+++ b/scr/staticresources/StageMapJsNew1.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>application/x-javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/StageProgressBarCss.css b/scr/staticresources/StageProgressBarCss.css
new file mode 100644
index 0000000..41100c7
--- /dev/null
+++ b/scr/staticresources/StageProgressBarCss.css
@@ -0,0 +1,276 @@
+/*-------------------------
+	Simple reset
+--------------------------*/
+
+
+*{
+	margin:0;
+	padding:0;
+}
+
+
+/*-------------------------
+	General Styles
+--------------------------*/
+
+
+body{
+	font:15px/1.3 'Raleway', sans-serif;
+	color: #5e5b64;
+	padding-bottom:120px;
+	text-align: center;
+}
+
+a, a:visited {
+	outline:none;
+	color:#389dc1;
+}
+
+a:hover{
+	text-decoration:none;
+}
+
+section, footer, header, aside{
+	display: block;
+}
+
+
+/*-------------------------
+	The main page elements
+--------------------------*/
+
+
+h1{
+	font-size: 36px;
+	color: #5e5b64;
+	text-align: center;
+	padding-top: 100px;
+	padding-bottom:40px;
+	position: relative;
+}
+
+div.control-area{
+	font: bold 14px 'Raleway',sans-serif;
+	margin: 40px auto 0;
+	background-color: #f3f3f3;
+	padding: 20px;
+	border-radius: 5px;
+	width: 400px;
+	color:#888;
+}
+
+div.control-area a{
+	display: inline-block;
+	cursor: pointer;
+	margin: 7px auto;
+	background-color: #fdfdfd;
+	border-radius: 2px;
+	padding: 8px 10px;
+	font-size: 13px;
+	text-transform: uppercase;
+}
+
+div.control-area a:hover{
+	background-color: #fff;
+	box-shadow:0 1px 1px #dfdfdf;
+}
+
+
+/*-------------------------
+	The buttons
+--------------------------*/
+
+
+.progress-button{
+	display: inline-block;
+	font-size:24px;
+	color:#fff !important;
+	text-decoration: none !important;
+	padding:14px 60px;
+	line-height:1;
+	overflow: hidden;
+	position:relative;
+
+	box-shadow:0 1px 1px #ccc;
+	border-radius:2px;
+
+	background-color: #51b7e6;
+	background-image:-webkit-linear-gradient(top, #51b7e6, #4dafdd);
+	background-image:-moz-linear-gradient(top, #51b7e6, #4dafdd);
+	background-image:linear-gradient(top, #51b7e6, #4dafdd);
+}
+
+/*	Hide the original text of the button. Then the loading or finished
+	text will be shown in the :after element above it. */
+
+.progress-button.in-progress,
+.progress-button.finished{
+	color:transparent !important;
+}
+
+.progress-button.in-progress:after,
+.progress-button.finished:after{
+	position: absolute;
+	z-index: 2;
+	width: 100%;
+	height: 100%;
+	text-align: center;
+	top: 0;
+	padding-top: inherit;
+	color: #fff !important;
+	left: 0;
+}
+
+/*	If the .in-progress class is set on the button, show the
+	contents of the data-loading attribute on the butotn */
+
+.progress-button.in-progress:after{
+	content:attr(data-loading);
+}
+
+/* The same goes for the .finished class */
+
+.progress-button.finished:after{
+	content:attr(data-finished);
+}
+
+/* The colorful bar that grows depending on the progress */
+
+.progress-button .tz-bar{
+	background-color:#e667c0;
+	height:3px;
+	bottom:0;
+	left:0;
+	width:0;
+	position:absolute;
+	z-index:1;
+
+	border-radius:0 0 2px 2px;
+
+	-webkit-transition: width 0.5s, height 0.5s;
+	-moz-transition: width 0.5s, height 0.5s;
+	transition: width 0.5s, height 0.5s;
+}
+
+/* The bar can be either horizontal, or vertical */
+
+.progress-button .tz-bar.background-horizontal{
+	height:100%;
+	border-radius:2px;
+}
+
+.progress-button .tz-bar.background-vertical{
+	height:0;
+	top:0;
+	width:100%;
+	border-radius:2px;
+}
+
+
+/*----------------------------
+	Color themes
+-----------------------------*/
+
+
+.progress-button.red{
+	background-color: #e6537d;
+	background-image:-webkit-linear-gradient(top, #e6537d, #df5179);
+	background-image:-moz-linear-gradient(top, #e6537d, #df5179);
+	background-image:linear-gradient(top, #e6537d, #df5179);
+}
+
+.progress-button.red .tz-bar{
+	background-color:#6876b4;
+}
+
+
+.progress-button.green{
+	background-color: #64c896;
+	background-image:-webkit-linear-gradient(top, #64c896, #5fbd8e);
+	background-image:-moz-linear-gradient(top, #64c896, #5fbd8e);
+	background-image:linear-gradient(top, #64c896, #5fbd8e);
+}
+
+.progress-button.green .tz-bar{
+	background-color:#9e81d6;
+}
+
+
+/*----------------------------
+	The Demo Footer
+-----------------------------*/
+
+
+footer{
+
+	width: 770px;
+	font: normal 16px Arial, Helvetica, sans-serif;
+	padding: 15px 35px;
+	position: fixed;
+	bottom: 0;
+	left: 50%;
+	margin-left: -420px;
+
+	background-color:#1f1f1f;
+
+	background-image:-webkit-linear-gradient(top, #1f1f1f, #101010);
+	background-image:-moz-linear-gradient(top, #1f1f1f, #101010);
+	background-image:linear-gradient(top, #1f1f1f, #101010);
+
+	border-radius:2px 2px 0 0;
+
+	box-shadow: 0 -1px 4px rgba(0,0,0,0.4);
+	z-index:1;
+}
+
+footer a.tz{
+	font-weight:normal;
+	font-size:16px !important;
+	text-decoration:none !important;
+	display:block;
+	margin-right: 300px;
+	text-overflow:ellipsis;
+	white-space: nowrap;
+	color:#bfbfbf !important;
+	z-index:1;
+}
+
+footer a.tz:before{
+	content: '';
+	background: url('http://cdn.tutorialzine.com/misc/enhance/v2_footer_bg.png') no-repeat 0 -53px;
+	width: 138px;
+	height: 20px;
+	display: inline-block;
+	position: relative;
+	bottom: -3px;
+}
+
+footer .close{
+	position: absolute;
+	cursor: pointer;
+	width: 8px;
+	height: 8px;
+	background: url('http://cdn.tutorialzine.com/misc/enhance/v2_footer_bg.png') no-repeat 0 0px;
+	top:10px;
+	right:10px;
+	z-index: 3;
+}
+
+footer #tzine-actions{
+	position: absolute;
+	top: 8px;
+	width: 500px;
+	right: 50%;
+	margin-right: -650px;
+	text-align: right;
+	z-index: 2;
+}
+
+footer #tzine-actions iframe{
+	display: inline-block;
+	height: 21px;
+	width: 95px;
+	position: relative;
+	float: left;
+	margin-top: 11px;
+}
diff --git a/scr/staticresources/StageProgressBarCss.resource-meta.xml b/scr/staticresources/StageProgressBarCss.resource-meta.xml
new file mode 100644
index 0000000..e892e80
--- /dev/null
+++ b/scr/staticresources/StageProgressBarCss.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/css</contentType>
+</StaticResource>
diff --git a/scr/staticresources/TrialPortalBanner.png b/scr/staticresources/TrialPortalBanner.png
new file mode 100644
index 0000000..efbcf96
--- /dev/null
+++ b/scr/staticresources/TrialPortalBanner.png
Binary files differ
diff --git a/scr/staticresources/TrialPortalBanner.resource-meta.xml b/scr/staticresources/TrialPortalBanner.resource-meta.xml
new file mode 100644
index 0000000..f7d6923
--- /dev/null
+++ b/scr/staticresources/TrialPortalBanner.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>image/png</contentType>
+</StaticResource>
diff --git a/scr/staticresources/apex20.js b/scr/staticresources/apex20.js
new file mode 100644
index 0000000..8c2f9ef
--- /dev/null
+++ b/scr/staticresources/apex20.js
@@ -0,0 +1,70 @@
+if (!sforce) {
+    throw "unable to find sforce. Make sure that connection.js is loaded before apex.js script";
+}
+
+sforce.Apex = function(){
+};
+
+
+sforce.RunTestsRequest = function() {
+};
+
+sforce.RunTestsRequest.prototype = new sforce.Xml("RunTestsRequest");
+
+sforce.Apex.prototype.namespaceMap = [{ns:"http://soap.sforce.com/2006/08/apex", prefix:""}];
+
+sforce.Apex.prototype.executeAnonymous = function (string, callback) {
+    var arg1 = new sforce.internal.Parameter("String", string, false);
+
+    return sforce.connection._invoke("executeAnonymous",[arg1], false,
+            callback, this.namespaceMap, (typeof UserContext.siteUrlPrefix != "undefined") ? UserContext.getUrl("/services/Soap/s/51.0") : "/services/Soap/s/51.0", this.namespaceMap[0].ns);
+};
+
+sforce.Apex.prototype.setDebug = function (flag, level, categories) {
+    if (flag) {
+        sforce.debug.apexTrace = true;
+        sforce.connection.debuggingHeader = {debugLevel : (level ? level : "Db"), debugCategories : (categories ? categories : null)};
+    } else {
+        sforce.debug.apexTrace = false;
+        sforce.connection.debuggingHeader = null;
+    }
+};
+
+sforce.Apex.prototype.execute = function (pkg, method, args, callback, isArray) {
+    pkg = pkg.replace(/\./g, "/");
+
+    var sobjectNs = "http://soap.sforce.com/schemas/package/" + pkg;
+    var nsmap = [{ns:sobjectNs, prefix:""}];
+
+    if (!args) {
+        throw "args not specified";
+    }
+
+    var params = [];
+    for (var field in args) {
+        var value = args[field];
+        if (typeof value != "function") {
+            var arrayParam = value === null ? false : (value.push?true:false);
+            var param = new sforce.internal.Parameter(field, value, arrayParam);
+            params.push(param);
+        }
+    }
+
+    var isRealArray = true;
+
+    if (isArray === false) {
+        isRealArray = false;
+    }
+
+    return sforce.connection._invoke(method, params, isRealArray, callback, nsmap,
+            ((typeof window.UserContext != "undefined") ? UserContext.getUrl("/services/Soap/package/") : "/services/Soap/package/") + pkg, sobjectNs, sobjectNs);
+};
+
+sforce.Apex.prototype.runTests = function (request, callback) {
+    var arg1 = new sforce.internal.Parameter("RunTestsRequest", request, false);
+
+    return sforce.connection._invoke("runTests",[arg1], false,
+            callback, this.namespaceMap, (typeof window.UserContext != "undefined") ? UserContext.getUrl("/services/Soap/s/51.0") : "/services/Soap/s/51.0", this.namespaceMap[0].ns);
+};
+
+sforce.apex = new sforce.Apex();
\ No newline at end of file
diff --git a/scr/staticresources/apex20.resource-meta.xml b/scr/staticresources/apex20.resource-meta.xml
new file mode 100644
index 0000000..6adb110
--- /dev/null
+++ b/scr/staticresources/apex20.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/blockUIcss.css b/scr/staticresources/blockUIcss.css
new file mode 100644
index 0000000..5f6c572
--- /dev/null
+++ b/scr/staticresources/blockUIcss.css
@@ -0,0 +1,29 @@
+#sbArea{
+	position:absolute;
+	left:0px;
+	top:0px;
+	z-index:101;
+}
+
+#sbArea_contentsArea{
+	position:absolute;
+	z-index:103;
+	overflow:auto;
+}
+
+#sbArea_contentsArea_msg{
+	color:#FFFFFF;
+	background-color:#070707;
+	text-align:center;
+	width:200px;
+	padding:8px;
+}
+
+
+#sbArea_backArea{
+	position:absolute;
+	left:0px;
+	top:0px;
+	z-index:100;
+	background-color:#000000;
+}
\ No newline at end of file
diff --git a/scr/staticresources/blockUIcss.resource-meta.xml b/scr/staticresources/blockUIcss.resource-meta.xml
new file mode 100644
index 0000000..e892e80
--- /dev/null
+++ b/scr/staticresources/blockUIcss.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/css</contentType>
+</StaticResource>
diff --git a/scr/staticresources/connection20.js b/scr/staticresources/connection20.js
new file mode 100644
index 0000000..1717252
--- /dev/null
+++ b/scr/staticresources/connection20.js
@@ -0,0 +1,1935 @@
+/*
+Salesforce.com AJAX Connector 51.0
+Copyright, 1999, salesforce.com, inc.
+All Rights Reserved
+*/
+/** check if sforce is already created by some other lib*/
+window.sforce = window.sforce || {};
+
+sforce.internal = {};
+/** StringBuffer */
+
+sforce.StringBuffer = function() {
+    this.buffer = [];
+
+    this.append = function (s) {
+        this.buffer.push(s);
+        return this;
+    };
+
+    this.toString = function() {
+        return this.buffer.join("");
+    };
+};
+
+/** Base64Binary */
+sforce.Base64Binary = function(text) {
+    this.input = text;
+};
+
+sforce.Base64Binary.prototype.keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+
+sforce.Base64Binary.prototype.toString = function() {
+    var output = [];
+    var chr1, chr2, chr3 = "";
+    var enc1, enc2, enc3, enc4 = "";
+    var i = 0;
+    do {
+        chr1 = this.input.charCodeAt(i++);
+        chr2 = this.input.charCodeAt(i++);
+        chr3 = this.input.charCodeAt(i++);
+        enc1 = chr1 >> 2;
+        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+        enc4 = chr3 & 63;
+        if (isNaN(chr2)) {
+            enc3 = enc4 = 64;
+        } else if (isNaN(chr3)) {
+            enc4 = 64;
+        }
+        output.push(this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4));
+        chr1 = chr2 = chr3 = "";
+        enc1 = enc2 = enc3 = enc4 = "";
+    } while (i < this.input.length);
+    return output.join("");
+};
+
+sforce.Base64Binary.prototype.decode = function(input) {
+    var output = [];
+    var chr1, chr2, chr3 = "";
+    var enc1, enc2, enc3, enc4 = "";
+    var i = 0;
+    var base64test = /[^A-Za-z0-9\+\/\=]/g;
+    if (base64test.exec(input)) {
+        alert("There were invalid base64 characters in the input text.\n" +
+              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='\n" + "Expect errors in decoding.");
+    }
+    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
+    do {
+        enc1 = this.keyStr.indexOf(input.charAt(i++));
+        enc2 = this.keyStr.indexOf(input.charAt(i++));
+        enc3 = this.keyStr.indexOf(input.charAt(i++));
+        enc4 = this.keyStr.indexOf(input.charAt(i++));
+        chr1 = (enc1 << 2) | (enc2 >> 4);
+        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+        chr3 = ((enc3 & 3) << 6) | enc4;
+        output.push(String.fromCharCode(chr1));
+        if (enc3 != 64) {
+            output.push(String.fromCharCode(chr2));
+        }
+        if (enc4 != 64) {
+            output.push(String.fromCharCode(chr3));
+        }
+        chr1 = chr2 = chr3 = "";
+        enc1 = enc2 = enc3 = enc4 = "";
+    } while (i < input.length);
+    return output.join("");
+};
+
+/**DateCodec.js*/
+
+sforce.internal.dateToString = function(theDate) {
+    var today = theDate;
+    var year = today.getFullYear();
+    var month = today.getMonth() + 1;
+    var day = today.getDate();
+    return  year + "-" + month + "-" + day;
+};
+
+sforce.internal.dateTimeToString = function(theDate) {
+    var today = theDate;
+    var year = today.getFullYear();
+    var month = today.getMonth() + 1;
+    var day = today.getDate();
+    var hour = today.getHours();
+    var minute = today.getMinutes();
+    var second = today.getSeconds();
+
+    var offset = today.getTimezoneOffset();
+    var pm = (offset < 0) ? "+" : "-";
+    offset = Math.abs(offset);
+    var hourdifference = offset / 60;
+    var minutedifference = offset % 60;
+
+    if (second <= 9) {
+        second = "0" + second;
+    }
+
+    var milli = today.getMilliseconds();
+    if (milli !== 0) {
+        milli = "." + milli;
+        if (milli.length > 4) {
+            milli = milli.substring(0, 4);
+        }
+        second = second + milli;
+    }
+
+    var timezone;
+
+    if (offset === 0) {
+        timezone = "Z";
+    } else {
+        if (minutedifference < 10) {
+            minutedifference = "0" + minutedifference;
+        }
+        if (hourdifference < 10) {
+            hourdifference = "0" + hourdifference;
+        }
+        timezone = pm + hourdifference + ":" + minutedifference;
+    }
+
+    if (month <= 9) {
+        month = "0" + month;
+    }
+    if (day <= 9) {
+        day = "0" + day;
+    }
+    if (hour <= 9) {
+        hour = "0" + hour;
+    }
+    if (minute <= 9) {
+        minute = "0" + minute;
+    }
+
+    return  year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second + timezone;
+};
+
+
+sforce.internal.stringToDate = function(source) {
+    var bc = false;
+    if (source === null || source.length === 0) {
+        throw "Unable to parse dateTime";
+    }
+
+    if (source.charAt(0) == '+') {
+        source = source.substring(1);
+    }
+
+    if (source.charAt(0) == '-') {
+        source = source.substring(1);
+        bc = true;
+    }
+
+    if (source.length != 10) {
+        throw ("Unable to parse date, " + source + " length != 10");
+    }
+
+    if (source.charAt(4) != '-' || source.charAt(7) != '-') {
+        throw ("Unable to parse date");
+    }
+
+    var year = source.substring(0, 4);
+    var month = source.substring(5, 7);
+    var day = source.substring(8, 10);
+
+    var date = new Date(year, month-1, day, 0, 0, 0);
+    date.setMilliseconds(0);
+    return date;
+};
+
+
+sforce.internal.stringToDateTime = function(source) {
+    var bc = false;
+    if (source === null || source.length === 0) {
+        throw "Unable to parse dateTime";
+    }
+
+    if (source.charAt(0) == '+') {
+        source = source.substring(1);
+    }
+    if (source.charAt(0) == '-') {
+        source = source.substring(1);
+        bc = true;
+    }
+
+    if (source.length < 19) {
+        throw ("Unable to parse dateTime");
+    }
+
+    if (source.charAt(4) != '-' || source.charAt(7) != '-' ||
+        source.charAt(10) != 'T') {
+        throw ("Unable to parse dateTime");
+    }
+
+    if (source.charAt(13) != ':' || source.charAt(16) != ':') {
+        throw ("Unable to parse dateTime");
+    }
+
+    var year = source.substring(0, 4);
+    var month = source.substring(5, 7);
+    var day = source.substring(8, 10);
+    var hour = source.substring(11, 13);
+    var min = source.substring(14, 16);
+    var sec = source.substring(17, 19);
+
+    var date = new Date(year, month-1, day, hour, min, sec);
+
+    var pos = 19;
+
+    // parse optional milliseconds
+    if (pos < source.length && source.charAt(pos) == '.') {
+        var milliseconds = 0;
+        var start = ++pos;
+        while (pos < source.length && sforce.internal.isDigit(source.charAt(pos))) {
+            pos++;
+        }
+        var decimal = source.substring(start, pos);
+        if (decimal.length == 3) {
+            milliseconds = decimal;
+        } else if (decimal.length < 3) {
+            milliseconds = (decimal + "000").substring(0, 3);
+        } else {
+            milliseconds = decimal.substring(0, 3);
+            if (decimal.charAt(3) >= '5') {
+                ++milliseconds;
+            }
+        }
+
+        date.setMilliseconds(milliseconds);
+    }
+
+    var offset = date.getTimezoneOffset() * 60000;
+    //offset in milli;
+
+    // parse optional timezone
+    if (pos + 5 < source.length &&
+        (source.charAt(pos) == '+' || (source.charAt(pos) == '-'))) {
+        if (!sforce.internal.isDigit(source.charAt(pos + 1)) ||
+            !sforce.internal.isDigit(source.charAt(pos + 2)) ||
+            source.charAt(pos + 3) != ':' ||
+            !sforce.internal.isDigit(source.charAt(pos + 4)) ||
+            !sforce.internal.isDigit(source.charAt(pos + 5))) {
+            throw "Unable to parse dateTime";
+        }
+        var hours = (source.charAt(pos + 1) - '0') * 10 + source.charAt(pos + 2) - '0';
+        var mins = (source.charAt(pos + 4) - '0') * 10 + source.charAt(pos + 5) - '0';
+        var mseconds = (hours * 60 + mins) * 60 * 1000;
+
+        // subtract milliseconds from current date to obtain GMT
+        if (source.charAt(pos) == '+') {
+            mseconds = -mseconds;
+        }
+
+        date = new Date(date.getTime() - offset + mseconds);
+        pos += 6;
+    }
+
+    if (pos < source.length && source.charAt(pos) == 'Z') {
+        pos++;
+        date = new Date(date.getTime() - offset);
+    }
+
+    if (pos < source.length) {
+        throw ("Unable to parse dateTime");
+    }
+
+    return date;
+};
+
+
+sforce.internal.isDigit = function (ch) {
+    if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' ||
+        ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9') {
+        return true;
+    } else {
+        return false;
+    }
+};
+/** Xml */
+
+sforce.Xml = function(name) {
+};
+
+sforce.Xml.prototype.toXml = function (sobjectNs, name, writer) {
+    writer.writeStartElement(name, sobjectNs);
+    if (this._xsiType) {
+        writer.writeXsiType(this._xsiType);
+    }
+    for (var f in this) {
+        if ("_name" == f || "_xsiType" == f) {
+            //skip
+        } else {
+            var val = this[f];
+            if (typeof val != "function") {
+                // if (typeof val == "array") {
+                if (Array.isArray(val)) {
+                    for (var i=0; i<val.length; i++) {
+                        this.writeValue(sobjectNs, writer, f, val[i]);
+                    }
+                } else {
+                    this.writeValue(sobjectNs, writer, f, val);
+                }
+            }
+        }
+    }
+    writer.writeEndElement(name, sobjectNs);
+};
+
+
+sforce.Xml.prototype.writeValue = function (sobjectNs, writer, name, val) {
+    if (val === null) {
+        writer.writeNameValueNode("fieldsToNull", name);
+        return;
+    }
+    if (typeof(val) === "undefined") {
+        //TODO:  throw "value for field " + name + " is undefined"; Bug: 100000000000Ufg
+        return; //skip for now
+    }
+    if (val.toXml) {
+        val.toXml(sobjectNs, name, writer);
+    } else {
+        writer.writeNameValueNode(name, val);
+    }
+};
+
+sforce.Xml.prototype.get = function(name) {
+    return this[name] ? this[name] : null;
+};
+
+sforce.Xml.prototype.set = function(name, value) {
+    this[name] = value;
+};
+
+sforce.Xml.prototype.getArray = function(name) {
+    var obj = this[name];
+    if (obj) {
+        if (obj.join) {
+            return obj;
+        } else {
+            return [obj];
+        }
+    } else {
+        return [];
+    }
+};
+
+sforce.Xml.prototype.getBoolean = function(name) {
+    return ("true" == this[name]) ? true : false;
+};
+
+sforce.Xml.prototype.getDate = function(name) {
+    if (this[name]) {
+        if (this[name].getFullYear) {
+            return this[name];
+        } else {
+            return sforce.internal.stringToDate(this[name]);
+        }
+    } else {
+        return null;
+    }
+};
+
+sforce.Xml.prototype.getDateTime = function(name) {
+    if (this[name]) {
+        if (this[name].getFullYear) {
+            return this[name];
+        } else {
+            return sforce.internal.stringToDateTime(this[name]);
+        }
+    } else {
+        return null;
+    }
+};
+
+sforce.Xml.prototype.getInt = function(name) {
+    if (this[name]) {
+        if (typeof this[name] === "number") {
+            return this[name];
+        } else {
+            return parseInt(this[name], 10);
+        }
+    } else {
+        throw "Unable to parse int field: " + name;
+    }
+};
+
+sforce.Xml.prototype.getFloat = function(name) {
+    if (this[name]) {
+        if (typeof this[name] === "number") {
+            return this[name];
+        } else {
+            return parseFloat(this[name]);
+        }
+    } else {
+        throw "Unable to parse float field: " + name;
+    }
+};
+
+sforce.Xml.prototype.getBase64Binary = function(name) {
+    if (this[name]) {
+        return sforce.Base64Binary.prototype.decode(this[name]);
+    } else {
+        throw "Unable to parse base64Binary field: " + name;
+    }
+};
+
+sforce.Xml.prototype.toString = function() {
+    var sb = new sforce.StringBuffer();
+    sb.append("{");
+
+    for (var f in this) {
+        var field = this[f];
+
+        if (!field) {
+            sb.append(f).append(":").append("" + field);
+        } else  if (typeof(field) == "object") {
+            sb.append(f).append(":").append(field.toString());
+        } else if (field.join) {
+            sb.append(f).append(":").append("[");
+            for (var i = 0; i < field.length; i++) {
+                sb.append(field[i]);
+                if (i < field.length - 1) {
+                    sb.append(", ");
+                }
+            }
+            sb.append("]");
+        } else if (typeof(field) == "function") {
+            continue;
+        } else {
+            sb.append(f).append(":").append("'" + field + "'");
+        }
+        sb.append(", ");
+    }
+
+    sb.append("}");
+    return sb.toString();
+};
+
+
+/** Debug */
+
+
+sforce.internal.Debug = function() {
+    this.output = null;
+    this.trace = false;
+    this.apexTrace = false;
+    this.win = null;
+    this.traceQueue = [];
+    this.quiet = false;
+
+    this.open = function() {
+        this.println("", "print");
+    };
+
+    this.println = function(s, type) {
+        if (this.quiet) {
+            return;
+        }
+
+        if (typeof(println) === "function") {
+            println(s, type);
+            return;
+        }
+
+        if (this.win === null || !this.win.document) {
+            this.output = null;
+            this.win = window.open((typeof window.UserContext != "undefined") ? UserContext.getUrl('/soap/ajax/51.0/debugshell.html') : '/soap/ajax/51.0/debugshell.html', '',
+                    'width=800,height=400,toolbar=no,location=no,directories=no,alwaysRaised=yes,' +
+                    'status=no,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes');
+        }
+
+        if (this.output === null) {
+            this.findOutput();
+        }
+
+        if (this.output !== null) {
+            if (sforce.debug.traceQueue.length > 0) {
+                this.traceCallback();
+            }
+            this.win.println(s, type);
+       } else {
+            sforce.debug.traceQueue.push({message: s, type: type});
+            setTimeout(sforce.debug.traceCallback, 1000);
+        }
+    };
+
+    this.traceCallback = function() {
+        sforce.debug.findOutput();
+
+        if (sforce.debug.output === null) {
+            setTimeout(sforce.debug.traceCallback, 1000);
+            return;
+        }
+
+        for (var i=0; i<sforce.debug.traceQueue.length; i++) {
+            var element = sforce.debug.traceQueue[i];
+            sforce.debug.win.println(element.message, element.type);
+        }
+        sforce.debug.traceQueue = [];
+    };
+
+    this.findOutput = function() {
+        if (this.output === null) {
+            this.output = this.win.document.getElementById("output");
+        }
+        return this.output;
+    };
+
+    this.logXml = function(str) {
+        str = str.replace(/</g, "&lt;");
+        str = str.replace(/>/g, "&gt;");
+        str = "<textarea cols=80 rows=5 wrap=hard>" + str + "</textarea>";
+        this.println(str, "printxml");
+    };
+
+    this.log = function(str) {
+        this.println(str, "print");
+    };
+
+    this.logApex = function(response) {
+        var start = response.indexOf("<debugLog>");
+        var end = response.indexOf("</debugLog>");
+        if (start === -1)
+            start = 0;
+        else
+            start = start + '<debugLog>'.length;
+        if (end === -1) end = response.length;
+        var msg = response.substring(start, end);
+
+        this.println(msg, "printxml");
+    };
+};
+
+sforce.debug = new sforce.internal.Debug();
+
+/** Transport */
+
+sforce.internal._connections = [];
+
+sforce.internal.ConnectionHolder = function(connection, callback) {
+    this.connection = connection;
+    this.callback = callback;
+    this.timedout = false;
+};
+
+sforce.Transport = function(url) {
+    this.url = url;
+    this.connection = null;
+
+    this.newConnection = function() {
+        try {
+            this.connection = new ActiveXObject('Msxml2.XMLHTTP');
+        } catch(e) {
+            try {
+                this.connection = new ActiveXObject('Microsoft.XMLHTTP');
+            } catch(e) {
+                this.connection = new XMLHttpRequest();
+            }
+        }
+
+        return this.connection;
+    };
+
+    this.send = function (envelope, callback, async, timeout) {
+        this.newConnection();
+        if (async) {
+            this.connection.onreadystatechange = this.httpConnectionCallback;
+        }
+        var holder = new sforce.internal.ConnectionHolder(this.connection, callback);
+        sforce.internal._connections.push(holder);
+        this.connection.open("POST", this.url, async);
+        this.connection.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
+        this.connection.setRequestHeader("SOAPAction", "\"\"");
+        this.connection.setRequestHeader("Accept", "text/xml");
+        this.connection.setRequestHeader("X-SFDC-User-Agent", "SFAJAX 1.0");
+        this.connection.send(envelope);
+        if (async && typeof(timeout) !== "undefined") {
+            this.setTimeoutOn(holder, timeout);
+        }
+        if (!async) {
+            this.httpConnectionCallback();
+        }
+    };
+
+    this.setTimeoutOn = function (holder, timeout) {
+        function abortConnection() {
+            if (holder.connection.readyState !== 4) {
+                holder.timedout = true;
+                holder.connection.abort();
+            }
+        }
+        setTimeout(abortConnection, timeout);
+    };
+
+    this.httpConnectionCallback = function () {
+
+        for (var i = 0; i < sforce.internal._connections.length; i++) {
+            var holder = sforce.internal._connections[i];
+            if (holder !== null) {
+                if (holder.timedout) {
+                    sforce.internal._connections[i] = null;
+                    sforce.internal._connections.slice(i,1);
+                    holder.callback.httpCallback("Remote invocation timed out", false);
+                } else  if (holder.connection.readyState == 4) {
+                    sforce.internal._connections[i] = null;
+                    sforce.internal._connections.slice(i,1);
+                    var success = holder.connection.status == 200;
+                    if (sforce.debug.trace) {
+                        sforce.debug.log("Response : status - " + holder.connection.status);
+                        sforce.debug.logXml(holder.connection.responseText);
+                    }
+                    if (sforce.debug.apexTrace) {
+                        sforce.debug.logApex(holder.connection.responseText);
+                    }
+                    if (holder.connection.responseXML && holder.connection.responseXML.documentElement) {
+                        holder.callback.httpCallback(holder.connection.responseXML.documentElement, success);
+                    } else {
+                        holder.callback.httpCallback("Remote invocation failed, due to: " + holder.connection.responseText +
+                                                     " status code: ", holder.connection.status);
+                    }
+                }
+            }
+        }
+    };
+};
+/** XmlWriter */
+
+
+sforce.XmlWriter = function() {
+    this.buffer = new sforce.StringBuffer();
+    this.namespaces = {};
+    this.prefixCount = 0;
+    this.writingStartElement = false;
+};
+
+sforce.XmlWriter.prototype.writeStartElement = function(name, namesp, prefix) {
+    if (this.writingStartElement) {
+        this.buffer.append(">");
+    }
+    this.buffer.append("<");
+    var newns = false;
+    if (namesp) {
+        if (!this.namespaces[namesp] && this.namespaces[namesp] !== "") {
+            newns = true;
+        }
+        if (!prefix) {
+            prefix = this.getPrefix(namesp);
+        }
+        if (prefix !== null && prefix !== "") {
+           this.buffer.append(prefix);
+           this.buffer.append(":");
+        }
+    }
+
+    this.buffer.append(name);
+    if (newns === true) {
+        this.writeNamespace(namesp, prefix);
+    }
+    this.writingStartElement = true;
+};
+
+sforce.XmlWriter.prototype.writeEndElement = function(name, namesp) {
+    if (this.writingStartElement) {
+        this.buffer.append("/>");
+    } else {
+        this.buffer.append("</");
+        if (namesp) {
+            var prefix = this.getPrefix(namesp);
+            if (prefix && prefix !== "") {
+              this.buffer.append(prefix);
+              this.buffer.append(":");
+            }
+        }
+        this.buffer.append(name);
+        this.buffer.append(">");
+    }
+    this.writingStartElement = false;
+};
+
+sforce.XmlWriter.prototype.writeNamespace = function(namesp, prefix) {
+    if (prefix && "" !== prefix) {
+        this.namespaces[namesp] = prefix;
+        this.buffer.append(" ");
+        this.buffer.append("xmlns:");
+        this.buffer.append(prefix);
+    } else {
+        this.namespaces[namesp] = "";
+        this.buffer.append(" ");
+        this.buffer.append("xmlns");
+    }
+    this.buffer.append("=\"");
+    this.buffer.append(namesp);
+    this.buffer.append("\"");
+};
+
+sforce.XmlWriter.prototype.writeText = function(text) {
+    if (this.writingStartElement) {
+        this.buffer.append(">");
+        this.writingStartElement = false;
+    } else {
+        throw "Can only write text after a start element";
+    }
+    if (typeof text == 'string') {
+        text = text.replace(/&/g, '\&amp;');
+        text = text.replace(/</g, '&lt;');
+        text = text.replace(/>/g, '&gt;');
+    }
+
+    this.buffer.append(text);
+};
+
+sforce.XmlWriter.prototype.writeXsiType = function(xsiType) {
+    this.writeNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
+    this.writeAttribute("xsi:type", xsiType);
+};
+
+sforce.XmlWriter.prototype.writeAttribute = function(name, value) {
+    this.buffer.append(" " + name + "=\"" + value + "\"");
+};
+
+sforce.XmlWriter.prototype.getPrefix = function(namesp) {
+    var prefix = this.namespaces[namesp];
+    //sforce.debug.log("--------");
+    //sforce.debug.log(namesp + ":" + (prefix === null ? "null":prefix) + ":");
+    if (!prefix && prefix !== "") {
+        prefix = "ns" + this.prefixCount;
+        this.prefixCount++;
+        this.namespaces[namesp] = prefix;
+        return prefix;
+    }
+    return prefix;
+};
+
+sforce.XmlWriter.prototype.toString = function() {
+    return this.buffer.toString();
+};
+
+/** soap writer*/
+sforce.XmlWriter.prototype.soapNS = "http://schemas.xmlsoap.org/soap/envelope/";
+
+sforce.XmlWriter.prototype.startEnvelope = function() {
+    this.writeStartElement("Envelope", this.soapNS, "se");
+};
+
+sforce.XmlWriter.prototype.endEnvelope = function() {
+    this.writeEndElement("Envelope", this.soapNS);
+};
+
+sforce.XmlWriter.prototype.startHeader = function() {
+    this.writeStartElement("Header", this.soapNS, "se");
+};
+
+sforce.XmlWriter.prototype.endHeader = function() {
+    this.writeEndElement("Header", this.soapNS);
+};
+
+sforce.XmlWriter.prototype.startBody = function() {
+    this.writeStartElement("Body", this.soapNS, "se");
+};
+
+sforce.XmlWriter.prototype.endBody = function() {
+    this.writeEndElement("Body", this.soapNS);
+};
+
+sforce.XmlWriter.prototype.writeNameValueNode = function(name, value) {
+    if (value === null) {
+        this.writeStartElement(name);
+        this.writeNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
+        this.writeAttribute("xsi:nill", "true");
+        this.writeEndElement(name);
+        return;
+    }
+
+    if (value.toUTCString) {
+        value = sforce.internal.dateTimeToString(value);
+    }
+    if (typeof value == "boolean") {
+        // boolean 'false' values get joined in string buffer,
+        // so convert to strings:
+        value = value ? "true" : "false";
+    }
+
+    if (value && value.join) {
+        for (var i=0; i<value.length; i++) {
+            this.writeStartElement(name);
+            this.writeText(value[i]);
+            this.writeEndElement(name);
+        }
+    } else {
+        this.writeStartElement(name);
+        this.writeText(value);
+        this.writeEndElement(name);
+    }
+};
+
+/** XmlReader */
+
+sforce.XmlReader = function(root) {
+    this.envelope = root;
+};
+
+sforce.XmlReader.prototype.getEnvelope = function() {
+    if (this.isTag("Envelope", this.envelope)) {
+        return this.envelope;
+    }
+    throw "Unable to find soap envelope, but found " + this.envelope.nodeName;
+};
+
+sforce.XmlReader.prototype.getBody = function() {
+    return this.getChild("Body", this.envelope);
+};
+
+sforce.XmlReader.prototype.getHeader = function() {
+    return this.getChild("Header", this.envelope);
+};
+
+sforce.XmlReader.prototype.getChild = function(name, node) {
+    var children = node.childNodes;
+    for (var i = 0; i < children.length; i++) {
+        if (children[i].nodeType == 1 && this.isTag(name, children[i])) {
+            return children[i];
+        }
+    }
+    return null;
+};
+
+sforce.XmlReader.prototype.getFirstElement = function(node) {
+    var children = node.childNodes;
+    for (var i = 0; i < children.length; i++) {
+        if (children[i].nodeType == 1) {
+            return children[i];
+        }
+    }
+    return null;
+};
+
+sforce.XmlReader.prototype.isTag = function(name, node) {
+    var ns = node.nodeName.split(":");
+    if (ns.length == 2 && ns[1] == name) {
+        return true;
+    }
+    if (ns.length == 1 && ns[0] == name) {
+        return true;
+    }
+    return false;
+};
+
+sforce.XmlReader.prototype.isNameValueNode = function(node) {
+    var children = node.childNodes;
+    for (var i = 0; i < children.length; i++) {
+        if (children[i].nodeType != 3) {
+            return false;
+        }
+    }
+
+    return true;
+};
+
+sforce.XmlReader.prototype.getTextValue = function(node) {
+    if (node.nodeType == 3) {
+        return node.nodeValue;
+    }
+    //todo: fix the hardcoded xsi prefix
+    var xsiNil = node.getAttribute("xsi:nil");
+    if (xsiNil == "true") {
+        return null;
+    }
+    var sb = "";
+    var children = node.childNodes;
+    for (var i = 0; i < children.length; i++) {
+        if (children[i].nodeType == 3) {
+            sb += children[i].nodeValue;
+        } else {
+            throw "Not a simple name value node";
+        }
+    }
+    return sb;
+};
+
+//todo: optimize
+/*
+sforce.XmlReader.prototype.toXmlObject2 = function(node) {
+    var children = node.childNodes;
+    var obj = new sforce.Xml();
+    for (var i = 0; i < children.length; i++) {
+        var child = children[i];
+        if (child.nodeType != 1) continue;
+        var name = child.nodeName;
+        var index = name.indexOf(":");
+        name = (index == -1) ? name : name.substring(index + 1);
+        var value;
+        if (this.isNameValueNode(child)) {
+            value = this.getTextValue(child);
+        } else {
+            value = this.toXmlObject(child);
+        }
+        this.addToObject(obj, name, value);
+    }
+    return obj;
+}
+*/
+
+
+sforce.XmlReader.prototype.toXmlObject = function(n) {
+    //todo: fix the hardcoded xsi prefix
+    var xsiNil = n.getAttribute("xsi:nil");
+    if (xsiNil == "true") {
+        return null;
+    }
+
+    var top = new sforce.Xml();
+    var stack = [];
+    stack.push({node: n, obj: top});
+
+    while (stack.length > 0) {
+        var st = stack.shift();
+
+        for (var child = st.node.firstChild; child !== null; child = child.nextSibling) {
+            if (child.nodeType != 1) {
+                continue;
+            }
+            var name = child.nodeName;
+            var index = name.indexOf(":");
+            name = (index == -1) ? name : name.substring(index + 1);
+            var value;
+
+            var isNameValue = true;
+            var sb = "";
+            for (var tc = child.firstChild; tc !== null; tc = tc.nextSibling) {
+                if (tc.nodeType != 3) {
+                    isNameValue = false;
+                    break;
+                } else {
+                    sb += tc.nodeValue;
+                }
+            }
+
+            if (isNameValue) {
+                if (child.getAttribute("xsi:nil") == "true") {
+                    value = null;
+                } else {
+                    value = sb;
+                }
+            } else {
+                value = new sforce.Xml();
+                stack.push({node: child, obj: value});
+            }
+            if (!st.obj[name]) {
+                st.obj[name] = value;
+            } else {
+                if (st.obj[name].push) {
+                    st.obj[name].push(value);
+                } else {
+                    var old = st.obj[name];
+                    if (name === "Id" && old === value) {
+                        //skip, special case for dup Id in sobject
+                    } else {
+                        st.obj[name] = [];
+                        st.obj[name].push(old);
+                        st.obj[name].push(value);
+                    }
+                }
+            }
+        }
+    }
+    return top;
+};
+
+
+/** SoapTransport */
+
+sforce.SoapTransport = function() {
+    this.connectionCallback = null;
+    this.result = null;
+    this.fault = null;
+    this.isAsync = true;
+    this.isArray = false;
+};
+
+sforce.SoapTransport.prototype.onFailure = function(res, writer) {
+    var error = "ERROR: ........... ";
+    alert(error + res);
+    this.result = null;
+};
+
+sforce.SoapTransport.prototype.send = function(url, writer, isArray, connectionCallback) {
+    this.isArray = isArray;
+    var transport = new sforce.Transport(url);
+    this.isAsync = connectionCallback ? true : false;
+    if (this.isAsync) {
+        this.connectionCallback = connectionCallback;
+        transport.send(writer.toString(), this, this.isAsync, connectionCallback.timeout);
+    } else {
+        transport.send(writer.toString(), this, this.isAsync);
+        if (this.fault !== null) {
+            throw this.fault;
+        }
+        return this.result;
+    }
+};
+
+sforce.SoapTransport.prototype.httpCallback = function(response, success) {
+    try {
+        if (success === true) {
+            var reader = new sforce.XmlReader(response);
+            var envelope = reader.getEnvelope();
+            var body = reader.getBody();
+            var operation = reader.getFirstElement(body);
+            if (operation === null) {
+                throw "Unable to find operation response element";
+            }
+            var resultArray = [];
+            var children = operation.childNodes;
+            for (var i = 0; i < children.length; i++) {
+                if (children[i].nodeType != 1) {
+                    continue;
+                }
+                if (reader.isNameValueNode(children[i])) {
+                    resultArray.push(reader.getTextValue(children[i]));
+                } else {
+                    resultArray.push(reader.toXmlObject(children[i]));
+                }
+            }
+
+            if (this.isArray) {
+                this.result = resultArray;
+            } else {
+                if (resultArray.length > 1) {
+                    throw "Found more than one response: " + resultArray;
+                }
+                this.result = resultArray[0];
+            }
+
+            if (this.isAsync) {
+                try {
+                    this.beforeCallback();
+                    if (typeof this.connectionCallback == "function") {
+                        this.connectionCallback(this.result);
+                    } else {
+                        if (this.connectionCallback.onSuccess) {
+                            this.connectionCallback.onSuccess(this.result, this.connectionCallback.source);
+                        } else {
+                            throw "Unable to find onSuccess method in the callback object";
+                        }
+                    }
+                } finally {
+                    this.afterCallback();
+                }
+            }
+        } else {
+            if (typeof(response.nodeName) !== "undefined") {
+                var reader2 = new sforce.XmlReader(response);
+                var envelope2 = reader2.getEnvelope();
+                var body2 = reader2.getBody();
+                var soapfaultEl = reader2.getFirstElement(body2);
+                var soapfault = reader2.toXmlObject(soapfaultEl);
+                this.sendFault(soapfault);
+            } else {
+                this.sendFault(response);
+            }
+        }
+    } catch(fault) {
+        this.sendFault(fault);
+    }
+};
+
+
+sforce.SoapTransport.prototype.sendFault = function(fault) {
+    if (this.isAsync) {
+        if (this.connectionCallback.onFailure) {
+            try {
+                this.beforeCallback();
+                this.connectionCallback.onFailure(fault, this.connectionCallback.source);
+            } finally {
+                this.afterCallback();
+            }
+        } else {
+            this.onFailure(fault);
+        }
+    } else {
+        this.fault = fault;
+    }
+};
+
+sforce.SoapTransport.prototype.beforeCallback = function () {};
+
+sforce.SoapTransport.prototype.afterCallback = function () {};
+
+/** SObject */
+
+
+sforce.SObject = function(type) {
+    this.type = type;
+};
+
+sforce.SObject.prototype = new sforce.Xml("sObjects");
+
+
+/** LeadConvert */
+
+
+sforce.LeadConvert = function() {
+};
+
+sforce.LeadConvert.prototype = new sforce.Xml("leadConverts");
+
+/** MergeRequest */
+
+
+sforce.MergeRequest = function() {
+};
+
+sforce.MergeRequest.prototype = new sforce.Xml("request");
+
+/** DescribeSoqlListViewsRequest - see describeSoqlListViews() */
+sforce.DescribeSoqlListViewsRequest  = function() {
+};
+sforce.DescribeSoqlListViewsRequest.prototype = new sforce.Xml("request");
+
+/** DescribeSoqlListViewParams - see describeSoqlListViews() */
+sforce.DescribeSoqlListViewParams = function() {
+};
+sforce.DescribeSoqlListViewParams.prototype = new sforce.Xml("listViewParams");
+
+/** DescribePicklistsParam - see describePicklists() */
+sforce.DescribePicklistsParam = function() {
+};
+sforce.DescribePicklistsParam.prototype = new sforce.Xml("picklistParams");
+
+
+/** QuickAction */
+
+
+sforce.QuickAction = function() {
+};
+
+sforce.QuickAction.prototype = new sforce.Xml("quickActions");
+
+/** Connection */
+
+sforce.Connection = function() {
+    this.sessionId = null;
+    this.updateMru = null;
+    this.allowFieldTruncation = null;
+    this.disableFeedTracking = null;
+    this.streamingEnabled = null;
+    this.allOrNone = null;
+    this.client = null;
+    this.defaultNamespace = null;
+    this.batchSize = null;
+    this.loginScopeHeader = null;
+    this.emailHeader = null;
+    this.assignmentRuleHeader = null;
+    this.duplicateRuleHeader = null;
+    this.transferToUserId = null;
+    this.debuggingHeader = null;
+    this.serverUrl = (typeof window.UserContext != "undefined") ? UserContext.getUrl("/services/Soap/u/51.0") : "/services/Soap/u/51.0";
+};
+
+
+/** internal methods */
+
+sforce.internal.Parameter = function (n, v, a) {
+    this.name = n;
+    this.value = v;
+    this.isArray = a;
+};
+
+sforce.Connection.prototype.sforceNs = "urn:partner.soap.sforce.com";
+sforce.Connection.prototype.sobjectNs = "sobject.partner.soap.sforce.com";
+
+sforce.Connection.prototype.writeOne = function (writer, name, value, sobjectNs) {
+    if (value === null) {
+        writer.writeNameValueNode(name, null);
+    } else if (value.toXml) {
+        value.toXml(sobjectNs, name, writer);
+    } else {
+        writer.writeNameValueNode(name, value);
+    }
+};
+
+sforce.Connection.prototype.init = function(sessionId, serverUrl) {
+    this.sessionId = sessionId;
+    this.serverUrl = serverUrl;
+};
+
+sforce.Connection.prototype.login = function (username, password) {
+    var arg1 = new sforce.internal.Parameter("username", username, false);
+    var arg2 = new sforce.internal.Parameter("password", password, false);
+    var result = this.invoke("login", [arg1, arg2], false, null);
+    this.sessionId = result.sessionId;
+    return result;
+};
+
+sforce.Connection.prototype.describeSObject = function(type, callback) {
+    var arg = new sforce.internal.Parameter("sObjectType", type, false);
+    return this.invoke("describeSObject", [arg], false, callback);
+};
+
+sforce.Connection.prototype.describeSObjects = function(types, callback) {
+    var arg = new sforce.internal.Parameter("sObjectType", types, true);
+    return this.invoke("describeSObjects", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeSearchLayouts = function(type, callback) {
+    var arg = new sforce.internal.Parameter("sObjectType", type, true);
+    return this.invoke("describeSearchLayouts", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeListViews = function(type, callback) {
+    var arg = new sforce.internal.Parameter("sObjectType", type, true);
+    return this.invoke("describeListViews", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeSoqlListViews = function(name, type, callback) {
+    // this interface is only for a single list 
+    // build up a request for the user - easier than making caller do it
+	var rp = new sforce.DescribeSoqlListViewParams();
+	rp.developerNameOrId = name;
+	rp.sobjectType = type;
+	var describeRequest = new sforce.DescribeSoqlListViewsRequest();
+	describeRequest.listViewParams = [ rp ];
+    
+    var arg1 = new sforce.internal.Parameter("request", describeRequest, false);
+    return this.invoke("describeSoqlListViews", [arg1], false, callback);
+};
+
+sforce.Connection.prototype.describeGlobal = function(callback) {
+    return this.invoke("describeGlobal", [], false, callback);
+};
+
+sforce.Connection.prototype.describeLayout = function(type, layoutName, recordTypes, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjectType", type, false);
+    if (!layoutName) {
+        layoutName = null;
+    }
+    var arg2 = new sforce.internal.Parameter("layoutName", layoutName, false);
+    if (!recordTypes) {
+        recordTypes = [];
+    }
+    var arg3 = new sforce.internal.Parameter("recordTypeIds", recordTypes, true);
+    return this.invoke("describeLayout", [arg1, arg2, arg3], false, callback);
+};
+
+sforce.Connection.prototype.describeAvailableQuickActions = function(parentType, callback) {
+    var arg = new sforce.internal.Parameter("parentType", parentType, false);
+    return this.invoke("describeAvailableQuickActions", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeQuickActions = function(quickActionNames, callback) {
+    var arg = new sforce.internal.Parameter("quickActionNames", quickActionNames, true);
+    return this.invoke("describeQuickActions", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeQuickActionsForRecordType = function(quickActionNames, recordTypeId, callback) {
+    var arg = new sforce.internal.Parameter("quickActionNames", quickActionNames, true);
+    var arg2 = new sforce.internal.Parameter("recordTypeId", recordTypeId, false);
+    return this.invoke("describeQuickActionsForRecordType", [arg,arg2], true, callback);
+};
+
+sforce.Connection.prototype.performQuickActions = function(quickActions, callback) {
+    var arg = new sforce.internal.Parameter("quickActions", quickActions, true);
+    return this.invoke("performQuickActions", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeCompactLayouts = function(type, recordTypes, callback) {
+    var arg = new sforce.internal.Parameter("sObjectType", type, false);
+    if (!recordTypes) {
+        recordTypes = [];
+    }
+    var arg2 = new sforce.internal.Parameter("recordTypeIds", recordTypes, true);
+    return this.invoke("describeCompactLayouts", [arg, arg2], false, callback);
+};
+
+sforce.Connection.prototype.describePathAssistants = function(type, picklistValue, recordTypes, callback) {
+    var arg = new sforce.internal.Parameter("sObjectType", type, false);
+    if (!picklistValue) {
+        picklistValue = null;
+    }
+    var arg2 = new sforce.internal.Parameter("picklistValue", picklistValue, false);
+    if (!recordTypes) {
+        recordTypes = [];
+    }
+    var arg3 = new sforce.internal.Parameter("recordTypeIds", recordTypes, true);
+    return this.invoke("describePathAssistants", [arg, arg2, arg3], false, callback);
+};
+
+sforce.Connection.prototype.describePicklists = function(entityName, fieldNames, recordTypeId, callback) {
+    var picklistParams = new sforce.DescribePicklistsParam();
+    picklistParams.entityName = entityName;
+    picklistParams.fieldNames = fieldNames;
+    picklistParams.recordTypeId = recordTypeId;
+
+    var arg1 = new sforce.internal.Parameter("param", picklistParams, false);
+    return this.invoke("describePicklists", [arg1], false, callback);
+};
+
+sforce.Connection.prototype.describePrimaryCompactLayouts = function(sObjectTypes, callback) {
+    var arg = new sforce.internal.Parameter("sObjectTypes", sObjectTypes, true);
+    return this.invoke("describePrimaryCompactLayouts", [arg], true, callback);
+};
+
+sforce.Connection.prototype.describeApprovalLayout = function(type, approvalProcessNames, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjectType", type, false);
+    if (!approvalProcessNames) {
+    	approvalProcessNames = [];
+    }
+    var arg2 = new sforce.internal.Parameter("approvalProcessNames", approvalProcessNames, true);
+    return this.invoke("describeApprovalLayout", [arg1, arg2], false, callback);
+};
+
+sforce.Connection.prototype.describeSObjectListViews = function(type, recentlyViewed, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjectType", type, false);
+    var arg2 = new sforce.internal.Parameter("recentlyViewed", recentlyViewed, false);
+    var arg3 = new sforce.internal.Parameter("isSoqlCompatible", isSoqlCompatible, false);
+    var arg4 = new sforce.internal.Parameter("limit", limit, false);
+    var arg5 = new sforce.internal.Parameter("offset", offset, false);
+    return this.invoke("describeSObjectListViews", [arg1, arg2, arg3, arg4, arg5], true, callback);
+};
+
+sforce.Connection.prototype.describeTabs = function(callback) {
+	return this.invoke("describeTabs", [], true, callback);
+};
+
+sforce.Connection.prototype.describeAllTabs = function(callback) {
+	return this.invoke("describeAllTabs", [], true, callback);
+};
+
+sforce.Connection.prototype.describeAppMenu = function(appMenuType, networkId, callback) {
+	var arg1 = new sforce.internal.Parameter("appMenuType", appMenuType, false);
+	var arg2 = new sforce.internal.Parameter("networkId", networkId, false);
+    return this.invoke("describeAppMenu", [arg1, arg2], true, callback);
+};
+
+sforce.Connection.prototype.describeFlexiPages = function(flexipageDevName, callback) {
+	var arg1 = new sforce.internal.Parameter("FlexiPage", flexipageDevName, false);
+	return this.invoke("describeFlexiPages", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.describeTheme = function(callback) {
+    return this.invoke("describeTheme", [], true, callback);
+};
+
+sforce.Connection.prototype.describeGlobalTheme = function(callback) {
+    return this.invoke("describeGlobalTheme", [], true, callback);
+};
+
+sforce.Connection.prototype.describeSoftphoneLayout = function(callback) {
+    return this.invoke("describeSoftphoneLayout", [], false, callback);
+};
+
+sforce.Connection.prototype.describeMiniLayout = function (type, recordTypeIds, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjectType", type, false);
+    var arg2 = new sforce.internal.Parameter("recordTypeIds", recordTypeIds, true);
+    return this.invoke("describeMiniLayout", [arg1, arg2], false, callback);
+};
+
+sforce.Connection.prototype.describeSearchScopeOrder = function(callback) {
+     return this.invoke("describeSearchScopeOrder", [], true, callback);
+};
+
+sforce.Connection.prototype.create = function (sobjects, callback) {
+    var arg = new sforce.internal.Parameter("sObjects", sobjects, true);
+    return this.invoke("create", [arg], true, callback);
+};
+
+sforce.Connection.prototype.update = function (sobjects, callback) {
+    var arg = new sforce.internal.Parameter("sObjects", sobjects, true);
+    return this.invoke("update", [arg], true, callback);
+};
+
+sforce.Connection.prototype.upsert = function (externalIDFieldName, sobjects, callback) {
+    var arg1 = new sforce.internal.Parameter("externalIDFieldName", externalIDFieldName, false);
+    var arg2 = new sforce.internal.Parameter("sObjects", sobjects, true);
+    return this.invoke("upsert", [arg1, arg2], true, callback);
+};
+
+sforce.Connection.prototype.deleteIds = function (ids, callback) {
+    var arg = new sforce.internal.Parameter("ids", ids, true);
+    return this.invoke("delete", [arg], true, callback);
+};
+
+sforce.Connection.prototype.deleteByExample = function (sobjects, callback) {
+    var arg = new sforce.internal.Parameter("sObjects", sobjects, true);
+    return this.invoke("deleteByExample", [arg], true, callback);
+};
+
+sforce.Connection.prototype.impersonateUser = function (ids, callback) {
+    var arg = new sforce.internal.Parameter("ids", ids, true);
+    return this.invoke("impersonateUser", [arg], true, callback);
+};
+sforce.Connection.prototype.query = function(queryString, callback) {
+    var arg = new sforce.internal.Parameter("queryString", queryString, false);
+    return this.invoke("query", [arg], false, callback);
+};
+
+sforce.Connection.prototype.queryAll = function(queryString, callback) {
+    var arg = new sforce.internal.Parameter("queryString", queryString, false);
+    return this.invoke("queryAll", [arg], false, callback);
+};
+
+sforce.Connection.prototype.queryMore = function(queryLocator, callback) {
+    var arg = new sforce.internal.Parameter("queryLocator", queryLocator, false);
+    return this.invoke("queryMore", [arg], false, callback);
+};
+
+sforce.Connection.prototype.retrieve = function(fieldList, sObjectType, ids, callback) {
+    var arg1 = new sforce.internal.Parameter("fieldList", fieldList, false);
+    var arg2 = new sforce.internal.Parameter("sObjectType", sObjectType, false);
+    var arg3 = new sforce.internal.Parameter("ids", ids, true);
+    return this.invoke("retrieve", [arg1, arg2, arg3], true, callback);
+};
+
+sforce.Connection.prototype.getAccessInfo = function(callback) {
+    return this.invoke("getAccessInfo", [], false, callback);
+};
+
+sforce.Connection.prototype.getUserInfo = function(callback) {
+    return this.invoke("getUserInfo", [], false, callback);
+};
+
+sforce.Connection.prototype.resetPassword = function(userId, callback) {
+    var arg1 = new sforce.internal.Parameter("userId", userId, false);
+    return this.invoke("resetPassword", [arg1], false, callback);
+};
+
+sforce.Connection.prototype.setPassword = function(userId, password, callback) {
+    var arg1 = new sforce.internal.Parameter("userId", userId, false);
+    var arg2 = new sforce.internal.Parameter("password", password, false);
+    return this.invoke("setPassword", [arg1, arg2], false, callback);
+};
+
+sforce.Connection.prototype.search = function(searchString, callback) {
+    var arg1 = new sforce.internal.Parameter("searchString", searchString, false);
+    return this.invoke("search", [arg1], false, callback);
+};
+
+sforce.Connection.prototype.getDeleted = function(sObjectType, startDate, endDate, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjectType", sObjectType, false);
+    var arg2 = new sforce.internal.Parameter("startDate", startDate, false);
+    var arg3 = new sforce.internal.Parameter("endDate", endDate, false);
+    return this.invoke("getDeleted", [arg1, arg2, arg3], false, callback);
+};
+
+sforce.Connection.prototype.getUpdated = function(sObjectType, startDate, endDate, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjectType", sObjectType, false);
+    var arg2 = new sforce.internal.Parameter("startDate", startDate, false);
+    var arg3 = new sforce.internal.Parameter("endDate", endDate, false);
+    return this.invoke("getUpdated", [arg1, arg2, arg3], false, callback);
+};
+
+
+sforce.Connection.prototype.getServerTimestamp = function(callback) {
+    return this.invoke("getServerTimestamp", [], false, callback);
+};
+
+sforce.Connection.prototype.convertLead = function(leadConverts, callback) {
+    var arg1 = new sforce.internal.Parameter("leadConverts", leadConverts, true);
+    return this.invoke("convertLead", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.merge = function(mergeRequest, callback) {
+    var arg1 = new sforce.internal.Parameter("request", mergeRequest, true);
+    return this.invoke("merge", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.findDuplicates = function(sObjects, callback) {
+    var arg1 = new sforce.internal.Parameter("sObjects", sObjects, true);
+    return this.invoke("findDuplicates", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.findDuplicatesByIds = function(ids, callback) {
+    var arg1 = new sforce.internal.Parameter("ids", ids, true);
+    return this.invoke("findDuplicatesByIds", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.undelete = function(ids, callback) {
+    var arg1 = new sforce.internal.Parameter("ids", ids, true);
+    return this.invoke("undelete", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.process = function(actions, callback) {
+    var arg1 = new sforce.internal.Parameter("actions", actions, true);
+    return this.invoke("process", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.sendEmail = function(messages, callback) {
+    var arg1 = new sforce.internal.Parameter("messages", messages, true);
+    return this.invoke("sendEmail", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.emptyRecycleBin = function(ids, callback) {
+    var arg1 = new sforce.internal.Parameter("ids", ids, true);
+    return this.invoke("emptyRecycleBin", [arg1], true, callback);
+};
+
+sforce.Connection.prototype.invalidateSessions = function(sessionIds, callback) {
+    var arg = new sforce.internal.Parameter("sessionIds", sessionIds, true);
+    return this.invoke("invalidateSessions", [arg], true, callback);
+};
+
+sforce.Connection.prototype.logout = function(callback) {
+    return this.invoke("logout", [], true, callback);
+};
+
+sforce.Connection.prototype.remoteFunction = function(args) {
+    if (!args.url) {
+        throw "url not defined";
+    }
+    if (!args.onSuccess) {
+        throw "onSuccess method not defined";
+    }
+
+    if (!args.method) {
+        args.method = "GET";
+    }
+    if (!args.mimeType) {
+        args.mimeType = "text/plain";
+    }
+
+    if (typeof(args.async) == 'undefined') {
+        args.async = true;
+    }
+
+    if (typeof(args.cache) == 'undefined') {
+        args.cache = false;
+    }
+
+    if (!(args.mimeType == "text/plain" ||
+          args.mimeType == "text/xml")) {
+        throw "Unknown mime type " + args.mimeType;
+    }
+
+    if (sforce.debug.trace) {
+        sforce.debug.log("Open connection to ... " + args.url);
+    }
+
+    var request = new sforce.Transport().newConnection();
+    var proxyUrl = (typeof window.UserContext != "undefined") ? UserContext.getUrl("/services/proxy") : "/services/proxy";
+    if (args.cache) {
+        proxyUrl = proxyUrl + "?end-point-url=" + args.url;
+    } else {
+        proxyUrl = proxyUrl + "?no-cache=" + new Date().getTime();
+    }
+    request.open(args.method, proxyUrl, args.async);
+
+    if (args.requestHeaders) {
+        for (var k in args.requestHeaders) {
+            if (typeof args.requestHeaders[k] != "function") {
+                request.setRequestHeader(k, args.requestHeaders[k]);
+            }
+        }
+    }
+
+    request.setRequestHeader("SalesforceProxy-Endpoint", args.url);
+    request.setRequestHeader("SalesforceProxy-SID", this.sessionId);
+
+    if (args.async) {
+        request.onreadystatechange = _remoteFunctionCallback;
+    }
+
+    if (sforce.debug.trace) {
+        sforce.debug.log("Sending ...");
+    }
+
+    if (args.requestData) {
+        request.send(args.requestData);
+    } else {
+        request.send(null);
+    }
+
+    if (sforce.debug.trace) {
+        sforce.debug.log("Done Sending ...");
+    }
+
+    if (!args.async) {
+        _remoteFunctionCallback();
+    }
+
+    function _remoteFunctionCallback() {
+        if (sforce.debug.trace) {
+            sforce.debug.log("callback called ...");
+        }
+        if (request.readyState == 4) {
+            if (request.status == 200) {
+                if (args.mimeType == "text/plain") {
+                    args.onSuccess(request.responseText, request);
+                } else if (args.mimeType == "text/xml") {
+                    if (!request.responseXML || !request.responseXML.documentElement) {
+                        throw "Response not text/xml mime type: " + request.responseText;
+                    }
+                    args.onSuccess(request.responseXML.documentElement, request);
+                } else {
+                    throw "unsupported mime type: " + args.mimeType;
+                }
+            } else {
+                if (args.onFailure) {
+                    args.onFailure(request.responseText, request);
+                } else {
+                    sforce.debug.log(request.responseText);
+                }
+            }
+        }
+    }
+};
+
+
+sforce.Connection.prototype.writeHeader = function(writer, headerNs) {
+    writer.startHeader();
+
+    writer.writeNamespace(headerNs, "sfns");
+
+    if (this.sessionId !== null) {
+        writer.writeStartElement("SessionHeader", headerNs);
+        writer.writeNameValueNode("sessionId", this.sessionId);
+        writer.writeEndElement("SessionHeader", headerNs);
+    }
+    if (typeof(this.organizationId) !== "undefined") {
+        throw "Use sforce.connection.loginScopeHeader.organizationId instead of sforce.connection.organizationId";
+    }
+    if (this.loginScopeHeader !== null) {
+        writer.writeStartElement("LoginScopeHeader", headerNs);
+        if (this.loginScopeHeader.organizationId !== null) {
+            writer.writeNameValueNode("organizationId", this.loginScopeHeader.organizationId);
+        }
+        if (this.loginScopeHeader.portalId !== null) {
+            writer.writeNameValueNode("portalId", this.loginScopeHeader.portalId);
+        }
+        writer.writeEndElement("LoginScopeHeader", headerNs);
+    }
+    if (this.client !== null || this.defaultNamespace !== null) {
+        writer.writeStartElement("CallOptions", headerNs);
+        if (this.client !== null) {
+            writer.writeNameValueNode("client", this.client);
+        }
+        if (this.defaultNamespace !== null) {
+            writer.writeNameValueNode("defaultNamespace", this.defaultNamespace);
+         }
+        writer.writeEndElement("CallOptions", headerNs);
+    }
+    if (this.batchSize !== null) {
+        writer.writeStartElement("QueryOptions", headerNs);
+        writer.writeNameValueNode("batchSize", this.batchSize);
+        writer.writeEndElement("QueryOptions", headerNs);
+    }
+    if (this.allowFieldTruncation !== null) {
+        writer.writeStartElement("AllowFieldTruncationHeader", headerNs);
+        writer.writeNameValueNode("allowFieldTruncation", this.allowFieldTruncation);
+        writer.writeEndElement("AllowFieldTruncationHeader", headerNs);
+    }
+    if (this.disableFeedTracking !== null) {
+        writer.writeStartElement("DisableFeedTrackingHeader", headerNs);
+        writer.writeNameValueNode("disableFeedTracking", this.disableFeedTracking);
+        writer.writeEndElement("DisableFeedTrackingHeader", headerNs);
+    }
+    if (this.streamingEnabled !== null) {
+        writer.writeStartElement("StreamingEnabledHeader", headerNs);
+        writer.writeNameValueNode("StreamingEnabled", this.streamingEnabled);
+        writer.writeEndElement("StreamingEnabledHeader", headerNs);
+    }
+    if (this.allOrNone !== null) {
+        writer.writeStartElement("AllOrNoneHeader", headerNs);
+        writer.writeNameValueNode("allOrNone", this.allOrNone);
+        writer.writeEndElement("AllOrNoneHeader", headerNs);
+    }
+    if (this.updateMru !== null) {
+        writer.writeStartElement("MruHeader", headerNs);
+        writer.writeNameValueNode("updateMru", this.updateMru);
+        writer.writeEndElement("MruHeader", headerNs);
+    }
+    if (this.emailHeader !== null) {
+        writer.writeStartElement("EmailHeader", headerNs);
+        if (this.emailHeader.triggerAutoResponseEmail) {
+            writer.writeNameValueNode("triggerAutoResponseEmail", this.emailHeader.triggerAutoResponseEmail);
+        }
+        if (this.emailHeader.triggerOtherEmail) {
+            writer.writeNameValueNode("triggerOtherEmail", this.emailHeader.triggerOtherEmail);
+        }
+        if (this.emailHeader.triggerUserEmail) {
+            writer.writeNameValueNode("triggerUserEmail", this.emailHeader.triggerUserEmail);
+        }
+        writer.writeEndElement("EmailHeader", headerNs);
+    }
+    if (this.assignmentRuleHeader !== null) {
+        writer.writeStartElement("AssignmentRuleHeader", headerNs);
+        if (this.assignmentRuleHeader.assignmentRuleId) {
+            writer.writeNameValueNode("assignmentRuleId", this.assignmentRuleHeader.assignmentRuleId);
+        }
+        if (this.assignmentRuleHeader.useDefaultRule) {
+            writer.writeNameValueNode("useDefaultRule", this.assignmentRuleHeader.useDefaultRule);
+        }
+        writer.writeEndElement("AssignmentRuleHeader", headerNs);
+    }
+    if (this.transferToUserId !== null) {
+        writer.writeStartElement("UserTerritoryDeleteHeader", headerNs);
+        writer.writeNameValueNode("transferToUserId", this.transferToUserId);
+        writer.writeEndElement("UserTerritoryDeleteHeader", headerNs);
+    }
+    if (this.duplicateRuleHeader !== null) {
+        writer.writeStartElement("DuplicateRuleHeader", headerNs);
+        if (this.duplicateRuleHeader.allowSave) {
+            writer.writeNameValueNode("allowSave", this.duplicateRuleHeader.allowSave);
+        }
+        if (this.duplicateRuleHeader.includeRecordDetails) {
+            writer.writeNameValueNode("includeRecordDetails", this.duplicateRuleHeader.includeRecordDetails);
+        }
+        if (this.duplicateRuleHeader.runAsCurrentUser) {
+            writer.writeNameValueNode("runAsCurrentUser", this.duplicateRuleHeader.runAsCurrentUser);
+        }
+        writer.writeEndElement("DuplicateRuleHeader", headerNs);
+    }
+    if (this.debuggingHeader !== null) {
+        writer.writeStartElement("DebuggingHeader", headerNs);
+        // Write out old style if specified
+        if (this.debuggingHeader.debugLevel) {
+            writer.writeNameValueNode("debugLevel", this.debuggingHeader.debugLevel);
+        }
+        // Write out the new style debugging categories and levels
+        if (this.debuggingHeader.debugCategories) {
+            var categories = this.debuggingHeader.debugCategories;
+            for (var i = 0; i < categories.length; i++) {
+                var catAndLevel = categories[i].split(",");
+
+                if (catAndLevel.length == 2) {
+                    writer.writeStartElement("categories");
+                    writer.writeNameValueNode("category", catAndLevel[0]);
+                    writer.writeNameValueNode("level", catAndLevel[1]);
+                    writer.writeEndElement("categories");
+                }
+            }
+        }
+        writer.writeEndElement("DebuggingHeader", headerNs);
+    }
+
+    writer.endHeader();
+};
+
+sforce.Connection.prototype.namespaceMap = [
+{ns:sforce.Connection.prototype.sforceNs, prefix:null},
+{ns:sforce.Connection.prototype.sobjectNs, prefix:"ns1"}
+        ];
+
+sforce.Connection.prototype.invoke = function(method, args, isArray, callback) {
+    return this._invoke(method, args, isArray, callback, this.namespaceMap, this.serverUrl, this.sforceNs, this.sobjectNs);
+};
+
+sforce.Connection.prototype._invoke = function(method, args, isArray, callback, namespaces, url, headerNs, sobjectNs) {
+    if (callback) {
+        if (typeof(callback) == "function") {
+        } else {
+            if (!callback.onSuccess) {
+                throw "onSuccess not defined in the callback";
+            }
+            if (!callback.onFailure) {
+                throw "onFailure not defined in the callback";
+            }
+        }
+    }
+
+    var writer = new sforce.XmlWriter();
+    writer.startEnvelope();
+    this.writeHeader(writer, headerNs);
+    writer.startBody();
+    writer.writeStartElement(method);
+
+    for (var i = 0; i<namespaces.length; i++) {
+        writer.writeNamespace(namespaces[i].ns, namespaces[i].prefix);
+    }
+
+    for (var i = 0; i < args.length; i++) {
+        var arg = args[i];
+        if (typeof(arg.value) === "undefined") {
+            throw "arg " + i + " '" + arg.name + "' not specified";
+        }
+        if (arg.value !== null) {
+            if (arg.isArray && !arg.value.push) {
+                throw "arg " + i + " '" + arg.name + "' is an array. But passed in value is not an array";
+            }
+            if (!arg.isArray && arg.value.push) {
+                throw "arg " + i + " '" + arg.name + "' is not an array. But passed in value is an array";
+            }
+        }
+        if (arg.value === null) {
+            this.writeOne(writer, arg.name, null, sobjectNs);
+        } else if (arg.value.push) { //this is an array
+            for (var j = 0; j < arg.value.length; j++) {
+                var obj = arg.value[j];
+                if (!obj) {
+                    throw "Array element at " + j + " is null.";
+                }
+                this.writeOne(writer, arg.name, obj, sobjectNs);
+            }
+        } else {
+            this.writeOne(writer, arg.name, arg.value, sobjectNs);
+        }
+    }
+    writer.writeEndElement(method);
+    writer.endBody();
+    writer.endEnvelope();
+    if (sforce.debug.trace) {
+        sforce.debug.log("Request: server- " + url);
+        sforce.debug.logXml(writer.toString());
+    }
+    var transport = new sforce.SoapTransport();
+    return transport.send(url, writer, isArray, callback);
+};
+
+
+/* QueryResultIterator */
+
+sforce.QueryResultIterator = function(queryResult) {
+    this.queryResult = queryResult;
+    this.index = 0;
+    this.records = this.queryResult.getArray("records");
+};
+
+sforce.QueryResultIterator.prototype.hasNext = function() {
+    if (this.records.length > this.index) {
+        return true;
+    }
+    if (this.queryResult.queryLocator !== null) {
+        this.queryResult = sforce.connection.queryMore(this.queryResult.queryLocator);
+        this.records = this.queryResult.getArray("records");
+        this.index = 0;
+    }
+    if (this.records.length > this.index) {
+        return true;
+    } else {
+        return false;
+    }
+};
+
+sforce.QueryResultIterator.prototype.next = function() {
+    if (this.records.length > this.index) {
+        var result = this.records[this.index];
+        this.index++;
+        return result;
+    } else {
+        throw "Index out of bound : " + this.index;
+    }
+};
+
+
+/* Email */
+
+
+sforce.Email = function() {
+};
+
+sforce.Email.prototype = new sforce.Xml("messages");
+
+sforce.MassEmailMessage = function() {
+};
+
+sforce.MassEmailMessage.prototype = new sforce.Xml("messages");
+sforce.MassEmailMessage.prototype._xsiType = "MassEmailMessage";
+
+
+
+sforce.SingleEmailMessage = function() {
+};
+
+sforce.SingleEmailMessage.prototype = new sforce.Xml("messages");
+sforce.SingleEmailMessage.prototype._xsiType = "SingleEmailMessage";
+
+
+
+/* ProcessRequest */
+
+
+sforce.ProcessRequest = function() {
+};
+
+sforce.ProcessRequest.prototype = new sforce.Xml("actions");
+
+sforce.ProcessSubmitRequest = function() {
+};
+
+sforce.ProcessSubmitRequest.prototype = new sforce.Xml("actions");
+sforce.ProcessSubmitRequest.prototype._xsiType = "ProcessSubmitRequest";
+
+
+sforce.ProcessWorkitemRequest = function() {
+};
+
+sforce.ProcessWorkitemRequest.prototype = new sforce.Xml("actions");
+sforce.ProcessWorkitemRequest.prototype._xsiType = "ProcessWorkitemRequest";
+/* set up connection */
+sforce.connection = new sforce.Connection();
+
+var UserContext = (typeof window.UserContext != "undefined") ? window.UserContext : {
+    siteUrlPrefix : "",
+    getUrl : function (url) {
+        // fix URL for sites with prefixes
+        if (typeof url == "undefined" || typeof UserContext.siteUrlPrefix == "undefined" || !UserContext.siteUrlPrefix)
+            return url;
+
+        if (url.indexOf('/') != 0)
+            return url;
+
+        if(url.indexOf(UserContext.siteUrlPrefix) == 0)
+            return url;
+
+        return UserContext.siteUrlPrefix + url;
+    }
+};
+
+if (typeof(__sfdcSiteUrlPrefix) != "undefined") {
+    UserContext.siteUrlPrefix = __sfdcSiteUrlPrefix;
+}
+
+sforce.connection.serverUrl = (typeof window.UserContext != "undefined") ? UserContext.getUrl("/services/Soap/u/51.0") : "/services/Soap/u/51.0";
+
+if (typeof(__sfdcSessionId) != "undefined") {
+    sforce.connection.sessionId = __sfdcSessionId;
+}
diff --git a/scr/staticresources/connection20.resource-meta.xml b/scr/staticresources/connection20.resource-meta.xml
new file mode 100644
index 0000000..6adb110
--- /dev/null
+++ b/scr/staticresources/connection20.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/cti.js b/scr/staticresources/cti.js
new file mode 100644
index 0000000..9dfba31
--- /dev/null
+++ b/scr/staticresources/cti.js
Binary files differ
diff --git a/scr/staticresources/cti.resource-meta.xml b/scr/staticresources/cti.resource-meta.xml
new file mode 100644
index 0000000..2754b4b
--- /dev/null
+++ b/scr/staticresources/cti.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>application/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/jquery183minjs.resource-meta.xml b/scr/staticresources/jquery183minjs.resource-meta.xml
new file mode 100644
index 0000000..9f467c3
--- /dev/null
+++ b/scr/staticresources/jquery183minjs.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/plain</contentType>
+</StaticResource>
diff --git a/scr/staticresources/jquery183minjs.txt b/scr/staticresources/jquery183minjs.txt
new file mode 100644
index 0000000..45477c0
--- /dev/null
+++ b/scr/staticresources/jquery183minjs.txt
@@ -0,0 +1,2 @@
+/*! jQuery v1.8.3 jquery.com | jquery.org/license */
+(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
diff --git a/scr/staticresources/jquerysuggestcss.js b/scr/staticresources/jquerysuggestcss.js
new file mode 100644
index 0000000..3bacc2e
--- /dev/null
+++ b/scr/staticresources/jquerysuggestcss.js
@@ -0,0 +1,28 @@
+.ac_results {
+        border: 1px solid gray;
+        background-color: white;
+        padding: 0;
+        margin: 0;
+        list-style: none;
+        position: absolute;
+        z-index: 10000;
+        display: none;
+    }
+    
+    .ac_results li {
+        padding: 2px 5px 2px 0px;
+        margin-left : 2px;
+        white-space: nowrap;
+        color: #101010;
+        text-align: left;
+    }
+    
+    .ac_over {
+        cursor: pointer;
+        background-color: #F0F0B8;
+    }
+    
+    .ac_match {
+        text-decoration: underline;
+        color: black;
+    }
\ No newline at end of file
diff --git a/scr/staticresources/jquerysuggestcss.resource-meta.xml b/scr/staticresources/jquerysuggestcss.resource-meta.xml
new file mode 100644
index 0000000..463f132
--- /dev/null
+++ b/scr/staticresources/jquerysuggestcss.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Public</cacheControl>
+    <contentType>text/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/jquerysuggestjs.js b/scr/staticresources/jquerysuggestjs.js
new file mode 100644
index 0000000..5c15cf1
--- /dev/null
+++ b/scr/staticresources/jquerysuggestjs.js
@@ -0,0 +1,420 @@
+// reset閵囶喖鐗崥鍧眗ue
+    // Nama閵団問d 閵囥劊鍊愰妵顐㈩槷閺囨番浠愰妵顏備簻閸潙鎮巘rue
+    // 閺傝埇浠愰妵鍕偓銈埮嶇�规哎浠愰妵鐔风壃閸氬潚alse
+    function resetValue(htmlId){
+        v = j$(escapeVfId(htmlId)).value();
+        vb = j$(escapeVfId(htmlId + 'Hidden')).value();
+        vid = j$(escapeVfId(htmlId + 'Id')).value();
+        vidb = j$(escapeVfId(htmlId + 'HiddenId')).value();
+
+        // Nama閵団問d 閵囥劊鍊愰妵顐㈩槷閺囨番浠愰妵顏備簻閸潙鎮�
+        if(v == vb){
+            if(vid == vidb){
+                return true;
+            }
+        }
+        if(v == null || v == ''){
+            j$(escapeVfId(htmlId + 'Hidden')).val('');
+            j$(escapeVfId(htmlId + 'Id')).val('');
+            j$(escapeVfId(htmlId + 'HiddenId')).val('');
+            return false;
+        }
+        // Id閸忋劑鍎寸粚鎭掍化閵囷拷(閵囥們浼ㄩ妶濡攗ggest閵囧鍊滻d閵堟帟艒鐎规哎浠归妵宥冧桓閵囧嫨浠鹃妵锟�)
+        if(vid == '' && vidb == '') {
+            j$(escapeVfId(htmlId)).val('');
+            j$(escapeVfId(htmlId + 'Hidden')).val('');
+            return false;
+        }
+        // Name閸忋劑鍎寸粚鎭掍化閵囷拷(閵囧倶鍊為妵鍫涗痪閵囷拷)
+        if(v == '' && vb == '') {
+            j$(escapeVfId(htmlId + 'Id')).val('');
+            j$(escapeVfId(htmlId + 'HiddenId')).val('');
+            return false;
+        }
+        // Id娑撯偓閼风ame婢跺娲块敍鍧甧set閿涳拷
+        if(vid == vidb){
+            if(v != vb){
+                j$(escapeVfId(htmlId)).val(vb);
+                return true;
+            }
+        }
+        // Name娑撯偓閼风d婢跺娲块敍鍧皍ggest闁憡濮欓敍锟�
+        if(v == vb){
+            if(vid != vidb){
+                j$(escapeVfId(htmlId + 'Hidden')).val(v);
+                j$(escapeVfId(htmlId + 'HiddenId')).val(vid);
+                return false;
+            }
+        }
+        // Id 閵囷拷 Name 閵囥劊鍊愰妵顐︿粚閵囧棗鐗崥锟�
+        j$(escapeVfId(htmlId + 'Hidden')).val(v);
+        j$(escapeVfId(htmlId + 'HiddenId')).val(vid);
+        return false;
+    }
+
+    /*
+     *  jquery.suggest 1.1 - 2007-08-06
+     *
+     *  Uses code and techniques from following libraries:
+     *  1. http://www.dyve.net/jquery/?autocomplete
+     *  2. http://dev.jquery.com/browser/trunk/plugins/interface/iautocompleter.js
+     *
+     *  All the new stuff written by Peter Vulgaris (www.vulgarisoip.com)
+     *  Feel free to do whatever you want with this file
+     *
+     */
+
+    (function($) {
+
+        $.suggest = function(input, options) {
+            var $input = $(input).attr("autocomplete", "off");
+            var $results = $(document.createElement("ul"));
+
+            var timeout = false;        // hold timeout ID for suggestion results to appear
+            var prevLength = 0;         // last recorded length of $input.value()
+            var cache = [];             // cache MRU list
+            var beforerequest = null;
+            var cacheSize = 0;          // size of cache in chars (bytes?)
+/*------------------------------ by katsu --------*/
+            //$results.addClass(options.resultsClass).appendTo('body');
+            //resetPosition();
+            if ($input.attr("jquerysuggest") == "on") {
+                // aleady bind suggest
+                $results = $("#jquerysuggest");
+            } else {
+                $("#jquerysuggest").remove();
+                $results.addClass(options.resultsClass).appendTo('body');
+                resetPosition();
+            }
+            $input.attr("jquerysuggest", "on");
+            $results.attr("id", "jquerysuggest");
+/*------------------------------------------------*/
+
+            $(window)
+                .load(resetPosition)        // just in case user is changing size of page while loading
+                .resize(resetPosition);
+
+/*------------------------------ by systemconcept --------*/
+            //$input.blur(function() {
+            //  setTimeout(function() { $results.hide() }, 200);
+            //});
+            $input.attr("jquerysuggest_skip_flag", "false");
+            $input.blur(
+                function() {
+                    setTimeout(
+                        function() {
+                            if($input.attr("jquerysuggest_skip_flag") == "false") {
+                                $results.hide();
+                                $input.removeAttr("jquerysuggest");
+                            } else {
+                                $input.focus();
+                                $input.attr("jquerysuggest_skip_flag", "false");
+                            }
+                        },
+                        200
+                    );
+                }
+            );
+            $results.mousedown(function() { $input.attr("jquerysuggest_skip_flag", "true"); });
+/*--------------------------------------------------------*/
+            // help IE users if possible
+            try {
+                $results.bgiframe();
+            } catch(e) { }
+
+
+            // I really hate browser detection, but I don't see any other way
+            if ($.browser.mozilla)
+                $input.keypress(processKey);    // onkeypress repeats arrow keys in Mozilla/Opera
+            else
+                $input.keydown(processKey);     // onkeydown repeats arrow keys in IE/Safari
+
+
+            function resetPosition() {
+                // requires jquery.dimension plugin
+                var offset = $input.offset();
+                $results.css({
+                    top: (offset.top + input.offsetHeight) + 'px',
+                    left: offset.left + 'px'
+                });
+            }
+
+
+            function processKey(e) {
+
+                // handling up/down/escape requires results to be visible
+                // handling enter/tab requires that AND a result to be selected
+                if ((/27$|38$|40$/.test(e.keyCode) && $results.is(':visible')) ||
+                    (/^13$|^9$/.test(e.keyCode) && getCurrentResult())) {
+
+                    if (e.preventDefault)
+                        e.preventDefault();
+                    if (e.stopPropagation)
+                        e.stopPropagation();
+
+                    e.cancelBubble = true;
+                    e.returnValue = false;
+
+                    switch(e.keyCode) {
+
+                        case 38: // up
+                            prevResult();
+                            break;
+
+                        case 40: // down
+                            nextResult();
+                            break;
+
+                        case 9:  // tab
+                        case 13: // return
+                            selectCurrentResult();
+                            break;
+
+                        case 27: // escape
+                            $results.hide();
+                            $input.removeAttr("jquerysuggest");
+                            break;
+
+                    }
+
+                } else if ($input.value().length != prevLength) {
+                    if (e.keyCode == 9) {
+                        return;
+                    }
+                    if (timeout)
+                        clearTimeout(timeout);
+                    timeout = setTimeout(suggest, options.delay);
+                    prevLength = $input.value().length;
+
+                }
+
+
+            }
+
+
+            function suggest() {
+
+                var q = $.trim($input.value());
+                var qwords = [];
+                if (options.minwords > 0 && q.length > 0) {
+                    var qwordstmp = q.split(" ");
+                    for (var i = 0; i < qwordstmp.length; i++) {
+                        if (qwordstmp[i] != "" && qwordstmp[i] != " ") {
+                            qwords.push(qwordstmp[i]);
+                        }
+                    }
+                }
+
+                if (qwords.length >= options.minwords || q.length >= options.minchars) {
+
+//                  cached = checkCache(q);
+
+//                  if (cached) {
+
+//                      displayItems(cached['items']);
+
+//                  } else {
+                        if (beforerequest != null) {
+                            beforerequest.abort();
+                        }
+                        beforerequest = $.get(options.source, {q: q}, function(txt) {
+
+                            $results.hide();
+                            $input.removeAttr("jquerysuggest");
+
+                            var items = parseTxt(txt, q);
+
+                            displayItems(items);
+//                          addToCache(q, items, txt.length);
+
+                        });
+
+//                  }
+
+                } else {
+                    $results.hide();
+                    $input.removeAttr("jquerysuggest");
+                }
+
+            }
+
+
+            function checkCache(q) {
+
+                for (var i = 0; i < cache.length; i++)
+                    if (cache[i]['q'] == q) {
+                        cache.unshift(cache.splice(i, 1)[0]);
+                        return cache[0];
+                    }
+
+                return false;
+
+            }
+
+            function addToCache(q, items, size) {
+
+                while (cache.length && (cacheSize + size > options.maxCacheSize)) {
+                    var cached = cache.pop();
+                    cacheSize -= cached['size'];
+                }
+
+                cache.push({
+                    q: q,
+                    size: size,
+                    items: items
+                    });
+
+                cacheSize += size;
+
+            }
+
+            function displayItems(items) {
+                if (!items)
+                    return;
+
+                if (!items.length) {
+                    $results.hide();
+                    $input.removeAttr("jquerysuggest");
+                    return;
+                }
+
+                var html = '';
+                for (var i = 0; i < items.length; i++)
+                    html += '<li>' + items[i] + '</li>';
+
+                $results.html(html).show();
+                $input.attr("jquerysuggest", "on");
+
+                $results
+                    .children('li')
+                    .mouseover(function() {
+                        $results.children('li').removeClass(options.selectClass);
+                        $(this).addClass(options.selectClass);
+                    })
+                    .click(function(e) {
+                        e.preventDefault();
+                        e.stopPropagation();
+                        selectCurrentResult();
+                    });
+
+            }
+
+            function parseTxt(txt, q) {
+
+                var items = [];
+                var tokens = txt.split(options.delimiter);
+
+                // parse returned data for non-empty items
+                for (var i = 0; i < tokens.length; i++) {
+                    var token = $.trim(tokens[i]);
+                    if (token) {
+                        token = token.replace(
+                            new RegExp(q, 'ig'),
+                            function(q) { return '<span class="' + options.matchClass + '">' + q + '</span>' }
+                            );
+                        items[items.length] = token;
+                    }
+                }
+
+                return items;
+            }
+
+            function getCurrentResult() {
+
+                if (!$results.is(':visible'))
+                    return false;
+
+                var $currentResult = $results.children('li.' + options.selectClass);
+
+                if (!$currentResult.length)
+                    $currentResult = false;
+
+                return $currentResult;
+
+            }
+
+            function selectCurrentResult() {
+                $currentResult = getCurrentResult();
+
+                if ($currentResult) {
+                    var $name = $currentResult.children("span.result_name");
+                    var $id = $currentResult.children("span.result_id");
+/*------------------------------ by katsu --------*/
+                  if ($id.text() != '') {
+                    $input.val($name.text());
+
+                    var idId = $input.attr("id");
+                    idId = escapeVfId(idId + "Id");
+
+                    $(idId).val($id.text());
+                    idId = $input.attr("id");
+                    // onchange閵団暙nblur閵囶垽绱ら妵銈冧粣閵囧鐤呯憗鍛粣閵囶亗浜滈妵銊﹀厒鐎规哎鈧椒娴弬鐟版嚑閵囧啿鍤妵锟�
+                    // entry閵堫厹鍏楃�垫儳绻欓妵顔轰户閵堜降鈧胶娲块幒锟� onchange閵団暙nblur閵堟帒鎳犻妵鍐插毉閵囨瑥绻�鐟曚降浠归妵娆嶁偓锟�
+                    $input.change();
+                    $input.blur();
+                  }
+/*------------------------------------------------*/
+                    $results.hide();
+                    $input.removeAttr("jquerysuggest");
+
+                    if (options.onSelect)
+                        options.onSelect.apply($input[0]);
+                }
+
+            }
+
+            function nextResult() {
+
+                $currentResult = getCurrentResult();
+                if ($currentResult)
+                    $currentResult
+                        .removeClass(options.selectClass)
+                        .next()
+                        .addClass(options.selectClass);
+                else
+                    $results.children('li:first-child').addClass(options.selectClass);
+
+            }
+
+            function prevResult() {
+
+                $currentResult = getCurrentResult();
+
+                if ($currentResult)
+                    $currentResult
+                        .removeClass(options.selectClass)
+                        .prev()
+                            .addClass(options.selectClass);
+                else
+                    $results.children('li:last-child').addClass(options.selectClass);
+
+            }
+
+        }
+
+        $.fn.suggest = function(source, options) {
+
+            if (!source)
+                return;
+
+            options = options || {};
+            options.source = source;
+            options.delay = options.delay || 100;
+            options.resultsClass = options.resultsClass || 'ac_results';
+            options.selectClass = options.selectClass || 'ac_over';
+            options.matchClass = options.matchClass || 'ac_match';
+            options.minchars = options.minchars || 2;
+            options.minwords = options.minwords || 0;
+            options.delimiter = options.delimiter || '\n';
+            options.onSelect = options.onSelect || false;
+            options.maxCacheSize = options.maxCacheSize || 65536;
+
+            this.each(function() {
+                new $.suggest(this, options);
+            });
+
+            return this;
+
+        };
+
+    })(jQuery);
\ No newline at end of file
diff --git a/scr/staticresources/jquerysuggestjs.resource-meta.xml b/scr/staticresources/jquerysuggestjs.resource-meta.xml
new file mode 100644
index 0000000..463f132
--- /dev/null
+++ b/scr/staticresources/jquerysuggestjs.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Public</cacheControl>
+    <contentType>text/javascript</contentType>
+</StaticResource>
diff --git a/scr/staticresources/pdfSign.gif b/scr/staticresources/pdfSign.gif
new file mode 100644
index 0000000..9382498
--- /dev/null
+++ b/scr/staticresources/pdfSign.gif
Binary files differ
diff --git a/scr/staticresources/pdfSign.resource-meta.xml b/scr/staticresources/pdfSign.resource-meta.xml
new file mode 100644
index 0000000..fbd6a1c
--- /dev/null
+++ b/scr/staticresources/pdfSign.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Public</cacheControl>
+    <contentType>image/gif</contentType>
+</StaticResource>
diff --git a/scr/staticresources/scc_tour_images.resource-meta.xml b/scr/staticresources/scc_tour_images.resource-meta.xml
new file mode 100644
index 0000000..664da7f
--- /dev/null
+++ b/scr/staticresources/scc_tour_images.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>application/zip</contentType>
+</StaticResource>
diff --git a/scr/staticresources/scc_tour_images/Tour_Images/bg_tour.png b/scr/staticresources/scc_tour_images/Tour_Images/bg_tour.png
new file mode 100644
index 0000000..91cd0f9
--- /dev/null
+++ b/scr/staticresources/scc_tour_images/Tour_Images/bg_tour.png
Binary files differ
diff --git a/scr/staticresources/scc_tour_images/Tour_Images/chatter-answers-950.png b/scr/staticresources/scc_tour_images/Tour_Images/chatter-answers-950.png
new file mode 100644
index 0000000..b4216e9
--- /dev/null
+++ b/scr/staticresources/scc_tour_images/Tour_Images/chatter-answers-950.png
Binary files differ
diff --git a/scr/staticresources/scc_tour_images/Tour_Images/console-950.png b/scr/staticresources/scc_tour_images/Tour_Images/console-950.png
new file mode 100644
index 0000000..67c32ef
--- /dev/null
+++ b/scr/staticresources/scc_tour_images/Tour_Images/console-950.png
Binary files differ
diff --git a/scr/staticresources/scc_tour_images/Tour_Images/icon_sprite_serviceSupport.png b/scr/staticresources/scc_tour_images/Tour_Images/icon_sprite_serviceSupport.png
new file mode 100644
index 0000000..7d39663
--- /dev/null
+++ b/scr/staticresources/scc_tour_images/Tour_Images/icon_sprite_serviceSupport.png
Binary files differ
diff --git a/scr/staticresources/scc_tour_images/Tour_Images/tourArrows.png b/scr/staticresources/scc_tour_images/Tour_Images/tourArrows.png
new file mode 100644
index 0000000..a03b63d
--- /dev/null
+++ b/scr/staticresources/scc_tour_images/Tour_Images/tourArrows.png
Binary files differ
diff --git a/scr/staticresources/tests.js b/scr/staticresources/tests.js
new file mode 100644
index 0000000..2f1d85a
--- /dev/null
+++ b/scr/staticresources/tests.js
@@ -0,0 +1,3 @@
+function helloWorld() {
+alert("error");
+}
\ No newline at end of file
diff --git a/scr/staticresources/tests.resource-meta.xml b/scr/staticresources/tests.resource-meta.xml
new file mode 100644
index 0000000..6adb110
--- /dev/null
+++ b/scr/staticresources/tests.resource-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
+    <cacheControl>Private</cacheControl>
+    <contentType>text/javascript</contentType>
+</StaticResource>
diff --git a/scr/triggers/AccountTrigger.trigger b/scr/triggers/AccountTrigger.trigger
new file mode 100644
index 0000000..35c3989
--- /dev/null
+++ b/scr/triggers/AccountTrigger.trigger
@@ -0,0 +1,53 @@
+trigger AccountTrigger on Account (before insert, before update, after insert, after update) {
+    if (Trigger.isBefore && Trigger.isInsert) {
+        //鏂板缓涔嬪墠灏辩粰璧嬪�� gwy 2021-06-16
+        for (Account acc : Trigger.new) {
+            if(acc.ProductSegment__c == 'IE' && acc.Sub_Use1__c != null){
+                acc.Sub_Use__c  = acc.Sub_Use1__c;
+            }
+            if(acc.ProductSegment__c == 'IE' && acc.Sub_UseA__c != null){
+                acc.Sub_UseD__c = acc.Sub_UseA__c;
+            }
+            if(acc.ProductSegment__c == 'BS' && acc.IndustryB__c != null){
+                acc.IndustryC__c  = acc.IndustryB__c;
+            }
+            if(acc.ProductSegment__c == 'BS' && acc.IndustryBD__c != null){
+                acc.IndustryCD__c = acc.IndustryBD__c;
+            } 
+        }
+        AccountTriggerHandler.setIsNew(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AccountTriggerHandler.setSubUse(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isInsert) {
+        AccountTriggerHandler.setDealerGroup(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AccountTriggerHandler.updateCampaignRelationship(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,'1');
+    }
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        //鏇存柊鍓嶅氨缁欒祴鍊� gwy 2021-06-16
+        for (Account acc : Trigger.new) {
+            if(acc.ProductSegment__c == 'IE' && acc.Sub_Use1__c != null){
+                acc.Sub_Use__c  = acc.Sub_Use1__c;
+            }
+            if(acc.ProductSegment__c == 'IE' && acc.Sub_UseA__c != null){
+                acc.Sub_UseD__c = acc.Sub_UseA__c;
+            }
+            if(acc.ProductSegment__c == 'BS' && acc.IndustryB__c != null){
+                acc.IndustryC__c  = acc.IndustryB__c;
+            }
+            if(acc.ProductSegment__c == 'BS' && acc.IndustryBD__c != null){
+                acc.IndustryCD__c = acc.IndustryBD__c;
+            }  
+        }
+        AccountTriggerHandler.setSubUse(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AccountTriggerHandler.updateForDealer(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AccountTriggerHandler.dealerAccountApproval(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AccountTriggerHandler.CheckAccoutnNameChange(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isUpdate) {
+        AccountTriggerHandler.dealerAccountApproval2(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AccountTriggerHandler.setBusinesslicense(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if ((Trigger.isAfter && Trigger.isInsert) || (Trigger.isBefore && Trigger.isUpdate)) {
+        SBG001TriggerHandler.SBG001AccountTrigger(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/AccountTrigger.trigger-meta.xml b/scr/triggers/AccountTrigger.trigger-meta.xml
new file mode 100644
index 0000000..9972add
--- /dev/null
+++ b/scr/triggers/AccountTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/AssetTrigger.trigger b/scr/triggers/AssetTrigger.trigger
new file mode 100644
index 0000000..00c81eb
--- /dev/null
+++ b/scr/triggers/AssetTrigger.trigger
@@ -0,0 +1,9 @@
+trigger AssetTrigger on Asset (before update,after update) {
+	if(Trigger.isBefore && Trigger.isUpdate){
+		AssetTriggerHandler.checkStatus(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+		AssetTriggerHandler.checkPlace(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+	}
+	if(Trigger.isAfter && Trigger.isUpdate){
+		AssetTriggerHandler.isInstock(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+	}
+}
\ No newline at end of file
diff --git a/scr/triggers/AssetTrigger.trigger-meta.xml b/scr/triggers/AssetTrigger.trigger-meta.xml
new file mode 100644
index 0000000..b2bad7c
--- /dev/null
+++ b/scr/triggers/AssetTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/AttachmentTrigger.trigger b/scr/triggers/AttachmentTrigger.trigger
new file mode 100644
index 0000000..87fd151
--- /dev/null
+++ b/scr/triggers/AttachmentTrigger.trigger
@@ -0,0 +1,26 @@
+trigger AttachmentTrigger on Attachment (before insert, after insert, before update, before delete, after delete) {
+    if (Trigger.isBefore && Trigger.isInsert) {
+        AttachmentTriggerHandler.fileCheck(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.fileCheck5(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.UploadTradeCustomerManagerFile(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isInsert) {
+        AttachmentTriggerHandler.uploadContract(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.AfterPassUpload(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.fileCheck4(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.AfterUploadToUserFaultInfo(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        AttachmentTriggerHandler.fileCheck3(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.updateTradeCustomerManagerFile(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isBefore && Trigger.isDelete) {
+        AttachmentTriggerHandler.fileCheck2(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.fileCheck6(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.DeleteTradeCustomerManagerFile(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isDelete) {
+        AttachmentTriggerHandler.deleteContract(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        AttachmentTriggerHandler.deleteconfirm(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/AttachmentTrigger.trigger-meta.xml b/scr/triggers/AttachmentTrigger.trigger-meta.xml
new file mode 100644
index 0000000..9972add
--- /dev/null
+++ b/scr/triggers/AttachmentTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/BusinessActivityTrigger.trigger b/scr/triggers/BusinessActivityTrigger.trigger
new file mode 100644
index 0000000..55bb8ed
--- /dev/null
+++ b/scr/triggers/BusinessActivityTrigger.trigger
@@ -0,0 +1,17 @@
+trigger BusinessActivityTrigger on BusinessActivity__c (before insert,before update,after insert,before delete) {
+    if(Trigger.isBefore && Trigger.isUpdate){
+        BusinessActivityHandler.ValidDaysBetweenTwoWorkingDays(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        BusinessActivityHandler.TSRepairManagementCode(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if(Trigger.isBefore && Trigger.isInsert){
+       BusinessActivityHandler.ValidDaysBetweenTwoWorkingDays(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+
+    if(Trigger.isAfter && Trigger.isInsert){
+       BusinessActivityHandler.TSRepairManagementCode(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+
+    if(Trigger.isBefore && Trigger.isDelete){
+       BusinessActivityHandler.TSRepairManagementCode(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/BusinessActivityTrigger.trigger-meta.xml b/scr/triggers/BusinessActivityTrigger.trigger-meta.xml
new file mode 100644
index 0000000..8f932fc
--- /dev/null
+++ b/scr/triggers/BusinessActivityTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>49.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/CertificationDetailTrigger.trigger b/scr/triggers/CertificationDetailTrigger.trigger
new file mode 100644
index 0000000..62906e8
--- /dev/null
+++ b/scr/triggers/CertificationDetailTrigger.trigger
@@ -0,0 +1,6 @@
+trigger CertificationDetailTrigger on CertificationDetails__c (before insert, before update, after insert, after update) {
+	
+	if (Trigger.isAfter && Trigger.isInsert) {
+		CertificationDetailTriggerHandler.updateDealerPurchaseDetail(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+	}
+}
\ No newline at end of file
diff --git a/scr/triggers/CertificationDetailTrigger.trigger-meta.xml b/scr/triggers/CertificationDetailTrigger.trigger-meta.xml
new file mode 100644
index 0000000..6205514
--- /dev/null
+++ b/scr/triggers/CertificationDetailTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/ContactTrigger.trigger b/scr/triggers/ContactTrigger.trigger
new file mode 100644
index 0000000..9e99031
--- /dev/null
+++ b/scr/triggers/ContactTrigger.trigger
@@ -0,0 +1,12 @@
+trigger ContactTrigger on Contact (before insert, before update, after insert) {
+	if (Trigger.isBefore && Trigger.isInsert) {
+		ContactTriggerHandler.setIsNew(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+	}
+	if (Trigger.isBefore && Trigger.isUpdate) {
+		ContactTriggerHandler.updateForDealer(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    	ContactTriggerHandler.dealerContactApproval(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if ((Trigger.isAfter && Trigger.isInsert) || (Trigger.isBefore && Trigger.isUpdate)) {
+        SBG001TriggerHandler.SBG001ContactTrigger(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/ContactTrigger.trigger-meta.xml b/scr/triggers/ContactTrigger.trigger-meta.xml
new file mode 100644
index 0000000..9972add
--- /dev/null
+++ b/scr/triggers/ContactTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/DeliveryTrigger.trigger b/scr/triggers/DeliveryTrigger.trigger
new file mode 100644
index 0000000..56cef70
--- /dev/null
+++ b/scr/triggers/DeliveryTrigger.trigger
@@ -0,0 +1,6 @@
+trigger DeliveryTrigger on Delivery__c(before insert, before update, after insert, after update) {
+    if (Trigger.isBefore && Trigger.isInsert) {
+      DeliveryTriggerHandler.setDeliveryReceiver(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+       
+    }
\ No newline at end of file
diff --git a/scr/triggers/DeliveryTrigger.trigger-meta.xml b/scr/triggers/DeliveryTrigger.trigger-meta.xml
new file mode 100644
index 0000000..bc50bfc
--- /dev/null
+++ b/scr/triggers/DeliveryTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/OpportunityLineItemTrigger.trigger b/scr/triggers/OpportunityLineItemTrigger.trigger
new file mode 100644
index 0000000..a5c6ffa
--- /dev/null
+++ b/scr/triggers/OpportunityLineItemTrigger.trigger
@@ -0,0 +1,16 @@
+trigger OpportunityLineItemTrigger on OpportunityLineItem (before insert,after insert ,before update) {
+   
+        if (Trigger.isBefore) {
+            OpportunityLineItemTriggerHandler.updateForDealer(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityLineItemTriggerHandler.setTextField(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+
+        //XHL-20190510-AddStart
+        
+        if (Trigger.isAfter && Trigger.isInsert) {
+            
+            OpportunityLineItemTriggerHandler.SetProduct2Mark(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        //XHL-20190510-AddEnd
+   
+}
\ No newline at end of file
diff --git a/scr/triggers/OpportunityLineItemTrigger.trigger-meta.xml b/scr/triggers/OpportunityLineItemTrigger.trigger-meta.xml
new file mode 100644
index 0000000..9972add
--- /dev/null
+++ b/scr/triggers/OpportunityLineItemTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/OpportunityProgressBarTrgiger.trigger b/scr/triggers/OpportunityProgressBarTrgiger.trigger
new file mode 100644
index 0000000..75a3fc9
--- /dev/null
+++ b/scr/triggers/OpportunityProgressBarTrgiger.trigger
@@ -0,0 +1,5 @@
+trigger OpportunityProgressBarTrgiger on Opportunity (before insert, before update, after insert, after update) {
+// if (Trigger.isBefore && Trigger.isUpdate) {
+//      OpportunityStageProgressBarUpdate.updateProgressBar(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap); 
+//    }
+}
\ No newline at end of file
diff --git a/scr/triggers/OpportunityProgressBarTrgiger.trigger-meta.xml b/scr/triggers/OpportunityProgressBarTrgiger.trigger-meta.xml
new file mode 100644
index 0000000..ef63ab9
--- /dev/null
+++ b/scr/triggers/OpportunityProgressBarTrgiger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>39.0</apiVersion>
+    <status>Inactive</status>
+</ApexTrigger>
diff --git a/scr/triggers/OpportunityTrigger.trigger b/scr/triggers/OpportunityTrigger.trigger
new file mode 100644
index 0000000..4997717
--- /dev/null
+++ b/scr/triggers/OpportunityTrigger.trigger
@@ -0,0 +1,170 @@
+trigger OpportunityTrigger on Opportunity (before insert, before update, after insert, after update) {
+    
+    if(Trigger.new[0].DealerIsOk__c == true && Trigger.new[0].CrossCooperativeDealer__c == null){
+        Trigger.new[0].addError('璇峰~鍐欏悎浣滃尯鍩熶唬鐞嗗晢');
+    }
+
+    if(StaticParameter.OpportunityTriggerIsUpdate){
+        StaticParameter.OpportunityTriggerIsUpdate = false;
+        return;
+    }
+    if(Trigger.new[0].RecordTypeId == System.Label.SSBD_Replacement){
+        if (Trigger.isBefore && Trigger.isUpdate) {
+            OpportunityStageProgressBarUpdate.updateProgressBar(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        if (Trigger.isBefore) {
+            OpportunityTriggerHandler.updateStageLimit(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap); 
+            OpportunityTriggerHandler.autoSet(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap); 
+        }
+
+        if (Trigger.isBefore && Trigger.isInsert) {
+            OpportunityTriggerHandler.setIsNew(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setPriceBook(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+
+        if (Trigger.isBefore && Trigger.isUpdate) {
+            OpportunityTriggerHandler.updateForDealer(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.dealerOpportunityApproval(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setPriceBook(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setReceiver(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setTextField(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.check(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+
+        }
+        
+        if (Trigger.isAfter && Trigger.isInsert) {
+            OpportunityTriggerHandler.setDealerGroup(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        
+        if (Trigger.isAfter && Trigger.isUpdate) {
+            OpportunityTriggerHandler.dealerOpportunityApproval2(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setOrderFields(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        
+        if (Trigger.isBefore && Trigger.isUpdate) {
+            SBG007TriggerHandler.SBG007OpportunityTrigger(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityStockAnswer.SummaryStockAnswerUpdate(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+
+
+
+
+
+    }else{
+
+        if (Trigger.isBefore && Trigger.isUpdate) {
+            OpportunityStageProgressBarUpdate.updateProgressBar(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+
+        if (Trigger.isBefore) {
+            OpportunityTriggerHandler.updateStageLimit(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap); 
+            OpportunityTriggerHandler.autoSet(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap); 
+        }
+        
+        if (Trigger.isBefore && Trigger.isInsert) {
+            OpportunityTriggerHandler.setIsNew(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setPriceBook(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        
+        if (Trigger.isBefore && Trigger.isUpdate) {
+            OpportunityTriggerHandler.updateForDealer(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.dealerOpportunityApproval(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setPriceBook(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setReceiver(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setTextField(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.check(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+
+        }
+        
+        if (Trigger.isAfter && Trigger.isInsert) {
+            OpportunityTriggerHandler.setDealerGroup(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        
+        if (Trigger.isAfter && Trigger.isUpdate) {
+            OpportunityTriggerHandler.dealerOpportunityApproval2(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityTriggerHandler.setOrderFields(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        
+        if (Trigger.isBefore && Trigger.isUpdate) {
+            SBG007TriggerHandler.SBG007OpportunityTrigger(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            OpportunityStockAnswer.SummaryStockAnswerUpdate(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            Integer i = 0;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+            i++;
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/OpportunityTrigger.trigger-meta.xml b/scr/triggers/OpportunityTrigger.trigger-meta.xml
new file mode 100644
index 0000000..9972add
--- /dev/null
+++ b/scr/triggers/OpportunityTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/OrderItemTrigger.trigger b/scr/triggers/OrderItemTrigger.trigger
new file mode 100644
index 0000000..6a60d4c
--- /dev/null
+++ b/scr/triggers/OrderItemTrigger.trigger
@@ -0,0 +1,11 @@
+trigger OrderItemTrigger on OrderItem (after insert,after update,before delete) {
+    OrderItemTriggerHandler.setProductConfig(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    if(Trigger.isAfter && Trigger.isInsert){
+        System.debug('insert');
+        OrderItemTriggerHandler.insSingleProduct(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if(Trigger.isBefore && Trigger.isDelete){
+        System.debug('delete');
+        OrderItemTriggerHandler.delSingleProduct(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/OrderItemTrigger.trigger-meta.xml b/scr/triggers/OrderItemTrigger.trigger-meta.xml
new file mode 100644
index 0000000..b2bad7c
--- /dev/null
+++ b/scr/triggers/OrderItemTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/OrderTrigger.trigger b/scr/triggers/OrderTrigger.trigger
new file mode 100644
index 0000000..e7b28ac
--- /dev/null
+++ b/scr/triggers/OrderTrigger.trigger
@@ -0,0 +1,46 @@
+trigger OrderTrigger on Order (before insert, before update, after insert, after update) {
+    
+    if (Trigger.isBefore && Trigger.isInsert) {
+        System.debug('@@@@@@@@@@@@@@!!!!!!!!!!!!!!!');
+        OrderTriggerHandler.setIsNew(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setPriceBook(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setTransferValue(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.check(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isInsert) {
+        OrderTriggerHandler.addItem(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.radiation(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,false); 
+        OrderTriggerHandler.setOpportunityCOMPO(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,true);
+        OrderTriggerHandler.updateOpportunity(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,false);
+    }
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        //OrderTriggerHandler.check(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        //Trigger.new[0].name = '123123';
+        OrderTriggerHandler.setApprover(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.updateForDealer(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.dealerOrderApproval(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.ProfitApproveCheck(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.BackToPreStatus(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setTransferValue(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setRecordTypeHidden(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.TradeMagCategoryCheck(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);        
+        OrderTriggerHandler.checkAdderss(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.liApprove(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.addressCopy(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        
+        OrderTriggerHandler.radiation(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,true);
+        OrderTriggerHandler.updateOpportunity(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,true);
+    }
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        SBG027TriggerHandler.SBG027OrderTrigger(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isUpdate) {
+        OrderTriggerHandler.setOpportunity(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setQuote(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.Cancellostcontrol(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.OppAutoClose(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setfile(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        OrderTriggerHandler.setOrderShare(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        //OrderTriggerHandler.Productconfigchange(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/OrderTrigger.trigger-meta.xml b/scr/triggers/OrderTrigger.trigger-meta.xml
new file mode 100644
index 0000000..9972add
--- /dev/null
+++ b/scr/triggers/OrderTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>33.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/ProRegister.trigger b/scr/triggers/ProRegister.trigger
new file mode 100644
index 0000000..1884103
--- /dev/null
+++ b/scr/triggers/ProRegister.trigger
@@ -0,0 +1,12 @@
+trigger ProRegister on Product_Register__c(after update , after insert, before insert, before update) {
+	/*鏇存柊浜у搧鍐呮渶鏂颁骇鍝佸湪娉ㄥ唽璇�
+	 1.鏍规嵁闇�瑕佹洿鏂扮殑浜у搧娉ㄥ唽璇佹壘鍑烘墍鏈夊搴旂殑浜у搧-娉ㄥ唽璇佸叧绯�
+	 2.鏍规嵁浜у搧-娉ㄥ唽璇佸叧绯绘壘鍑烘墍鏈夊搴旂殑浜у搧
+	 3.鏍规嵁浜у搧鎵惧嚭鍏舵墍闇�鏈�鏂颁骇鍝佹敞鍐岃瘉
+	*/
+    if (Trigger.isAfter && Trigger.isUpdate) {
+        ProRegisterHandler.updateProduct(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        //浜у搧闄嶇被
+        ProRegisterHandler.checkRegistervervaldatum(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/ProRegister.trigger-meta.xml b/scr/triggers/ProRegister.trigger-meta.xml
new file mode 100644
index 0000000..6205514
--- /dev/null
+++ b/scr/triggers/ProRegister.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/ProRegisterLink.trigger b/scr/triggers/ProRegisterLink.trigger
new file mode 100644
index 0000000..c0d6300
--- /dev/null
+++ b/scr/triggers/ProRegisterLink.trigger
@@ -0,0 +1,14 @@
+trigger ProRegisterLink on Product_Register_Link__c(after insert, after update,after delete) {
+
+    if (Trigger.isAfter && Trigger.isInsert) {
+        ProRegisterLinkHandler.updateProduct(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,'1');
+    }
+    
+    if (Trigger.isAfter && Trigger.isUpdate) {
+    	ProRegisterLinkHandler.updateProduct(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,'1');
+    }
+    
+    if (Trigger.isAfter && Trigger.isDelete) {
+    	ProRegisterLinkHandler.updateProduct(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,'2');
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/ProRegisterLink.trigger-meta.xml b/scr/triggers/ProRegisterLink.trigger-meta.xml
new file mode 100644
index 0000000..6205514
--- /dev/null
+++ b/scr/triggers/ProRegisterLink.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>41.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/Product2Triggrt.trigger b/scr/triggers/Product2Triggrt.trigger
new file mode 100644
index 0000000..7918cec
--- /dev/null
+++ b/scr/triggers/Product2Triggrt.trigger
@@ -0,0 +1,9 @@
+trigger Product2Triggrt on Product2 (after insert, after update , before insert, before update) {
+    if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate))
+    {
+    	Product2TriggerHandler.upsertProductSearch(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+    if(trigger.isBefore && (trigger.isInsert || trigger.isUpdate)){
+    	Product2TriggerHandler.checkProduct2Level(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/Product2Triggrt.trigger-meta.xml b/scr/triggers/Product2Triggrt.trigger-meta.xml
new file mode 100644
index 0000000..fa25206
--- /dev/null
+++ b/scr/triggers/Product2Triggrt.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/QuoteLineItemTrigger.trigger b/scr/triggers/QuoteLineItemTrigger.trigger
new file mode 100644
index 0000000..1ae04f6
--- /dev/null
+++ b/scr/triggers/QuoteLineItemTrigger.trigger
@@ -0,0 +1,11 @@
+trigger QuoteLineItemTrigger on QuoteLineItem (before insert,after insert,before update,after update,before delete,after delete) {
+    //XHL-20190513-AddStart
+
+    
+        if (Trigger.isAfter && Trigger.isInsert) {
+            QuoteLineItemTriggerHandler.SetOpportunityLineItem(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+    
+    //XHL-20190513-AddEnd
+
+}
\ No newline at end of file
diff --git a/scr/triggers/QuoteLineItemTrigger.trigger-meta.xml b/scr/triggers/QuoteLineItemTrigger.trigger-meta.xml
new file mode 100644
index 0000000..b2bad7c
--- /dev/null
+++ b/scr/triggers/QuoteLineItemTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/QuoteTrigger.trigger b/scr/triggers/QuoteTrigger.trigger
new file mode 100644
index 0000000..667734a
--- /dev/null
+++ b/scr/triggers/QuoteTrigger.trigger
@@ -0,0 +1,17 @@
+trigger QuoteTrigger on Quote (after insert,after update,before update) {
+
+        if (Trigger.isAfter && Trigger.isInsert) {
+            QuoteTriggerHandler.setDealerGroup(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        if(Trigger.isAfter && trigger.isUpdate){
+            QuoteTriggerHandler.setPaymetTerms(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            QuoteTriggerHandler.check(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+        if(Trigger.isBefore && Trigger.isUpdate){
+            QuoteTriggerHandler.setDontSingleProductCode(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+            
+
+        }
+    
+    
+}
\ No newline at end of file
diff --git a/scr/triggers/QuoteTrigger.trigger-meta.xml b/scr/triggers/QuoteTrigger.trigger-meta.xml
new file mode 100644
index 0000000..fa25206
--- /dev/null
+++ b/scr/triggers/QuoteTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>34.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/RepairDetailsTrigger.trigger b/scr/triggers/RepairDetailsTrigger.trigger
new file mode 100644
index 0000000..8b55506
--- /dev/null
+++ b/scr/triggers/RepairDetailsTrigger.trigger
@@ -0,0 +1,5 @@
+trigger RepairDetailsTrigger on RepairDetails__c (before insert) {
+	if (Trigger.isBefore && Trigger.isInsert) {
+		RepairDetailsTriggerHandler.setNumber(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+	}
+}
\ No newline at end of file
diff --git a/scr/triggers/RepairDetailsTrigger.trigger-meta.xml b/scr/triggers/RepairDetailsTrigger.trigger-meta.xml
new file mode 100644
index 0000000..b2bad7c
--- /dev/null
+++ b/scr/triggers/RepairDetailsTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/RepairTrigger.trigger b/scr/triggers/RepairTrigger.trigger
new file mode 100644
index 0000000..5b529ba
--- /dev/null
+++ b/scr/triggers/RepairTrigger.trigger
@@ -0,0 +1,5 @@
+trigger RepairTrigger on Repair__c (before insert, before update) {
+     if (Trigger.isBefore ) {
+        RepairTriggerHandler.setdate(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        }
+}
\ No newline at end of file
diff --git a/scr/triggers/RepairTrigger.trigger-meta.xml b/scr/triggers/RepairTrigger.trigger-meta.xml
new file mode 100644
index 0000000..f89680f
--- /dev/null
+++ b/scr/triggers/RepairTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>45.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/SWOTrigger.trigger b/scr/triggers/SWOTrigger.trigger
new file mode 100644
index 0000000..397c7da
--- /dev/null
+++ b/scr/triggers/SWOTrigger.trigger
@@ -0,0 +1,8 @@
+trigger SWOTrigger on SWO__c (before insert,after insert,before update) {
+	if(trigger.isBefore){
+		SWOTriggerHandler.setDateTimeSendEmail(trigger.new, trigger.newMap, trigger.old, trigger.oldMap);
+	}
+	if(trigger.isAfter && trigger.isInsert){
+		SWOTriggerHandler.sendEmail(trigger.new, trigger.newMap, trigger.old, trigger.oldMap);
+	}
+}
\ No newline at end of file
diff --git a/scr/triggers/SWOTrigger.trigger-meta.xml b/scr/triggers/SWOTrigger.trigger-meta.xml
new file mode 100644
index 0000000..c46c9f8
--- /dev/null
+++ b/scr/triggers/SWOTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>51.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/ServiceSummaryTrigger.trigger b/scr/triggers/ServiceSummaryTrigger.trigger
new file mode 100644
index 0000000..1f06795
--- /dev/null
+++ b/scr/triggers/ServiceSummaryTrigger.trigger
@@ -0,0 +1,11 @@
+trigger ServiceSummaryTrigger on ServiceSummary__c (before Insert,after Insert,after update,before update) {
+
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        ServiceSummaryHandler.CreateCase(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);    
+    }
+
+    if (Trigger.isAfter && Trigger.isInsert) {
+        ServiceSummaryHandler.CreateCase(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+
+}
\ No newline at end of file
diff --git a/scr/triggers/ServiceSummaryTrigger.trigger-meta.xml b/scr/triggers/ServiceSummaryTrigger.trigger-meta.xml
new file mode 100644
index 0000000..c46c9f8
--- /dev/null
+++ b/scr/triggers/ServiceSummaryTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>51.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/TaskTrigger.trigger b/scr/triggers/TaskTrigger.trigger
new file mode 100644
index 0000000..f0f8f6d
--- /dev/null
+++ b/scr/triggers/TaskTrigger.trigger
@@ -0,0 +1,10 @@
+trigger TaskTrigger on Task (before Insert,after Insert,after update,before update)  {
+
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        TaskTriggerHandler.CreateCase(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);    
+    }
+
+    if (Trigger.isAfter && Trigger.isInsert) {
+        TaskTriggerHandler.CreateCase(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/TaskTrigger.trigger-meta.xml b/scr/triggers/TaskTrigger.trigger-meta.xml
new file mode 100644
index 0000000..23257e1
--- /dev/null
+++ b/scr/triggers/TaskTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>52.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/UpdateLogisticsInformation.trigger b/scr/triggers/UpdateLogisticsInformation.trigger
new file mode 100644
index 0000000..0952198
--- /dev/null
+++ b/scr/triggers/UpdateLogisticsInformation.trigger
@@ -0,0 +1,11 @@
+trigger UpdateLogisticsInformation on Loaner_Express__c (after update,after insert) {
+	if(Trigger.isAfter && Trigger.isUpdate){
+		LoanerExpressTriggerHandler.updateExpress(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+		LoanerExpressTriggerHandler.emailDate(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+		LoanerExpressTriggerHandler.updateName(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+	}
+
+    if(Trigger.isAfter && Trigger.isInsert){
+    	 LoanerExpressTriggerHandler.getApprover(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/UpdateLogisticsInformation.trigger-meta.xml b/scr/triggers/UpdateLogisticsInformation.trigger-meta.xml
new file mode 100644
index 0000000..b2bad7c
--- /dev/null
+++ b/scr/triggers/UpdateLogisticsInformation.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/UserFaultInfoTrigger.trigger b/scr/triggers/UserFaultInfoTrigger.trigger
new file mode 100644
index 0000000..57fa782
--- /dev/null
+++ b/scr/triggers/UserFaultInfoTrigger.trigger
@@ -0,0 +1,14 @@
+trigger UserFaultInfoTrigger on User_FaultInfo__c (after insert,before update,before insert) {
+
+    if(Trigger.isBefore && Trigger.isUpdate){
+        UserFaultInfoHandler.UserFaultInfoWorkingHoursAssignment(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,'');
+        UserFaultInfoHandler.ASSIGNEDTOChange(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isBefore && Trigger.isInsert) {
+        UserFaultInfoHandler.BeforeSendEmail(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if(Trigger.isAfter && Trigger.isInsert){
+       UserFaultInfoHandler.UserFaultInfoWorkingHoursAssignment(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap,'insert');
+       UserFaultInfoHandler.ASSIGNEDTOChange(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/UserFaultInfoTrigger.trigger-meta.xml b/scr/triggers/UserFaultInfoTrigger.trigger-meta.xml
new file mode 100644
index 0000000..8f932fc
--- /dev/null
+++ b/scr/triggers/UserFaultInfoTrigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>49.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/User_Violations.trigger b/scr/triggers/User_Violations.trigger
new file mode 100644
index 0000000..0553266
--- /dev/null
+++ b/scr/triggers/User_Violations.trigger
@@ -0,0 +1,5 @@
+trigger User_Violations on User_Violations__c (after update) {
+	if(Trigger.isAfter && Trigger.isUpdate){
+		UserViolationsTriggerHandler.setOK(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+	}
+}
\ No newline at end of file
diff --git a/scr/triggers/User_Violations.trigger-meta.xml b/scr/triggers/User_Violations.trigger-meta.xml
new file mode 100644
index 0000000..b2bad7c
--- /dev/null
+++ b/scr/triggers/User_Violations.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>36.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger b/scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger
new file mode 100644
index 0000000..36decfb
--- /dev/null
+++ b/scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger
@@ -0,0 +1,29 @@
+trigger chatter_answers_question_escalation_to_case_trigger on Question (after update) {
+    for (Question q: Trigger.new) {
+        try {
+            if (q.Priority == 'high' && (q.Cases == null || q.Cases.size() == 0) && Trigger.oldMap.get(q.id).Priority != 'high') {
+                q = [select Id, Title, Body, CommunityId, createdById, createdBy.AccountId, createdBy.ContactId from Question where Id = :q.Id];
+                Case newCase = new Case(Origin='Chatter Answers', OwnerId=q.CreatedById, QuestionId=q.Id, CommunityId=q.CommunityId, Subject=q.Title, Description=q.Body, AccountId=q.CreatedBy.AccountId, ContactId=q.CreatedBy.ContactId);
+                insert newCase;
+            }
+        } catch (Exception e) {
+            String subjectText = 'Case Escalation exception in site ' + Site.getName();
+            String bodyText = 'Case Escalation on Question having ID: ' + q.Id + ' has failed with the following message: ' + e.getMessage() +
+                '\n\nStacktrace: ' + e.getStacktraceString();
+
+            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
+            String[] toAddresses = new String[] { Site.getAdminEmail() };
+
+            mail.setReplyTo('no-reply@salesforce.com');
+            mail.setSenderDisplayName('Salesforce Chatter Answers User');
+
+            // The default sender is the portal user causing this trigger to run, to change this, set an organization-wide address for
+            // the portal user profile, and set the ID in the following line.
+            // mail.setOrgWideEmailAddressId(orgWideEmailAddressId);
+            mail.setToAddresses(toAddresses);
+            mail.setSubject(subjectText);
+            mail.setPlainTextBody(bodyText);
+            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
+        }
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger-meta.xml b/scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger-meta.xml
new file mode 100644
index 0000000..1257ef6
--- /dev/null
+++ b/scr/triggers/chatter_answers_question_escalation_to_case_trigger.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>27.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/loanerAppDetStatusUp.trigger b/scr/triggers/loanerAppDetStatusUp.trigger
new file mode 100644
index 0000000..26ec15b
--- /dev/null
+++ b/scr/triggers/loanerAppDetStatusUp.trigger
@@ -0,0 +1,21 @@
+trigger loanerAppDetStatusUp on loaner_application_detail__c (after insert,after delete,after update) {
+    /*if (!LoanerAppDetailTriggerHandler.runTrigger) {
+        return;
+    }*/
+    Set<String> loanerAppSet = new Set<String>();
+    Set<String> loanerSet = new Set<String>();
+    if (Trigger.isAfter && Trigger.isDelete) {
+        LoanerAppDetailTriggerHandler.delStatusUp(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+    if (Trigger.isAfter && Trigger.isInsert) {
+        LoanerAppDetailTriggerHandler.insStatusUp(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+        LoanerAppDetailTriggerHandler.setUser(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+
+    if(Trigger.isAfter && Trigger.isUpdate){
+        LoanerAppDetailTriggerHandler.upsertCheckLost(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+        LoanerAppDetailTriggerHandler.upsertDiscarded(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+        LoanerAppDetailTriggerHandler.notReceivingNum(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+        LoanerAppDetailTriggerHandler.emailDate(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/loanerAppDetStatusUp.trigger-meta.xml b/scr/triggers/loanerAppDetStatusUp.trigger-meta.xml
new file mode 100644
index 0000000..80455b5
--- /dev/null
+++ b/scr/triggers/loanerAppDetStatusUp.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>42.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/loanerAppStatusUp.trigger b/scr/triggers/loanerAppStatusUp.trigger
new file mode 100644
index 0000000..44c06d6
--- /dev/null
+++ b/scr/triggers/loanerAppStatusUp.trigger
@@ -0,0 +1,44 @@
+trigger loanerAppStatusUp on loaner_application__c (before insert,before update, after update) {
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        loanerAppTriggerHandler.setSubmitUser(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if (Trigger.isBefore && Trigger.isInsert) {
+        loanerAppTriggerHandler.setRemind_Date(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        //loanerAppTriggerHandler.changeFollowOpp(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    }
+    
+    if (Trigger.isBefore && Trigger.isUpdate) {
+        
+        loanerAppTriggerHandler.setApprover(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    } 
+    
+    if (Trigger.isBefore && Trigger.isUpdate) {
+         loanerAppTriggerHandler.changeFollowOpp(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+        loanerAppTriggerHandler.BackToPreStatus(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        // 銆岃浆鍊熸牱鏈虹敵璇峰崟銆嶆壒鍑嗗悗 || 閿�鍞媴褰撳繀椤诲厛鍋氭牱鏈哄垎閰嶅悗鍐嶅鎵�
+        loanerAppTriggerHandler.GoToNextStatusHead(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        loanerAppTriggerHandler.setRemind_Date(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        loanerAppTriggerHandler.rental_Datejudgment(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+        loanerAppTriggerHandler.serviceApproval(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    } 
+    if (Trigger.isAfter && Trigger.isUpdate) {
+        loanerAppTriggerHandler.transferBack(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    // 銆屾牱鏈虹敵璇峰崟銆嶆彁浜ゅ悗
+        String sapResult = loanerAppTriggerHandler.upsertAssetSubmit(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    // 銆屾牱鏈虹敵璇峰崟銆嶆壒鍑嗗悗
+        loanerAppTriggerHandler.upsertAssetApproval(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    // 銆屾牱鏈虹敵璇峰崟銆嶉┏鍥炲悗
+        loanerAppTriggerHandler.upsertAssetCancle(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    // 銆屾牱鏈虹敵璇峰崟銆嶈皟鍥炲悗
+        loanerAppTriggerHandler.upsertAssetcallback(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+    // 銆屾牱鏈虹敵璇峰崟銆嶅彇娑堝悗
+        loanerAppTriggerHandler.cancelLoanerApplication(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+        // 銆岃浆鍊熸牱鏈虹敵璇峰崟銆嶆壒鍑嗗悗鏄庣粏鏇存柊
+        //loanerAppTriggerHandler.GoToNextStatusDet(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);
+    }
+    if(Trigger.isAfter && Trigger.isUpdate){
+        loanerAppTriggerHandler.emailDate(trigger.new,trigger.newMap,trigger.old,trigger.oldMap);
+
+      
+    }
+}
\ No newline at end of file
diff --git a/scr/triggers/loanerAppStatusUp.trigger-meta.xml b/scr/triggers/loanerAppStatusUp.trigger-meta.xml
new file mode 100644
index 0000000..80455b5
--- /dev/null
+++ b/scr/triggers/loanerAppStatusUp.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>42.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>
diff --git a/scr/triggers/loanerchangerecord.trigger b/scr/triggers/loanerchangerecord.trigger
new file mode 100644
index 0000000..073f1e6
--- /dev/null
+++ b/scr/triggers/loanerchangerecord.trigger
@@ -0,0 +1,5 @@
+trigger loanerchangerecord on LoanerChangeRecord__c (after update,after insert) {
+  if(Trigger.isAfter && Trigger.isUpdate){    
+     loanerChangeRecordTriggerHandler.SetAssetStatus(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap);    
+  }
+}
\ No newline at end of file
diff --git a/scr/triggers/loanerchangerecord.trigger-meta.xml b/scr/triggers/loanerchangerecord.trigger-meta.xml
new file mode 100644
index 0000000..0f47aa0
--- /dev/null
+++ b/scr/triggers/loanerchangerecord.trigger-meta.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
+    <apiVersion>44.0</apiVersion>
+    <status>Active</status>
+</ApexTrigger>

--
Gitblit v1.9.1