package com.leanwo.activiti.delegate.business;

import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leanwo.activiti.config.EmailConfiguration;
import com.leanwo.activiti.delegate.base.AssetServerService;
import com.leanwo.activiti.dto.BaseObjectResponse;
import com.leanwo.activiti.service.base.impl.ProdogServer;
import com.leanwo.activiti.service.base.impl.UserPreference;
import com.leanwo.activiti.util.CloseableUtil;
import com.leanwo.activiti.util.SpringUtil;

public class AssetLabelPrintCheckReportDelegate implements JavaDelegate{

    private static Logger logger = LoggerFactory.getLogger(AssetLabelPrintCheckReportDelegate.class);
    
	@Override
	public void execute(DelegateExecution delegateExecution) {
		Long recordId = (Long) delegateExecution.getVariable(UserPreference.RECORD_ID);
        Long accountId = (Long) delegateExecution.getVariable(UserPreference.ACCOUNT_ID);
		

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            DataSource dataSource = SpringUtil.getBean("dataSource" + accountId);
            connection = dataSource.getConnection();
            String sql = "SELECT "
            		+ " alpc.id as id,"
            		+ " bu.id as userId,"
            		+ " bu.name as assetManagerName,"
            		+ " bu.email as assetManagerEmail,"
            		+ " alpc.name as documentName,"
            		+ " alpc.documentNo as documentNo,"
            		+ " client.name AS clientName,"
            		+ " organization.name AS organizationName,"
            		+ " room.name as roomName"
            		+ " FROM Ass_AssetLabelPrintCheck AS alpc"
            		+ " LEFT JOIN BASE_USER bu on bu.id = alpc.pasteResponsibleUserId"
            		+ " LEFT JOIN Base_Client AS client on client.id = alpc.clientId"
            		+ " LEFT JOIN Base_Organization AS organization on organization.id = alpc.organizationId"
            		+ " LEFT JOIN Ass_Room AS room on room.id = alpc.roomId"
            		+ " WHERE alpc.id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1, recordId);
            resultSet = preparedStatement.executeQuery();
            Long id = null, userId = null;
            String userName = null, email = null, clientName = null, organizationName = null, roomName = null;
            while(resultSet.next()){
            	id = resultSet.getLong("id");
                userId = resultSet.getLong("userId");
                if(resultSet.wasNull()) {
                	userId = null;
                }
                userName = resultSet.getString("assetManagerName");
                email = resultSet.getString("assetManagerEmail");
                
                
                clientName = resultSet.getString("clientName");
                organizationName = resultSet.getString("organizationName");
                roomName = resultSet.getString("roomName");
            }

            if(userId != null) {
                delegateExecution.setVariable("userId1", userId);
                delegateExecution.setVariable("userName1", userName);
                delegateExecution.setVariable("to1", email);
                
                EmailConfiguration emailConfiguration = (EmailConfiguration) SpringUtil.getBean("emailConfiguration");
                delegateExecution.setVariable("from1", emailConfiguration.getMailServerDefaultFrom());
                
                delegateExecution.setVariable("subject1", "固定资产管理系统需要您使用A4打印机打印新增的资产卡片，请登录系统完成相关操作。");
                String content = String.format("尊敬的%s您好，\r\n固定资产管理系统需要您给公司：%s，部门：%s，营业场所：%s，使用A4打印机打印新增的资产卡片，请登录系统完成相关操作。", 
                		userName,
                		clientName,
                		organizationName,
                		roomName);
                		
                delegateExecution.setVariable("content1", content);
                
                delegateExecution.setVariable(UserPreference.APPROVE_TITLE, "使用A4打印机打印新增的资产卡片");
                delegateExecution.setVariable(UserPreference.APPROVE_CONTENT, content);
            }
            
            connection.commit();
        } catch (SQLException e) {
            logger.error("", e);
        }finally{
            CloseableUtil.close(resultSet, preparedStatement, connection);
        }
            
            
        AssetServerService assetServerService = (AssetServerService) SpringUtil.getSingleBean(AssetServerService.class);
        BaseObjectResponse<String> baseObjectResponse = assetServerService.generateReport(recordId);
		if(baseObjectResponse.getErrorCode() ==0) {
			String url = "/#/desktop/pdf-print?pdfSrc=" + URLEncoder.encode(baseObjectResponse.getData());
			delegateExecution.setVariable("PDF_REPORT", url);
		}
        
	}

}
