 package com.leanwo.activiti.delegate.business;

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.exception.ServerException;
import com.leanwo.activiti.service.base.impl.UserPreference;
import com.leanwo.activiti.util.CloseableUtil;
import com.leanwo.activiti.util.SpringUtil;

/**
 * 登录的时候填充资产管理员
 * @author YangZhiJie
 * @date 2022/07/21
 */
public class FillAssetManagerLoginDelegate implements JavaDelegate{
    
    private static Logger logger = LoggerFactory.getLogger(FillAssetManagerLoginDelegate.class);
    
    /* (non-Javadoc)
     * @see org.activiti.engine.delegate.JavaDelegate#execute(org.activiti.engine.delegate.DelegateExecution)
     */
    @Override
    public void execute(DelegateExecution delegateExecution) {
        String tenantId = delegateExecution.getTenantId();
        Long accountId = (Long) delegateExecution.getVariable(UserPreference.ACCOUNT_ID);
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        PreparedStatement preparedStatement1 = null;
        ResultSet resultSet = null;
        try {
            DataSource dataSource = SpringUtil.getBean("dataSource" + accountId);
            connection = dataSource.getConnection();
            String sql = "SELECT TOP 1 coru.id AS id, deptManager.id AS userId, deptManager.name as deptManagerName, deptManager.email AS deptManagerEmail, "
            		+ "client.name AS clientName, organization.name AS organizationName, room.name as roomName FROM Ass_ClientOrganizationRoomUser AS coru "
            		+ "LEFT JOIN Base_User AS deptManager on deptManager.id = coru.userId "
            		+ "LEFT JOIN Base_Client AS client on client.id = coru.clientId "
            		+ "LEFT JOIN Base_Organization AS organization on organization.id = coru.organizationId "
            		+ "LEFT JOIN Ass_Room AS room on room.id = coru.roomId "
            		+ "WHERE coru.assetManagerId is null AND deptManager.id is not null AND deptManager.email is not null "
            		+ "AND coru.processInstanceId IS NULL order by coru.id asc";
            preparedStatement = connection.prepareStatement(sql);
            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("deptManagerName");
                email = resultSet.getString("deptManagerEmail");
                clientName = resultSet.getString("clientName");
                organizationName = resultSet.getString("organizationName");
                roomName = resultSet.getString("roomName");
            }

            if(userId != null) {
                delegateExecution.setVariable("userId", userId);
                delegateExecution.setVariable("userName", userName);
                delegateExecution.setVariable("to", email);
                
                EmailConfiguration emailConfiguration = (EmailConfiguration) SpringUtil.getBean("emailConfiguration");
                delegateExecution.setVariable("from", emailConfiguration.getMailServerDefaultFrom());
                
                delegateExecution.setVariable("subject", "固定资产管理系统需要您分配营业场所资产管理员，请登录系统完成资产管理员的分配操作。");
                String content = String.format("尊敬的%s您好，\r\n固定资产管理系统需要您给公司：%s，部门：%s，营业场所：%s，分配资产管理员，请登录系统完成分配操作。", 
                		userName,
                		clientName,
                		organizationName,
                		roomName);
                		
                delegateExecution.setVariable("content", content);
                
                delegateExecution.setVariable(UserPreference.APPROVE_TITLE, "分配营业场所资产管理员");
                delegateExecution.setVariable(UserPreference.APPROVE_CONTENT, content);
            }
            
            if(userId != null) {
                sql = "update Ass_ClientOrganizationRoomUser set processInstanceId = ? where userId = ?";
                preparedStatement1 = connection.prepareStatement(sql);
                preparedStatement1.setString(1, delegateExecution.getProcessDefinitionId());
                preparedStatement1.setLong(2, userId);
                int count = preparedStatement1.executeUpdate();
                if(count < 1) {
                    throw new ServerException("更新Ass_ClientOrganizationRoomUser(userId = " + userId + ")的processInstanceId属性失败。");
                }
            }
            
            connection.commit();
        } catch (SQLException e) {
            logger.error("", e);
        }finally{
            CloseableUtil.close(resultSet, preparedStatement, preparedStatement1, connection);
        }
    }
}
