 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 ApproverLoginDelegate implements JavaDelegate{
    
    private static Logger logger = LoggerFactory.getLogger(ApproverLoginDelegate.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;
        PreparedStatement preparedStatement2 = null;
        PreparedStatement preparedStatement3 = null;
        PreparedStatement preparedStatement4 = null;
        ResultSet resultSet = null;
        ResultSet resultSet2 = null;
        ResultSet resultSet3 = null;
        ResultSet resultSet4 = null;
        try {
            DataSource dataSource = SpringUtil.getBean("dataSource" + accountId);
            connection = dataSource.getConnection();
            String sql = "SELECT top 1 id, name, loginName, email FROM BASE_USER WHERE loginProcessInstanceId IS NULL AND email IS NOT NULL ORDER BY id";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            Long userId = null;
            String userName = null, loginName = null, email = null;
            while(resultSet.next()){
                userId = resultSet.getLong("id");
                if(resultSet.wasNull()) {
                	userId = null;
                }
                userName = resultSet.getString("name");
                loginName = resultSet.getString("loginName");
                email = resultSet.getString("email");
            }

            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 = "尊敬的" + userName + "您好，\r\n您的固定资产管理系统账号已经开通，请点击下面的网址，完成登录和培训的操作。";
                delegateExecution.setVariable("content", content);
                //delegateExecution.setVariable("from", email);
                
                delegateExecution.setVariable(UserPreference.APPROVE_TITLE, "登录指引");
                delegateExecution.setVariable(UserPreference.APPROVE_CONTENT, "确认隐私说明，审批培训，重置密码");
            }
            
            
            if(userId != null) {
                sql = "update BASE_USER set loginProcessInstanceId = ? where id = ?";
                preparedStatement1 = connection.prepareStatement(sql);
                preparedStatement1.setString(1, delegateExecution.getProcessDefinitionId());
                preparedStatement1.setLong(2, userId);
                int count = preparedStatement1.executeUpdate();
                if(count != 1) {
                    throw new ServerException("更新用户" + userId + "的loginProcessInstanceId属性失败。");
                }
            }
            
            
            // 是否是部门经理
            boolean isDepartmentManager = false;
            
            sql = "SELECT count(*) as count1 FROM Ass_ClientOrganizationRoomUser where userId = ?";
            preparedStatement2 = connection.prepareStatement(sql);
            preparedStatement2.setLong(1, userId);
            resultSet2 = preparedStatement2.executeQuery();
    		while(resultSet2.next()){
    			int count = resultSet2.getInt(1);
    			if(count > 0) {
    				isDepartmentManager = true;
    			}
            }
    		delegateExecution.setVariable("isDepartmentManager", isDepartmentManager);
    		
    		
            // 是否是资产管理员
            boolean isAssetManager = false;
            sql = "SELECT count(*) as count1 FROM Ass_ClientOrganizationRoomUser where assetManagerId = ?";
            preparedStatement3 = connection.prepareStatement(sql);
            preparedStatement3.setLong(1, userId);
            resultSet3 = preparedStatement3.executeQuery();
    		while(resultSet3.next()){
    			int count = resultSet3.getInt(1);
    			if(count > 0) {
    				isAssetManager = true;
    			}
            }
    		delegateExecution.setVariable("isAssetManager", isAssetManager);
            

            // 是否是审批人
            boolean isApprover = false;
            sql = "SELECT "
            		+ "(SELECT COUNT(*) FROM Base_RegionApproval WHERE bfManagerId = ? OR regionIEManagerId = ? OR regionControllerId = ? OR regionManagerId = ?) AS COUNT?, "
            		+ "(SELECT COUNT(*) FROM Base_DistrictApproval WHERE bfManagerId = ? OR districtIEManagerId = ? OR financeControllerId = ? OR districtManagerId = ?) AS COUNT2, "
            		+ "(SELECT COUNT(*) FROM Base_CountryApproval WHERE areaId = ? OR bfManagerId = ? OR areaIEManagerId = ? OR financeManagerId = ? OR managerId = ?) AS COUNT3, "
            		+ "(SELECT COUNT(*) FROM Base_FunctionalManagerApproval WHERE deptId = ? OR areaId = ? OR areaApproverId =? OR districtApproverId = ?) AS COUNT4";
            sql = sql.replace("?", userId.toString());
            preparedStatement4 = connection.prepareStatement(sql);
            resultSet4 = preparedStatement4.executeQuery();
    		while(resultSet4.next()){
    			int count1 = resultSet4.getInt(1);
    			int count2 = resultSet4.getInt(2);
    			int count3 = resultSet4.getInt(3);
    			int count4 = resultSet4.getInt(4);
    			if((count1 + count2 + count3 + count4) > 0) {
    				isApprover = true;
    			}
            }
    		delegateExecution.setVariable("isApprover", isApprover);

            connection.commit();
        } catch (SQLException e) {
            logger.error("", e);
        }finally{
            CloseableUtil.close(resultSet, resultSet2, resultSet3, resultSet4,
            		preparedStatement, preparedStatement1, preparedStatement2, preparedStatement3, preparedStatement4,
            		connection);
        }
    }
}
