public with sharing class ChangeDealerApprovalController {

	public String estimateId { get; private set; }

	public Maintenance_Contract_Estimate__c estimate { get; set; }

	public List<SelectOption> etSelectOptions { get; private set; }

	public Boolean submitErrorMsg { get; set; }

    public Boolean getApprovalButDisabled() {
        if (String.isBlank(this.estimate.Change_Dealer_Approval__c) == false
                && this.estimate.Change_Dealer_Approval__c != '批准'
                && this.estimate.Change_Dealer_Approval__c != '未批准') {
            return true;
        }
        return false;
    }

	public ChangeDealerApprovalController() {
		this.estimateId = ApexPages.currentPage().getParameters().get('eid');
		
		etSelectOptions = new List<SelectOption>();
	    etSelectOptions.add(new SelectOption('医院', '医院'));
	    etSelectOptions.add(new SelectOption('经销商', '经销商'));
	}

	public void init() {
		this.submitErrorMsg = false;
		if (String.isBlank(this.estimateId)) {
			return ;
		}
		setThisEstimate();
		if (String.isBlank(this.estimate.Change_Dealer_Approval__c)
			|| this.estimate.Change_Dealer_Approval__c == '未批准') {
			this.estimate.Changed_Estimate_Target__c = this.estimate.Estimate_Target__c;
			this.estimate.Changed_Dealer__c = this.estimate.Dealer__c;
		}
	}

	public PageReference submitApproval() {
		Savepoint sp = Database.setSavepoint();
		this.submitErrorMsg = false;
		try {
			this.estimate.Change_Dealer_Approval__c = '申请中';
			if (this.estimate.Changed_Estimate_Target__c == '医院') {
				this.estimate.Changed_Dealer__c = null;
			}
			update estimate;
			Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
	        psr.setObjectId(this.estimate.Id);
	        Approval.ProcessResult submitResult = Approval.process(psr);
	    } catch (Exception ex) {
            Database.rollback(sp);
            this.estimate.Change_Dealer_Approval__c = null;
            this.submitErrorMsg = true;
            ApexPages.addMessages(ex);
        }

		return null;
	}

	private void setThisEstimate() {
		this.estimate = [SELECT Id, Estimate_Target__c, Dealer__c, Changed_Estimate_Target__c, 
								Changed_Dealer__c, Change_Dealer_Approval__c
                         FROM Maintenance_Contract_Estimate__c WHERE Id = :this.estimateId];
	}
}